| 1 |
import pytest |
| 2 |
import django |
| 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.deletion import Collector |
| 9 |
from django.db.models.sql.constants import LOUTER |
| 10 |
from django.db.utils import OperationalError, ProgrammingError |
| 11 |
from django.test import TestCase |
| 12 |
|
| 13 |
from django_cte import CTE, with_cte |
| 14 |
|
| 15 |
from .models import Order, Region, User, WithDBColumn |
| 16 |
|
| 17 |
int_field = IntegerField() |
| 18 |
text_field = TextField() |
| 19 |
|
| 20 |
|
| 21 |
class TestCTE(TestCase): |
| 22 |
|
| 23 |
def test_simple_cte_query(self): |
| 24 |
cte = CTE( |
| 25 |
Order.objects |
| 26 |
.values("region_id") |
| 27 |
.annotate(total=Sum("amount")) |
| 28 |
) |
| 29 |
|
| 30 |
orders = with_cte( |
| 31 |
# WITH cte ... |
| 32 |
cte, |
| 33 |
|
| 34 |
# SELECT ... FROM orders |
| 35 |
# INNER JOIN cte ON orders.region_id = cte.region_id |
| 36 |
select=cte.join(Order, region=cte.col.region_id), |
| 37 |
).annotate(region_total=cte.col.total) |
| 38 |
print(orders.query) |
| 39 |
|
| 40 |
data = sorted((o.amount, o.region_id, o.region_total) for o in orders) |
| 41 |
self.assertEqual(data, [ |
| 42 |
(1, 'moon', 6), |
| 43 |
(2, 'moon', 6), |
| 44 |
(3, 'moon', 6), |
| 45 |
(10, 'mercury', 33), |
| 46 |
(10, 'proxima centauri b', 33), |
| 47 |
(11, 'mercury', 33), |
| 48 |
(11, 'proxima centauri b', 33), |
| 49 |
(12, 'mercury', 33), |
| 50 |
(12, 'proxima centauri b', 33), |
| 51 |
(20, 'venus', 86), |
| 52 |
(21, 'venus', 86), |
| 53 |
(22, 'venus', 86), |
| 54 |
(23, 'venus', 86), |
| 55 |
(30, 'earth', 126), |
| 56 |
(31, 'earth', 126), |
| 57 |
(32, 'earth', 126), |
| 58 |
(33, 'earth', 126), |
| 59 |
(40, 'mars', 123), |
| 60 |
(41, 'mars', 123), |
| 61 |
(42, 'mars', 123), |
| 62 |
(1000, 'sun', 1000), |
| 63 |
(2000, 'proxima centauri', 2000), |
| 64 |
]) |
| 65 |
|
| 66 |
def test_cte_name_escape(self): |
| 67 |
totals = CTE( |
| 68 |
Order.objects |
| 69 |
.filter(region__parent="sun") |
| 70 |
.values("region_id") |
| 71 |
.annotate(total=Sum("amount")), |
| 72 |
name="mixedCaseCTEName" |
| 73 |
) |
| 74 |
orders = with_cte( |
| 75 |
totals, |
| 76 |
select=totals.join(Order, region=totals.col.region_id) |
| 77 |
.annotate(region_total=totals.col.total) |
| 78 |
.order_by("amount") |
| 79 |
) |
| 80 |
self.assertTrue( |
| 81 |
str(orders.query).startswith('WITH RECURSIVE "mixedCaseCTEName"')) |
| 82 |
|
| 83 |
def test_cte_queryset(self): |
| 84 |
sub_totals = CTE( |
| 85 |
Order.objects |
| 86 |
.values(region_parent=F("region__parent_id")) |
| 87 |
.annotate(total=Sum("amount")), |
| 88 |
) |
| 89 |
regions = with_cte( |
| 90 |
sub_totals, |
| 91 |
select=Region.objects.annotate( |
| 92 |
child_regions_total=Subquery( |
| 93 |
sub_totals.queryset() |
| 94 |
.filter(region_parent=OuterRef("name")) |
| 95 |
.values("total"), |
| 96 |
), |
| 97 |
) |
| 98 |
.order_by("name") |
| 99 |
) |
| 100 |
print(regions.query) |
| 101 |
|
| 102 |
data = [(r.name, r.child_regions_total) for r in regions] |
| 103 |
self.assertEqual(data, [ |
| 104 |
("bernard's star", None), |
| 105 |
('deimos', None), |
| 106 |
('earth', 6), |
| 107 |
('mars', None), |
| 108 |
('mercury', None), |
| 109 |
('moon', None), |
| 110 |
('phobos', None), |
| 111 |
('proxima centauri', 33), |
| 112 |
('proxima centauri b', None), |
| 113 |
('sun', 368), |
| 114 |
('venus', None) |
| 115 |
]) |
| 116 |
|
| 117 |
def test_cte_queryset_with_model_result(self): |
| 118 |
cte = CTE( |
| 119 |
Order.objects |
| 120 |
.annotate(region_parent=F("region__parent_id")), |
| 121 |
) |
| 122 |
orders = with_cte( |
| 123 |
cte, # WITH cte AS (...) |
| 124 |
select=cte, # SELECT ... FROM cte |
| 125 |
) |
| 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 = CTE( |
| 144 |
Order.objects |
| 145 |
.annotate(region_parent=F("region__parent_id")), |
| 146 |
) |
| 147 |
orders = with_cte( |
| 148 |
cte, |
| 149 |
select=cte.queryset() |
| 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 = CTE( |
| 166 |
Order.objects |
| 167 |
.values( |
| 168 |
"region_id", |
| 169 |
region_parent=F("region__parent_id"), |
| 170 |
) |
| 171 |
.distinct() |
| 172 |
) |
| 173 |
values = with_cte(cte, select=cte).filter(region_parent__isnull=False) |
| 174 |
print(values.query) |
| 175 |
|
| 176 |
def key(item): |
| 177 |
return item["region_parent"], item["region_id"] |
| 178 |
|
| 179 |
data = sorted(values, key=key)[:5] |
| 180 |
self.assertEqual(data, [ |
| 181 |
{'region_id': 'moon', 'region_parent': 'earth'}, |
| 182 |
{ |
| 183 |
'region_id': 'proxima centauri b', |
| 184 |
'region_parent': 'proxima centauri', |
| 185 |
}, |
| 186 |
{'region_id': 'earth', 'region_parent': 'sun'}, |
| 187 |
{'region_id': 'mars', 'region_parent': 'sun'}, |
| 188 |
{'region_id': 'mercury', 'region_parent': 'sun'}, |
| 189 |
]) |
| 190 |
|
| 191 |
def test_named_simple_ctes(self): |
| 192 |
totals = CTE( |
| 193 |
Order.objects |
| 194 |
.filter(region__parent="sun") |
| 195 |
.values("region_id") |
| 196 |
.annotate(total=Sum("amount")), |
| 197 |
name="totals", |
| 198 |
) |
| 199 |
region_count = CTE( |
| 200 |
Region.objects |
| 201 |
.filter(parent="sun") |
| 202 |
.values("parent_id") |
| 203 |
.annotate(num=Count("name")), |
| 204 |
name="region_count", |
| 205 |
) |
| 206 |
orders = with_cte( |
| 207 |
totals, |
| 208 |
region_count, |
| 209 |
select=region_count.join( |
| 210 |
totals.join(Order, region=totals.col.region_id), |
| 211 |
region__parent=region_count.col.parent_id |
| 212 |
) |
| 213 |
.annotate(region_total=totals.col.total) |
| 214 |
.annotate(region_count=region_count.col.num) |
| 215 |
.order_by("amount") |
| 216 |
) |
| 217 |
print(orders.query) |
| 218 |
|
| 219 |
data = [( |
| 220 |
o.amount, |
| 221 |
o.region_id, |
| 222 |
o.region_count, |
| 223 |
o.region_total, |
| 224 |
) for o in orders] |
| 225 |
self.assertEqual(data, [ |
| 226 |
(10, 'mercury', 4, 33), |
| 227 |
(11, 'mercury', 4, 33), |
| 228 |
(12, 'mercury', 4, 33), |
| 229 |
(20, 'venus', 4, 86), |
| 230 |
(21, 'venus', 4, 86), |
| 231 |
(22, 'venus', 4, 86), |
| 232 |
(23, 'venus', 4, 86), |
| 233 |
(30, 'earth', 4, 126), |
| 234 |
(31, 'earth', 4, 126), |
| 235 |
(32, 'earth', 4, 126), |
| 236 |
(33, 'earth', 4, 126), |
| 237 |
(40, 'mars', 4, 123), |
| 238 |
(41, 'mars', 4, 123), |
| 239 |
(42, 'mars', 4, 123), |
| 240 |
]) |
| 241 |
|
| 242 |
def test_named_ctes(self): |
| 243 |
def make_root_mapping(rootmap): |
| 244 |
return Region.objects.filter( |
| 245 |
parent__isnull=True |
| 246 |
).values( |
| 247 |
"name", |
| 248 |
root=F("name"), |
| 249 |
).union( |
| 250 |
rootmap.join(Region, parent=rootmap.col.name).values( |
| 251 |
"name", |
| 252 |
root=rootmap.col.root, |
| 253 |
), |
| 254 |
all=True, |
| 255 |
) |
| 256 |
rootmap = CTE.recursive(make_root_mapping, name="rootmap") |
| 257 |
|
| 258 |
totals = CTE( |
| 259 |
rootmap.join(Order, region_id=rootmap.col.name) |
| 260 |
.values( |
| 261 |
root=rootmap.col.root, |
| 262 |
).annotate( |
| 263 |
orders_count=Count("id"), |
| 264 |
region_total=Sum("amount"), |
| 265 |
), |
| 266 |
name="totals", |
| 267 |
) |
| 268 |
|
| 269 |
root_regions = with_cte( |
| 270 |
rootmap, |
| 271 |
totals, |
| 272 |
select=totals.join(Region, name=totals.col.root).annotate( |
| 273 |
# count of orders in this region and all subregions |
| 274 |
orders_count=totals.col.orders_count, |
| 275 |
# sum of order amounts in this region and all subregions |
| 276 |
region_total=totals.col.region_total, |
| 277 |
) |
| 278 |
) |
| 279 |
print(root_regions.query) |
| 280 |
|
| 281 |
data = sorted( |
| 282 |
(r.name, r.orders_count, r.region_total) for r in root_regions |
| 283 |
) |
| 284 |
self.assertEqual(data, [ |
| 285 |
('proxima centauri', 4, 2033), |
| 286 |
('sun', 18, 1374), |
| 287 |
]) |
| 288 |
|
| 289 |
def test_materialized_option(self): |
| 290 |
totals = CTE( |
| 291 |
Order.objects |
| 292 |
.filter(region__parent="sun") |
| 293 |
.values("region_id") |
| 294 |
.annotate(total=Sum("amount")), |
| 295 |
materialized=True |
| 296 |
) |
| 297 |
orders = with_cte( |
| 298 |
totals, |
| 299 |
select=totals.join(Order, region=totals.col.region_id) |
| 300 |
.annotate(region_total=totals.col.total) |
| 301 |
.order_by("amount") |
| 302 |
) |
| 303 |
self.assertTrue( |
| 304 |
str(orders.query).startswith( |
| 305 |
'WITH RECURSIVE "cte" AS MATERIALIZED' |
| 306 |
) |
| 307 |
) |
| 308 |
|
| 309 |
def test_update_cte_query(self): |
| 310 |
cte = CTE( |
| 311 |
Order.objects |
| 312 |
.values(region_parent=F("region__parent_id")) |
| 313 |
.annotate(total=Sum("amount")) |
| 314 |
.filter(total__isnull=False) |
| 315 |
) |
| 316 |
# not the most efficient query, but it exercises CTEUpdateQuery |
| 317 |
with_cte(cte, select=Order).filter(region_id__in=Subquery( |
| 318 |
cte.queryset() |
| 319 |
.filter(region_parent=OuterRef("region_id")) |
| 320 |
.values("region_parent") |
| 321 |
)).update(amount=Subquery( |
| 322 |
cte.queryset() |
| 323 |
.filter(region_parent=OuterRef("region_id")) |
| 324 |
.values("total") |
| 325 |
)) |
| 326 |
|
| 327 |
data = set((o.region_id, o.amount) for o in Order.objects.filter( |
| 328 |
region_id__in=["earth", "sun", "proxima centauri", "mars"] |
| 329 |
)) |
| 330 |
self.assertEqual(data, { |
| 331 |
('earth', 6), |
| 332 |
('mars', 40), |
| 333 |
('mars', 41), |
| 334 |
('mars', 42), |
| 335 |
('proxima centauri', 33), |
| 336 |
('sun', 368), |
| 337 |
}) |
| 338 |
|
| 339 |
def test_update_with_subquery(self): |
| 340 |
# Test for issue: https://github.com/dimagi/django-cte/issues/9 |
| 341 |
# Issue is not reproduced on sqlite3, use postgres to run. |
| 342 |
# To reproduce the problem it's required to have some join |
| 343 |
# in the select-query so the compiler will turn it into a subquery. |
| 344 |
# To add a join use a filter over field of related model |
| 345 |
orders = Order.objects.filter(region__parent_id='sun') |
| 346 |
orders.update(amount=0) |
| 347 |
data = {(order.region_id, order.amount) for order in orders} |
| 348 |
self.assertEqual(data, { |
| 349 |
('mercury', 0), |
| 350 |
('venus', 0), |
| 351 |
('earth', 0), |
| 352 |
('mars', 0), |
| 353 |
}) |
| 354 |
|
| 355 |
@pytest.mark.xfail( |
| 356 |
reason="this test will not work until `QuerySet.delete` " |
| 357 |
"(Django method) calls `self.query.chain(sql.DeleteQuery)` " |
| 358 |
"instead of `sql.DeleteQuery(self.model)`", |
| 359 |
raises=(OperationalError, ProgrammingError), |
| 360 |
strict=True, |
| 361 |
) |
| 362 |
def test_delete_cte_query(self): |
| 363 |
# This test requires "fast" deletion. If this constraint is broken |
| 364 |
# the models have been modified in an incompatible way and they |
| 365 |
# should be adjusted until this assertion passes again. |
| 366 |
self.assertTrue(Collector(None).can_fast_delete(Order)) |
| 367 |
|
| 368 |
cte = CTE( |
| 369 |
Order.objects |
| 370 |
.values(region_parent=F("region__parent_id")) |
| 371 |
.annotate(total=Sum("amount")) |
| 372 |
.filter(total__isnull=False) |
| 373 |
) |
| 374 |
with_cte(cte, select=Order).annotate( |
| 375 |
cte_has_order=Exists( |
| 376 |
cte.queryset() |
| 377 |
.values("total") |
| 378 |
.filter(region_parent=OuterRef("region_id")) |
| 379 |
) |
| 380 |
).filter(cte_has_order=False).delete() |
| 381 |
|
| 382 |
data = [(o.region_id, o.amount) for o in Order.objects.all()] |
| 383 |
self.assertEqual(data, [ |
| 384 |
('sun', 1000), |
| 385 |
('earth', 30), |
| 386 |
('earth', 31), |
| 387 |
('earth', 32), |
| 388 |
('earth', 33), |
| 389 |
('proxima centauri', 2000), |
| 390 |
]) |
| 391 |
|
| 392 |
def test_outerref_in_cte_query(self): |
| 393 |
# This query is meant to return the difference between min and max |
| 394 |
# order of each region, through a subquery |
| 395 |
min_and_max = CTE( |
| 396 |
Order.objects |
| 397 |
.filter(region=OuterRef("pk")) |
| 398 |
.values('region') # This is to force group by region_id |
| 399 |
.annotate( |
| 400 |
amount_min=Min("amount"), |
| 401 |
amount_max=Max("amount"), |
| 402 |
) |
| 403 |
.values('amount_min', 'amount_max') |
| 404 |
) |
| 405 |
regions = ( |
| 406 |
Region.objects |
| 407 |
.annotate( |
| 408 |
difference=Subquery( |
| 409 |
with_cte(min_and_max, select=min_and_max) |
| 410 |
.annotate( |
| 411 |
difference=ExpressionWrapper( |
| 412 |
F('amount_max') - F('amount_min'), |
| 413 |
output_field=int_field, |
| 414 |
), |
| 415 |
).values('difference')[:1], |
| 416 |
output_field=IntegerField() |
| 417 |
) |
| 418 |
) |
| 419 |
.order_by("name") |
| 420 |
) |
| 421 |
print(regions.query) |
| 422 |
|
| 423 |
data = [(r.name, r.difference) for r in regions] |
| 424 |
self.assertEqual(data, [ |
| 425 |
("bernard's star", None), |
| 426 |
('deimos', None), |
| 427 |
('earth', 3), |
| 428 |
('mars', 2), |
| 429 |
('mercury', 2), |
| 430 |
('moon', 2), |
| 431 |
('phobos', None), |
| 432 |
('proxima centauri', 0), |
| 433 |
('proxima centauri b', 2), |
| 434 |
('sun', 0), |
| 435 |
('venus', 3) |
| 436 |
]) |
| 437 |
|
| 438 |
def test_experimental_left_outer_join(self): |
| 439 |
totals = CTE( |
| 440 |
Order.objects |
| 441 |
.values("region_id") |
| 442 |
.annotate(total=Sum("amount")) |
| 443 |
.filter(total__gt=100) |
| 444 |
) |
| 445 |
orders = with_cte( |
| 446 |
totals, |
| 447 |
select=totals |
| 448 |
.join(Order, region=totals.col.region_id, _join_type=LOUTER) |
| 449 |
.annotate(region_total=totals.col.total) |
| 450 |
) |
| 451 |
print(orders.query) |
| 452 |
self.assertIn("LEFT OUTER JOIN", str(orders.query)) |
| 453 |
self.assertNotIn("INNER JOIN", str(orders.query)) |
| 454 |
|
| 455 |
data = sorted((o.region_id, o.amount, o.region_total) for o in orders) |
| 456 |
self.assertEqual(data, [ |
| 457 |
('earth', 30, 126), |
| 458 |
('earth', 31, 126), |
| 459 |
('earth', 32, 126), |
| 460 |
('earth', 33, 126), |
| 461 |
('mars', 40, 123), |
| 462 |
('mars', 41, 123), |
| 463 |
('mars', 42, 123), |
| 464 |
('mercury', 10, None), |
| 465 |
('mercury', 11, None), |
| 466 |
('mercury', 12, None), |
| 467 |
('moon', 1, None), |
| 468 |
('moon', 2, None), |
| 469 |
('moon', 3, None), |
| 470 |
('proxima centauri', 2000, 2000), |
| 471 |
('proxima centauri b', 10, None), |
| 472 |
('proxima centauri b', 11, None), |
| 473 |
('proxima centauri b', 12, None), |
| 474 |
('sun', 1000, 1000), |
| 475 |
('venus', 20, None), |
| 476 |
('venus', 21, None), |
| 477 |
('venus', 22, None), |
| 478 |
('venus', 23, None), |
| 479 |
]) |
| 480 |
|
| 481 |
def test_non_cte_subquery(self): |
| 482 |
""" |
| 483 |
Verifies that subquery annotations are handled correctly when the |
| 484 |
subquery model doesn't use the CTE manager, and the query results |
| 485 |
match expected behavior |
| 486 |
""" |
| 487 |
sub_totals = CTE( |
| 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 = with_cte( |
| 500 |
sub_totals, |
| 501 |
select=Region.objects.annotate( |
| 502 |
child_regions_total=Subquery( |
| 503 |
sub_totals.queryset() |
| 504 |
.filter(region_parent=OuterRef("name")) |
| 505 |
.values("total"), |
| 506 |
), |
| 507 |
) |
| 508 |
.order_by("name") |
| 509 |
) |
| 510 |
print(regions.query) |
| 511 |
|
| 512 |
data = [(r.name, r.child_regions_total) for r in regions] |
| 513 |
self.assertEqual(data, [ |
| 514 |
("bernard's star", None), |
| 515 |
('deimos', None), |
| 516 |
('earth', 6), |
| 517 |
('mars', None), |
| 518 |
('mercury', None), |
| 519 |
('moon', None), |
| 520 |
('phobos', None), |
| 521 |
('proxima centauri', 33), |
| 522 |
('proxima centauri b', None), |
| 523 |
('sun', 368), |
| 524 |
('venus', None) |
| 525 |
]) |
| 526 |
|
| 527 |
def test_explain(self): |
| 528 |
""" |
| 529 |
Verifies that using .explain() prepends the EXPLAIN clause in the |
| 530 |
correct position |
| 531 |
""" |
| 532 |
|
| 533 |
totals = CTE( |
| 534 |
Order.objects |
| 535 |
.filter(region__parent="sun") |
| 536 |
.values("region_id") |
| 537 |
.annotate(total=Sum("amount")), |
| 538 |
name="totals", |
| 539 |
) |
| 540 |
region_count = CTE( |
| 541 |
Region.objects |
| 542 |
.filter(parent="sun") |
| 543 |
.values("parent_id") |
| 544 |
.annotate(num=Count("name")), |
| 545 |
name="region_count", |
| 546 |
) |
| 547 |
orders = with_cte( |
| 548 |
totals, |
| 549 |
region_count, |
| 550 |
select=region_count.join( |
| 551 |
totals.join(Order, region=totals.col.region_id), |
| 552 |
region__parent=region_count.col.parent_id |
| 553 |
) |
| 554 |
.annotate(region_total=totals.col.total) |
| 555 |
.annotate(region_count=region_count.col.num) |
| 556 |
.order_by("amount") |
| 557 |
) |
| 558 |
print(orders.query) |
| 559 |
|
| 560 |
self.assertIsInstance(orders.explain(), str) |
| 561 |
|
| 562 |
def test_empty_result_set_cte(self): |
| 563 |
""" |
| 564 |
Verifies that the CTEQueryCompiler can handle empty result sets in the |
| 565 |
related CTEs |
| 566 |
""" |
| 567 |
totals = CTE( |
| 568 |
Order.objects |
| 569 |
.filter(id__in=[]) |
| 570 |
.values("region_id") |
| 571 |
.annotate(total=Sum("amount")), |
| 572 |
name="totals", |
| 573 |
) |
| 574 |
orders = with_cte( |
| 575 |
totals, |
| 576 |
select=totals.join(Order, region=totals.col.region_id) |
| 577 |
.annotate(region_total=totals.col.total) |
| 578 |
.order_by("amount") |
| 579 |
) |
| 580 |
|
| 581 |
self.assertEqual(len(orders), 0) |
| 582 |
|
| 583 |
def test_left_outer_join_on_empty_result_set_cte(self): |
| 584 |
totals = CTE( |
| 585 |
Order.objects |
| 586 |
.filter(id__in=[]) |
| 587 |
.values("region_id") |
| 588 |
.annotate(total=Sum("amount")), |
| 589 |
name="totals", |
| 590 |
) |
| 591 |
orders = with_cte( |
| 592 |
totals, |
| 593 |
select=totals |
| 594 |
.join(Order, region=totals.col.region_id, _join_type=LOUTER) |
| 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 = CTE(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 = with_cte( |
| 615 |
orders_cte, |
| 616 |
select=earth_mars |
| 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 = CTE(orders) |
| 635 |
queryset = with_cte( |
| 636 |
cte, select=cte.join(orders, pk=cte.col.pk) |
| 637 |
).order_by("pk") |
| 638 |
print(queryset.query) |
| 639 |
self.assertEqual(list(queryset), [ |
| 640 |
{'pk': 9}, |
| 641 |
{'pk': 10}, |
| 642 |
{'pk': 11}, |
| 643 |
{'pk': 12}, |
| 644 |
]) |
| 645 |
|
| 646 |
def test_django52_resolve_ref_regression(self): |
| 647 |
cte = CTE( |
| 648 |
Order.objects.annotate( |
| 649 |
pnt_id=F("region__parent_id"), |
| 650 |
region_name=F("region__name"), |
| 651 |
).values( |
| 652 |
# important: more than one query.select field |
| 653 |
"region_id", |
| 654 |
"amount", |
| 655 |
# important: more than one query.annotations field |
| 656 |
"pnt_id", |
| 657 |
"region_name", |
| 658 |
) |
| 659 |
) |
| 660 |
qs = with_cte( |
| 661 |
cte, |
| 662 |
select=cte.queryset() |
| 663 |
.values( |
| 664 |
amt=cte.col.amount, |
| 665 |
pnt_id=cte.col.pnt_id, |
| 666 |
region_name=cte.col.region_name, |
| 667 |
) |
| 668 |
.filter(region_id="earth") |
| 669 |
.order_by("amount") |
| 670 |
) |
| 671 |
print(qs.query) |
| 672 |
self.assertEqual(list(qs), [ |
| 673 |
{'amt': 30, 'region_name': 'earth', 'pnt_id': 'sun'}, |
| 674 |
{'amt': 31, 'region_name': 'earth', 'pnt_id': 'sun'}, |
| 675 |
{'amt': 32, 'region_name': 'earth', 'pnt_id': 'sun'}, |
| 676 |
{'amt': 33, 'region_name': 'earth', 'pnt_id': 'sun'}, |
| 677 |
]) |
| 678 |
|
| 679 |
def test_django52_queryset_regression(self): |
| 680 |
cte = CTE(Order.objects.values("id", "region_id")) |
| 681 |
q = cte.queryset() |
| 682 |
q.values("id", "region_id") # Raises an exception before the fix |
| 683 |
|
| 684 |
def test_django52_ambiguous_column_names(self): |
| 685 |
cte = CTE(Order.objects.values("region", "amount", "user_id")) |
| 686 |
cte2 = CTE(User.objects.annotate(user_id=F("id")), name="cte2") |
| 687 |
qs = with_cte( |
| 688 |
cte, |
| 689 |
cte2, |
| 690 |
select=cte2.join(cte.queryset(), user_id=cte2.col.user_id) |
| 691 |
.annotate(user_name=cte2.col.name) |
| 692 |
.order_by("region", "amount") |
| 693 |
.values_list("region", "amount", "user_name"), |
| 694 |
) |
| 695 |
# Executing this query should not raise a |
| 696 |
# django.db.utils.OperationalError: ambiguous column name: user_id |
| 697 |
self.assertEqual(list(qs), [ |
| 698 |
('earth', 30, "admin"), |
| 699 |
('earth', 31, "admin"), |
| 700 |
('earth', 32, "admin"), |
| 701 |
('earth', 33, "admin"), |
| 702 |
('mars', 40, "admin"), |
| 703 |
('mars', 41, "admin"), |
| 704 |
('mars', 42, "admin"), |
| 705 |
('mercury', 10, "admin"), |
| 706 |
('mercury', 11, "admin"), |
| 707 |
('mercury', 12, "admin"), |
| 708 |
('moon', 1, "admin"), |
| 709 |
('moon', 2, "admin"), |
| 710 |
('moon', 3, "admin"), |
| 711 |
('proxima centauri', 2000, "admin"), |
| 712 |
('proxima centauri b', 10, "admin"), |
| 713 |
('proxima centauri b', 11, "admin"), |
| 714 |
('proxima centauri b', 12, "admin"), |
| 715 |
('sun', 1000, "admin"), |
| 716 |
('venus', 20, "admin"), |
| 717 |
('venus', 21, "admin"), |
| 718 |
('venus', 22, "admin"), |
| 719 |
('venus', 23, "admin"), |
| 720 |
]) |
| 721 |
|
| 722 |
def test_django52_queryset_aggregates_klass_error(self): |
| 723 |
cte = CTE( |
| 724 |
Order.objects.annotate(user_name=F("user__name")) |
| 725 |
.values("user_name") |
| 726 |
.annotate(c=Count("user_name")) |
| 727 |
.values("user_name", "c") |
| 728 |
) |
| 729 |
qs = with_cte(cte, select=cte) |
| 730 |
# Executing the query should not raise TypeError: 'NoneType' object is not subscriptable |
| 731 |
self.assertEqual(list(qs), [{"user_name": "admin", "c": 22}]) |
| 732 |
|
| 733 |
def test_django52_annotate_model_field_name_after_queryset(self): |
| 734 |
# Select the `id` field in one CTE |
| 735 |
cte = CTE(Order.objects.values("id", "region", "user_id")) |
| 736 |
# In the next query, when querying from the CTE we reassign the `id` field |
| 737 |
# Previously, this would have thrown an exception |
| 738 |
qs = ( |
| 739 |
with_cte(cte, select=cte) |
| 740 |
.annotate(id=F('user_id')) |
| 741 |
.values_list('id', 'region') |
| 742 |
.order_by('id', 'region') |
| 743 |
.distinct() |
| 744 |
) |
| 745 |
self.assertEqual(list(qs), [ |
| 746 |
(1, 'earth'), |
| 747 |
(1, 'mars'), |
| 748 |
(1, 'mercury'), |
| 749 |
(1, 'moon'), |
| 750 |
(1, 'proxima centauri'), |
| 751 |
(1, 'proxima centauri b'), |
| 752 |
(1, 'sun'), |
| 753 |
(1, 'venus'), |
| 754 |
]) |
| 755 |
|
| 756 |
@pytest.mark.skipif(django.VERSION < (5, 2), reason="Requires Django 5.2+") |
| 757 |
def test_queryset_after_values_list(self): |
| 758 |
cte = CTE(Order.objects.values_list("region", "amount").order_by("region", "amount")) |
| 759 |
qs = with_cte(cte, select=cte) |
| 760 |
self.assertEqual(list(qs), [ |
| 761 |
('earth', 30), |
| 762 |
('earth', 31), |
| 763 |
('earth', 32), |
| 764 |
('earth', 33), |
| 765 |
('mars', 40), |
| 766 |
('mars', 41), |
| 767 |
('mars', 42), |
| 768 |
('mercury', 10), |
| 769 |
('mercury', 11), |
| 770 |
('mercury', 12), |
| 771 |
('moon', 1), |
| 772 |
('moon', 2), |
| 773 |
('moon', 3), |
| 774 |
('proxima centauri', 2000), |
| 775 |
('proxima centauri b', 10), |
| 776 |
('proxima centauri b', 11), |
| 777 |
('proxima centauri b', 12), |
| 778 |
('sun', 1000), |
| 779 |
('venus', 20), |
| 780 |
('venus', 21), |
| 781 |
('venus', 22), |
| 782 |
('venus', 23), |
| 783 |
]) |
| 784 |
|
| 785 |
@pytest.mark.skipif(django.VERSION < (5, 2), reason="Requires Django 5.2+") |
| 786 |
def test_queryset_after_values_list_flat(self): |
| 787 |
cte = CTE( |
| 788 |
Order.objects.values_list("region", flat=True) |
| 789 |
.order_by("region") |
| 790 |
.distinct() |
| 791 |
) |
| 792 |
qs = with_cte(cte, select=cte) |
| 793 |
self.assertEqual(list(qs), [ |
| 794 |
'earth', |
| 795 |
'mars', |
| 796 |
'mercury', |
| 797 |
'moon', |
| 798 |
'proxima centauri', |
| 799 |
'proxima centauri b', |
| 800 |
'sun', |
| 801 |
'venus' |
| 802 |
]) |
| 803 |
|
| 804 |
@pytest.mark.skipif(django.VERSION < (5, 2), reason="Requires Django 5.2+") |
| 805 |
def test_queryset_values_list_order1(self): |
| 806 |
cte = CTE( |
| 807 |
Order.objects.values("region") |
| 808 |
.annotate(c=Count("region")) |
| 809 |
.values_list("c", "region") |
| 810 |
.order_by("region") |
| 811 |
) |
| 812 |
qs = with_cte(cte, select=cte) |
| 813 |
# Ensure the column order of queried fields is the specified one: c, region |
| 814 |
# Before the fix, the order would have been this one: region, c |
| 815 |
self.assertEqual(list(qs), [ |
| 816 |
(4, 'earth'), |
| 817 |
(3, 'mars'), |
| 818 |
(3, 'mercury'), |
| 819 |
(3, 'moon'), |
| 820 |
(1, 'proxima centauri'), |
| 821 |
(3, 'proxima centauri b'), |
| 822 |
(1, 'sun'), |
| 823 |
(4, 'venus'), |
| 824 |
]) |
| 825 |
|
| 826 |
@pytest.mark.skipif(django.VERSION < (5, 2), reason="Requires Django 5.2+") |
| 827 |
def test_queryset_values_list_order2(self): |
| 828 |
cte = CTE( |
| 829 |
Order.objects.values("region") |
| 830 |
.annotate(r=F("region"), c=Count("region")) |
| 831 |
.values_list("c", "r") |
| 832 |
.order_by("r") |
| 833 |
) |
| 834 |
qs = with_cte(cte, select=cte) |
| 835 |
# Ensure the column order of queried fields is the specified one: c, r |
| 836 |
# Before the fix, the order would have been this one: r, c |
| 837 |
self.assertEqual(list(qs), [ |
| 838 |
(4, 'earth'), |
| 839 |
(3, 'mars'), |
| 840 |
(3, 'mercury'), |
| 841 |
(3, 'moon'), |
| 842 |
(1, 'proxima centauri'), |
| 843 |
(3, 'proxima centauri b'), |
| 844 |
(1, 'sun'), |
| 845 |
(4, 'venus'), |
| 846 |
]) |
| 847 |
|
| 848 |
@pytest.mark.skipif(django.VERSION < (5, 2), reason="Requires Django 5.2+") |
| 849 |
def test_left_outer_join_invalid_innerjoin(self): |
| 850 |
totals = CTE( |
| 851 |
Order.objects |
| 852 |
.values("region_id") |
| 853 |
.annotate(total=Sum("amount")) |
| 854 |
) |
| 855 |
# Query all regions but only show the total order amount for regions that are |
| 856 |
# grandchildren of "sun". |
| 857 |
# This requires the __parent to be joined using LEFT OUTER JOIN too. |
| 858 |
# Otherwise, if django did an INNER JOIN for __parent then only regions that |
| 859 |
# have a parent would be included in the result set. |
| 860 |
qs = with_cte( |
| 861 |
totals, |
| 862 |
select=totals.join( |
| 863 |
Region, |
| 864 |
parent__parent="sun", |
| 865 |
name=totals.col.region_id, |
| 866 |
_join_type=LOUTER |
| 867 |
).values("name", total=totals.col.total) |
| 868 |
.order_by("name") |
| 869 |
) |
| 870 |
self.assertEqual(list(qs), [ |
| 871 |
{'name': "bernard's star", 'total': None}, |
| 872 |
{'name': 'deimos', 'total': None}, |
| 873 |
{'name': 'earth', 'total': None}, |
| 874 |
{'name': 'mars', 'total': None}, |
| 875 |
{'name': 'mercury', 'total': None}, |
| 876 |
{'name': 'moon', 'total': 6}, |
| 877 |
{'name': 'phobos', 'total': None}, |
| 878 |
{'name': 'proxima centauri', 'total': None}, |
| 879 |
{'name': 'proxima centauri b', 'total': None}, |
| 880 |
{'name': 'sun', 'total': None}, |
| 881 |
{'name': 'venus', 'total': None} |
| 882 |
]) |
| 883 |
|
| 884 |
def test_cte_join_alias_is_quoted(self): |
| 885 |
# A CTE-joined queryset used as a subquery gets its alias prefix |
| 886 |
# bumped, so the join alias differs from the CTE name and must be |
| 887 |
# quoted like the column references pointing at it. |
| 888 |
totals = CTE( |
| 889 |
Order.objects |
| 890 |
.values("region_id") |
| 891 |
.annotate(total=Sum("amount")) |
| 892 |
) |
| 893 |
big_orders = with_cte( |
| 894 |
totals, |
| 895 |
select=totals.join(Order, region=totals.col.region_id), |
| 896 |
).annotate(region_total=totals.col.total).filter( |
| 897 |
region_id=OuterRef("name"), |
| 898 |
region_total__gt=100, |
| 899 |
) |
| 900 |
regions = Region.objects.filter(Exists(big_orders)).order_by("name") |
| 901 |
self.assertEqual([r.name for r in regions], [ |
| 902 |
'earth', |
| 903 |
'mars', |
| 904 |
'proxima centauri', |
| 905 |
'sun', |
| 906 |
]) |
| 907 |
|
| 908 |
def test_fields_with_db_column(self): |
| 909 |
cte = CTE.recursive( |
| 910 |
lambda cte: WithDBColumn.objects.filter(id=10) |
| 911 |
.union(cte.join(WithDBColumn, id=cte.col.parent_id)) |
| 912 |
) |
| 913 |
qs = with_cte(cte, select=cte) |
| 914 |
query = str(qs.query) |
| 915 |
self.assertIn("uid", query) |
| 916 |
self.assertIn("pid", query) |
| 917 |
self.assertEqual( |
| 918 |
[(i.id, i.parent_id) for i in qs], |
| 919 |
[(i, (i - 1) if i > 1 else None) for i in range(10, 0, -1)] |
| 920 |
) |
| 921 |
|
| 922 |
@pytest.mark.skipif(django.VERSION < (5, 2), reason='Requires Django 5.2+') |
| 923 |
def test_composite_primary_key(self): |
| 924 |
from .models import Site, WithCompositePK |
| 925 |
|
| 926 |
cte = CTE(WithCompositePK.objects.all()) |
| 927 |
qs = with_cte(cte, select=cte).values(test=cte.col.pk) |
| 928 |
|
| 929 |
with pytest.raises(ValueError, match='reference column pairs'): |
| 930 |
str(qs.query) |
| 931 |
|
| 932 |
qs = with_cte(cte, select=cte).values(test1=cte.col.site, test2=cte.col.username) |
| 933 |
query = str(qs.query) |
| 934 |
self.assertIn("test1", query) |
| 935 |
self.assertIn("site_id", query) |
| 936 |
self.assertIn("test2", query) |
| 937 |
self.assertIn("username", query) |
| 938 |
self.assertEqual(list(qs), [ |
| 939 |
{ |
| 940 |
'test1': Site.objects.values_list("pk", flat=True).get(), |
| 941 |
'test2': "test_user", |
| 942 |
} |
| 943 |
]) |