Debian Codegraph @

tests/test_v1/test_cte.py

raw
1 from unittest import SkipTest
2
3 from django.db.models import IntegerField, TextField
4 from django.db.models.aggregates import Count, Max, Min, Sum
5 from django.db.models.expressions import (
6 Exists, ExpressionWrapper, F, OuterRef, Subquery,
7 )
8 from django.db.models.sql.constants import LOUTER
9 from django.test import TestCase
10
11 from django_cte import With
12 from django_cte import CTEManager
13
14 from .models import Order, Region, User
15
16 int_field = IntegerField()
17 text_field = TextField()
18
19
20 class TestCTE(TestCase):
21
22 def test_simple_cte_query(self):
23 cte = With(
24 Order.objects
25 .values("region_id")
26 .annotate(total=Sum("amount"))
27 )
28
29 orders = (
30 # FROM orders INNER JOIN cte ON orders.region_id = cte.region_id
31 cte.join(Order, region=cte.col.region_id)
32
33 # Add `WITH ...` before `SELECT ... FROM orders ...`
34 .with_cte(cte)
35
36 # Annotate each Order with a "region_total"
37 .annotate(region_total=cte.col.total)
38 )
39 print(orders.query)
40
41 data = sorted((o.amount, o.region_id, o.region_total) for o in orders)
42 self.assertEqual(data, [
43 (1, 'moon', 6),
44 (2, 'moon', 6),
45 (3, 'moon', 6),
46 (10, 'mercury', 33),
47 (10, 'proxima centauri b', 33),
48 (11, 'mercury', 33),
49 (11, 'proxima centauri b', 33),
50 (12, 'mercury', 33),
51 (12, 'proxima centauri b', 33),
52 (20, 'venus', 86),
53 (21, 'venus', 86),
54 (22, 'venus', 86),
55 (23, 'venus', 86),
56 (30, 'earth', 126),
57 (31, 'earth', 126),
58 (32, 'earth', 126),
59 (33, 'earth', 126),
60 (40, 'mars', 123),
61 (41, 'mars', 123),
62 (42, 'mars', 123),
63 (1000, 'sun', 1000),
64 (2000, 'proxima centauri', 2000),
65 ])
66
67 def test_cte_name_escape(self):
68 totals = With(
69 Order.objects
70 .filter(region__parent="sun")
71 .values("region_id")
72 .annotate(total=Sum("amount")),
73 name="mixedCaseCTEName"
74 )
75 orders = (
76 totals
77 .join(Order, region=totals.col.region_id)
78 .with_cte(totals)
79 .annotate(region_total=totals.col.total)
80 .order_by("amount")
81 )
82 self.assertTrue(
83 str(orders.query).startswith('WITH RECURSIVE "mixedCaseCTEName"'))
84
85 def test_cte_queryset(self):
86 sub_totals = With(
87 Order.objects
88 .values(region_parent=F("region__parent_id"))
89 .annotate(total=Sum("amount")),
90 )
91 regions = (
92 Region.objects.all()
93 .with_cte(sub_totals)
94 .annotate(
95 child_regions_total=Subquery(
96 sub_totals.queryset()
97 .filter(region_parent=OuterRef("name"))
98 .values("total"),
99 ),
100 )
101 .order_by("name")
102 )
103 print(regions.query)
104
105 data = [(r.name, r.child_regions_total) for r in regions]
106 self.assertEqual(data, [
107 ("bernard's star", None),
108 ('deimos', None),
109 ('earth', 6),
110 ('mars', None),
111 ('mercury', None),
112 ('moon', None),
113 ('phobos', None),
114 ('proxima centauri', 33),
115 ('proxima centauri b', None),
116 ('sun', 368),
117 ('venus', None)
118 ])
119
120 def test_cte_queryset_with_model_result(self):
121 cte = With(
122 Order.objects
123 .annotate(region_parent=F("region__parent_id")),
124 )
125 orders = cte.queryset().with_cte(cte)
126 print(orders.query)
127
128 data = sorted(
129 (x.region_id, x.amount, x.region_parent) for x in orders)[:5]
130 self.assertEqual(data, [
131 ("earth", 30, "sun"),
132 ("earth", 31, "sun"),
133 ("earth", 32, "sun"),
134 ("earth", 33, "sun"),
135 ("mars", 40, "sun"),
136 ])
137 self.assertTrue(
138 all(isinstance(x, Order) for x in orders),
139 repr([x for x in orders]),
140 )
141
142 def test_cte_queryset_with_join(self):
143 cte = With(
144 Order.objects
145 .annotate(region_parent=F("region__parent_id")),
146 )
147 orders = (
148 cte.queryset()
149 .with_cte(cte)
150 .annotate(parent=F("region__parent_id"))
151 .order_by("region_id", "amount")
152 )
153 print(orders.query)
154
155 data = [(x.region_id, x.region_parent, x.parent) for x in orders][:5]
156 self.assertEqual(data, [
157 ("earth", "sun", "sun"),
158 ("earth", "sun", "sun"),
159 ("earth", "sun", "sun"),
160 ("earth", "sun", "sun"),
161 ("mars", "sun", "sun"),
162 ])
163
164 def test_cte_queryset_with_values_result(self):
165 cte = With(
166 Order.objects
167 .values(
168 "region_id",
169 region_parent=F("region__parent_id"),
170 )
171 .distinct()
172 )
173 values = (
174 cte.queryset()
175 .with_cte(cte)
176 .filter(region_parent__isnull=False)
177 )
178 print(values.query)
179
180 def key(item):
181 return item["region_parent"], item["region_id"]
182
183 data = sorted(values, key=key)[:5]
184 self.assertEqual(data, [
185 {'region_id': 'moon', 'region_parent': 'earth'},
186 {
187 'region_id': 'proxima centauri b',
188 'region_parent': 'proxima centauri',
189 },
190 {'region_id': 'earth', 'region_parent': 'sun'},
191 {'region_id': 'mars', 'region_parent': 'sun'},
192 {'region_id': 'mercury', 'region_parent': 'sun'},
193 ])
194
195 def test_named_simple_ctes(self):
196 totals = With(
197 Order.objects
198 .filter(region__parent="sun")
199 .values("region_id")
200 .annotate(total=Sum("amount")),
201 name="totals",
202 )
203 region_count = With(
204 Region.objects
205 .filter(parent="sun")
206 .values("parent_id")
207 .annotate(num=Count("name")),
208 name="region_count",
209 )
210 orders = (
211 region_count.join(
212 totals.join(Order, region=totals.col.region_id),
213 region__parent=region_count.col.parent_id
214 )
215 .with_cte(totals)
216 .with_cte(region_count)
217 .annotate(region_total=totals.col.total)
218 .annotate(region_count=region_count.col.num)
219 .order_by("amount")
220 )
221 print(orders.query)
222
223 data = [(
224 o.amount,
225 o.region_id,
226 o.region_count,
227 o.region_total,
228 ) for o in orders]
229 self.assertEqual(data, [
230 (10, 'mercury', 4, 33),
231 (11, 'mercury', 4, 33),
232 (12, 'mercury', 4, 33),
233 (20, 'venus', 4, 86),
234 (21, 'venus', 4, 86),
235 (22, 'venus', 4, 86),
236 (23, 'venus', 4, 86),
237 (30, 'earth', 4, 126),
238 (31, 'earth', 4, 126),
239 (32, 'earth', 4, 126),
240 (33, 'earth', 4, 126),
241 (40, 'mars', 4, 123),
242 (41, 'mars', 4, 123),
243 (42, 'mars', 4, 123),
244 ])
245
246 def test_named_ctes(self):
247 def make_root_mapping(rootmap):
248 return Region.objects.filter(
249 parent__isnull=True
250 ).values(
251 "name",
252 root=F("name"),
253 ).union(
254 rootmap.join(Region, parent=rootmap.col.name).values(
255 "name",
256 root=rootmap.col.root,
257 ),
258 all=True,
259 )
260 rootmap = With.recursive(make_root_mapping, name="rootmap")
261
262 totals = With(
263 rootmap.join(Order, region_id=rootmap.col.name)
264 .values(
265 root=rootmap.col.root,
266 ).annotate(
267 orders_count=Count("id"),
268 region_total=Sum("amount"),
269 ),
270 name="totals",
271 )
272
273 root_regions = (
274 totals.join(Region, name=totals.col.root)
275 .with_cte(rootmap)
276 .with_cte(totals)
277 .annotate(
278 # count of orders in this region and all subregions
279 orders_count=totals.col.orders_count,
280 # sum of order amounts in this region and all subregions
281 region_total=totals.col.region_total,
282 )
283 )
284 print(root_regions.query)
285
286 data = sorted(
287 (r.name, r.orders_count, r.region_total) for r in root_regions
288 )
289 self.assertEqual(data, [
290 ('proxima centauri', 4, 2033),
291 ('sun', 18, 1374),
292 ])
293
294 def test_materialized_option(self):
295 totals = With(
296 Order.objects
297 .filter(region__parent="sun")
298 .values("region_id")
299 .annotate(total=Sum("amount")),
300 materialized=True
301 )
302 orders = (
303 totals
304 .join(Order, region=totals.col.region_id)
305 .with_cte(totals)
306 .annotate(region_total=totals.col.total)
307 .order_by("amount")
308 )
309 self.assertTrue(
310 str(orders.query).startswith(
311 'WITH RECURSIVE "cte" AS MATERIALIZED'
312 )
313 )
314
315 def test_update_cte_query(self):
316 cte = With(
317 Order.objects
318 .values(region_parent=F("region__parent_id"))
319 .annotate(total=Sum("amount"))
320 .filter(total__isnull=False)
321 )
322 # not the most efficient query, but it exercises CTEUpdateQuery
323 Order.objects.all().with_cte(cte).filter(region_id__in=Subquery(
324 cte.queryset()
325 .filter(region_parent=OuterRef("region_id"))
326 .values("region_parent")
327 )).update(amount=Subquery(
328 cte.queryset()
329 .filter(region_parent=OuterRef("region_id"))
330 .values("total")
331 ))
332
333 data = set((o.region_id, o.amount) for o in Order.objects.filter(
334 region_id__in=["earth", "sun", "proxima centauri", "mars"]
335 ))
336 self.assertEqual(data, {
337 ('earth', 6),
338 ('mars', 40),
339 ('mars', 41),
340 ('mars', 42),
341 ('proxima centauri', 33),
342 ('sun', 368),
343 })
344
345 def test_update_with_subquery(self):
346 # Test for issue: https://github.com/dimagi/django-cte/issues/9
347 # Issue is not reproduces on sqlite3 use postgres to run.
348 # To reproduce the problem it's required to have some join
349 # in the select-query so the compiler will turn it into a subquery.
350 # To add a join use a filter over field of related model
351 orders = Order.objects.filter(region__parent_id='sun')
352 orders.update(amount=0)
353 data = {(order.region_id, order.amount) for order in orders}
354 self.assertEqual(data, {
355 ('mercury', 0),
356 ('venus', 0),
357 ('earth', 0),
358 ('mars', 0),
359 })
360
361 def test_delete_cte_query(self):
362 raise SkipTest(
363 "this test will not work until `QuerySet.delete` (Django method) "
364 "calls `self.query.chain(sql.DeleteQuery)` instead of "
365 "`sql.DeleteQuery(self.model)`"
366 )
367 cte = With(
368 Order.objects
369 .values(region_parent=F("region__parent_id"))
370 .annotate(total=Sum("amount"))
371 .filter(total__isnull=False)
372 )
373 Order.objects.all().with_cte(cte).annotate(
374 cte_has_order=Exists(
375 cte.queryset()
376 .values("total")
377 .filter(region_parent=OuterRef("region_id"))
378 )
379 ).filter(cte_has_order=False).delete()
380
381 data = [(o.region_id, o.amount) for o in Order.objects.all()]
382 self.assertEqual(data, [
383 ('sun', 1000),
384 ('earth', 30),
385 ('earth', 31),
386 ('earth', 32),
387 ('earth', 33),
388 ('proxima centauri', 2000),
389 ])
390
391 def test_outerref_in_cte_query(self):
392 # This query is meant to return the difference between min and max
393 # order of each region, through a subquery
394 min_and_max = With(
395 Order.objects
396 .filter(region=OuterRef("pk"))
397 .values('region') # This is to force group by region_id
398 .annotate(
399 amount_min=Min("amount"),
400 amount_max=Max("amount"),
401 )
402 .values('amount_min', 'amount_max')
403 )
404 regions = (
405 Region.objects
406 .annotate(
407 difference=Subquery(
408 min_and_max.queryset().with_cte(min_and_max).annotate(
409 difference=ExpressionWrapper(
410 F('amount_max') - F('amount_min'),
411 output_field=int_field,
412 ),
413 ).values('difference')[:1],
414 output_field=IntegerField()
415 )
416 )
417 .order_by("name")
418 )
419 print(regions.query)
420
421 data = [(r.name, r.difference) for r in regions]
422 self.assertEqual(data, [
423 ("bernard's star", None),
424 ('deimos', None),
425 ('earth', 3),
426 ('mars', 2),
427 ('mercury', 2),
428 ('moon', 2),
429 ('phobos', None),
430 ('proxima centauri', 0),
431 ('proxima centauri b', 2),
432 ('sun', 0),
433 ('venus', 3)
434 ])
435
436 def test_experimental_left_outer_join(self):
437 totals = With(
438 Order.objects
439 .values("region_id")
440 .annotate(total=Sum("amount"))
441 .filter(total__gt=100)
442 )
443 orders = (
444 totals
445 .join(Order, region=totals.col.region_id, _join_type=LOUTER)
446 .with_cte(totals)
447 .annotate(region_total=totals.col.total)
448 )
449 print(orders.query)
450 self.assertIn("LEFT OUTER JOIN", str(orders.query))
451 self.assertNotIn("INNER JOIN", str(orders.query))
452
453 data = sorted((o.region_id, o.amount, o.region_total) for o in orders)
454 self.assertEqual(data, [
455 ('earth', 30, 126),
456 ('earth', 31, 126),
457 ('earth', 32, 126),
458 ('earth', 33, 126),
459 ('mars', 40, 123),
460 ('mars', 41, 123),
461 ('mars', 42, 123),
462 ('mercury', 10, None),
463 ('mercury', 11, None),
464 ('mercury', 12, None),
465 ('moon', 1, None),
466 ('moon', 2, None),
467 ('moon', 3, None),
468 ('proxima centauri', 2000, 2000),
469 ('proxima centauri b', 10, None),
470 ('proxima centauri b', 11, None),
471 ('proxima centauri b', 12, None),
472 ('sun', 1000, 1000),
473 ('venus', 20, None),
474 ('venus', 21, None),
475 ('venus', 22, None),
476 ('venus', 23, None),
477 ])
478
479 def test_non_cte_subquery(self):
480 """
481 Verifies that subquery annotations are handled correctly when the
482 subquery model doesn't use the CTE manager, and the query results
483 match expected behavior
484 """
485 self.assertNotIsInstance(User.objects, CTEManager)
486
487 sub_totals = With(
488 Order.objects
489 .values(region_parent=F("region__parent_id"))
490 .annotate(
491 total=Sum("amount"),
492 # trivial subquery example testing existence of
493 # a user for the order
494 non_cte_subquery=Exists(
495 User.objects.filter(pk=OuterRef("user_id"))
496 ),
497 ),
498 )
499 regions = (
500 Region.objects.all()
501 .with_cte(sub_totals)
502 .annotate(
503 child_regions_total=Subquery(
504 sub_totals.queryset()
505 .filter(region_parent=OuterRef("name"))
506 .values("total"),
507 ),
508 )
509 .order_by("name")
510 )
511 print(regions.query)
512
513 data = [(r.name, r.child_regions_total) for r in regions]
514 self.assertEqual(data, [
515 ("bernard's star", None),
516 ('deimos', None),
517 ('earth', 6),
518 ('mars', None),
519 ('mercury', None),
520 ('moon', None),
521 ('phobos', None),
522 ('proxima centauri', 33),
523 ('proxima centauri b', None),
524 ('sun', 368),
525 ('venus', None)
526 ])
527
528 def test_explain(self):
529 """
530 Verifies that using .explain() prepends the EXPLAIN clause in the
531 correct position
532 """
533
534 totals = With(
535 Order.objects
536 .filter(region__parent="sun")
537 .values("region_id")
538 .annotate(total=Sum("amount")),
539 name="totals",
540 )
541 region_count = With(
542 Region.objects
543 .filter(parent="sun")
544 .values("parent_id")
545 .annotate(num=Count("name")),
546 name="region_count",
547 )
548 orders = (
549 region_count.join(
550 totals.join(Order, region=totals.col.region_id),
551 region__parent=region_count.col.parent_id
552 )
553 .with_cte(totals)
554 .with_cte(region_count)
555 .annotate(region_total=totals.col.total)
556 .annotate(region_count=region_count.col.num)
557 .order_by("amount")
558 )
559 print(orders.query)
560
561 self.assertIsInstance(orders.explain(), str)
562
563 def test_empty_result_set_cte(self):
564 """
565 Verifies that the CTEQueryCompiler can handle empty result sets in the
566 related CTEs
567 """
568 totals = With(
569 Order.objects
570 .filter(id__in=[])
571 .values("region_id")
572 .annotate(total=Sum("amount")),
573 name="totals",
574 )
575 orders = (
576 totals.join(Order, region=totals.col.region_id)
577 .with_cte(totals)
578 .annotate(region_total=totals.col.total)
579 .order_by("amount")
580 )
581
582 self.assertEqual(len(orders), 0)
583
584 def test_left_outer_join_on_empty_result_set_cte(self):
585 totals = With(
586 Order.objects
587 .filter(id__in=[])
588 .values("region_id")
589 .annotate(total=Sum("amount")),
590 name="totals",
591 )
592 orders = (
593 totals.join(Order, region=totals.col.region_id, _join_type=LOUTER)
594 .with_cte(totals)
595 .annotate(region_total=totals.col.total)
596 .order_by("amount")
597 )
598
599 self.assertEqual(len(orders), 22)
600
601 def test_union_query_with_cte(self):
602 orders = (
603 Order.objects
604 .filter(region__parent="sun")
605 .only("region", "amount")
606 )
607 orders_cte = With(orders, name="orders_cte")
608 orders_cte_queryset = orders_cte.queryset()
609
610 earth_orders = orders_cte_queryset.filter(region="earth")
611 mars_orders = orders_cte_queryset.filter(region="mars")
612
613 earth_mars = earth_orders.union(mars_orders, all=True)
614 earth_mars_cte = (
615 earth_mars
616 .with_cte(orders_cte)
617 .order_by("region", "amount")
618 .values_list("region", "amount")
619 )
620 print(earth_mars_cte.query)
621
622 self.assertEqual(list(earth_mars_cte), [
623 ('earth', 30),
624 ('earth', 31),
625 ('earth', 32),
626 ('earth', 33),
627 ('mars', 40),
628 ('mars', 41),
629 ('mars', 42),
630 ])
631
632 def test_cte_select_pk(self):
633 orders = Order.objects.filter(region="earth").values("pk")
634 cte = With(orders)
635 queryset = cte.join(orders, pk=cte.col.pk).with_cte(cte).order_by("pk")
636 print(queryset.query)
637 self.assertEqual(list(queryset), [
638 {'pk': 9},
639 {'pk': 10},
640 {'pk': 11},
641 {'pk': 12},
642 ])