| 1 |
import pickle |
| 2 |
from unittest import SkipTest |
| 3 |
|
| 4 |
from django.db.models import IntegerField, TextField |
| 5 |
from django.db.models.expressions import ( |
| 6 |
Case, |
| 7 |
Exists, |
| 8 |
ExpressionWrapper, |
| 9 |
F, |
| 10 |
OuterRef, |
| 11 |
Q, |
| 12 |
Value, |
| 13 |
When, |
| 14 |
) |
| 15 |
from django.db.models.functions import Concat |
| 16 |
from django.db.utils import DatabaseError |
| 17 |
from django.test import TestCase |
| 18 |
|
| 19 |
from django_cte import With |
| 20 |
|
| 21 |
from .models import KeyPair, Region |
| 22 |
|
| 23 |
int_field = IntegerField() |
| 24 |
text_field = TextField() |
| 25 |
|
| 26 |
|
| 27 |
class TestRecursiveCTE(TestCase): |
| 28 |
|
| 29 |
def test_recursive_cte_query(self): |
| 30 |
def make_regions_cte(cte): |
| 31 |
return Region.objects.filter( |
| 32 |
# non-recursive: get root nodes |
| 33 |
parent__isnull=True |
| 34 |
).values( |
| 35 |
"name", |
| 36 |
path=F("name"), |
| 37 |
depth=Value(0, output_field=int_field), |
| 38 |
).union( |
| 39 |
# recursive union: get descendants |
| 40 |
cte.join(Region, parent=cte.col.name).values( |
| 41 |
"name", |
| 42 |
path=Concat( |
| 43 |
cte.col.path, Value(" / "), F("name"), |
| 44 |
output_field=text_field, |
| 45 |
), |
| 46 |
depth=cte.col.depth + Value(1, output_field=int_field), |
| 47 |
), |
| 48 |
all=True, |
| 49 |
) |
| 50 |
|
| 51 |
cte = With.recursive(make_regions_cte) |
| 52 |
|
| 53 |
regions = ( |
| 54 |
cte.join(Region, name=cte.col.name) |
| 55 |
.with_cte(cte) |
| 56 |
.annotate( |
| 57 |
path=cte.col.path, |
| 58 |
depth=cte.col.depth, |
| 59 |
) |
| 60 |
.filter(depth=2) |
| 61 |
.order_by("path") |
| 62 |
) |
| 63 |
print(regions.query) |
| 64 |
|
| 65 |
data = [(r.name, r.path, r.depth) for r in regions] |
| 66 |
self.assertEqual(data, [ |
| 67 |
('moon', 'sun / earth / moon', 2), |
| 68 |
('deimos', 'sun / mars / deimos', 2), |
| 69 |
('phobos', 'sun / mars / phobos', 2), |
| 70 |
]) |
| 71 |
|
| 72 |
def test_recursive_cte_reference_in_condition(self): |
| 73 |
def make_regions_cte(cte): |
| 74 |
return Region.objects.filter( |
| 75 |
parent__isnull=True |
| 76 |
).values( |
| 77 |
"name", |
| 78 |
path=F("name"), |
| 79 |
depth=Value(0, output_field=int_field), |
| 80 |
is_planet=Value(0, output_field=int_field), |
| 81 |
).union( |
| 82 |
cte.join( |
| 83 |
Region, parent=cte.col.name |
| 84 |
).annotate( |
| 85 |
# annotations for filter and CASE/WHEN conditions |
| 86 |
parent_name=ExpressionWrapper( |
| 87 |
cte.col.name, |
| 88 |
output_field=text_field, |
| 89 |
), |
| 90 |
parent_depth=ExpressionWrapper( |
| 91 |
cte.col.depth, |
| 92 |
output_field=int_field, |
| 93 |
), |
| 94 |
).filter( |
| 95 |
~Q(parent_name="mars"), |
| 96 |
).values( |
| 97 |
"name", |
| 98 |
path=Concat( |
| 99 |
cte.col.path, Value("\x01"), F("name"), |
| 100 |
output_field=text_field, |
| 101 |
), |
| 102 |
depth=cte.col.depth + Value(1, output_field=int_field), |
| 103 |
is_planet=Case( |
| 104 |
When(parent_depth=0, then=Value(1)), |
| 105 |
default=Value(0), |
| 106 |
output_field=int_field, |
| 107 |
), |
| 108 |
), |
| 109 |
all=True, |
| 110 |
) |
| 111 |
cte = With.recursive(make_regions_cte) |
| 112 |
regions = cte.join(Region, name=cte.col.name).with_cte(cte).annotate( |
| 113 |
path=cte.col.path, |
| 114 |
depth=cte.col.depth, |
| 115 |
is_planet=cte.col.is_planet, |
| 116 |
).order_by("path") |
| 117 |
|
| 118 |
data = [(r.path.split("\x01"), r.is_planet) for r in regions] |
| 119 |
print(data) |
| 120 |
self.assertEqual(data, [ |
| 121 |
(["bernard's star"], 0), |
| 122 |
(['proxima centauri'], 0), |
| 123 |
(['proxima centauri', 'proxima centauri b'], 1), |
| 124 |
(['sun'], 0), |
| 125 |
(['sun', 'earth'], 1), |
| 126 |
(['sun', 'earth', 'moon'], 0), |
| 127 |
(['sun', 'mars'], 1), # mars moons excluded: parent_name != 'mars' |
| 128 |
(['sun', 'mercury'], 1), |
| 129 |
(['sun', 'venus'], 1), |
| 130 |
]) |
| 131 |
|
| 132 |
def test_recursive_cte_with_empty_union_part(self): |
| 133 |
def make_regions_cte(cte): |
| 134 |
return Region.objects.none().union( |
| 135 |
cte.join(Region, parent=cte.col.name), |
| 136 |
all=True, |
| 137 |
) |
| 138 |
cte = With.recursive(make_regions_cte) |
| 139 |
regions = cte.join(Region, name=cte.col.name).with_cte(cte) |
| 140 |
|
| 141 |
print(regions.query) |
| 142 |
try: |
| 143 |
self.assertEqual(regions.count(), 0) |
| 144 |
except DatabaseError: |
| 145 |
raise SkipTest( |
| 146 |
"Expected failure: QuerySet omits `EmptyQuerySet` from " |
| 147 |
"UNION queries resulting in invalid CTE SQL" |
| 148 |
) |
| 149 |
|
| 150 |
# -- recursive query "cte" does not have the form |
| 151 |
# -- non-recursive-term UNION [ALL] recursive-term |
| 152 |
# WITH RECURSIVE cte AS ( |
| 153 |
# SELECT "tests_region"."name", "tests_region"."parent_id" |
| 154 |
# FROM "tests_region", "cte" |
| 155 |
# WHERE "tests_region"."parent_id" = ("cte"."name") |
| 156 |
# ) |
| 157 |
# SELECT COUNT(*) |
| 158 |
# FROM "tests_region", "cte" |
| 159 |
# WHERE "tests_region"."name" = ("cte"."name") |
| 160 |
|
| 161 |
def test_circular_ref_error(self): |
| 162 |
def make_bad_cte(cte): |
| 163 |
# NOTE: not a valid recursive CTE query |
| 164 |
return cte.join(Region, parent=cte.col.name).values( |
| 165 |
depth=cte.col.depth + 1, |
| 166 |
) |
| 167 |
cte = With.recursive(make_bad_cte) |
| 168 |
regions = cte.join(Region, name=cte.col.name).with_cte(cte) |
| 169 |
with self.assertRaises(ValueError) as context: |
| 170 |
print(regions.query) |
| 171 |
self.assertIn("Circular reference:", str(context.exception)) |
| 172 |
|
| 173 |
def test_attname_should_not_mask_col_name(self): |
| 174 |
def make_regions_cte(cte): |
| 175 |
return Region.objects.filter( |
| 176 |
name="moon" |
| 177 |
).values( |
| 178 |
"name", |
| 179 |
"parent_id", |
| 180 |
).union( |
| 181 |
cte.join(Region, name=cte.col.parent_id).values( |
| 182 |
"name", |
| 183 |
"parent_id", |
| 184 |
), |
| 185 |
all=True, |
| 186 |
) |
| 187 |
cte = With.recursive(make_regions_cte) |
| 188 |
regions = ( |
| 189 |
Region.objects.all() |
| 190 |
.with_cte(cte) |
| 191 |
.annotate(_ex=Exists( |
| 192 |
cte.queryset() |
| 193 |
.values(value=Value("1", output_field=int_field)) |
| 194 |
.filter(name=OuterRef("name")) |
| 195 |
)) |
| 196 |
.filter(_ex=True) |
| 197 |
.order_by("name") |
| 198 |
) |
| 199 |
print(regions.query) |
| 200 |
|
| 201 |
data = [r.name for r in regions] |
| 202 |
self.assertEqual(data, ['earth', 'moon', 'sun']) |
| 203 |
|
| 204 |
def test_pickle_recursive_cte_queryset(self): |
| 205 |
def make_regions_cte(cte): |
| 206 |
return Region.objects.filter( |
| 207 |
parent__isnull=True |
| 208 |
).annotate( |
| 209 |
depth=Value(0, output_field=int_field), |
| 210 |
).union( |
| 211 |
cte.join(Region, parent=cte.col.name).annotate( |
| 212 |
depth=cte.col.depth + Value(1, output_field=int_field), |
| 213 |
), |
| 214 |
all=True, |
| 215 |
) |
| 216 |
cte = With.recursive(make_regions_cte) |
| 217 |
regions = cte.queryset().with_cte(cte).filter(depth=2).order_by("name") |
| 218 |
|
| 219 |
pickled_qs = pickle.loads(pickle.dumps(regions)) |
| 220 |
|
| 221 |
data = [(r.name, r.depth) for r in pickled_qs] |
| 222 |
self.assertEqual(data, [(r.name, r.depth) for r in regions]) |
| 223 |
self.assertEqual(data, [('deimos', 2), ('moon', 2), ('phobos', 2)]) |
| 224 |
|
| 225 |
def test_alias_change_in_annotation(self): |
| 226 |
def make_regions_cte(cte): |
| 227 |
return Region.objects.filter( |
| 228 |
parent__name="sun", |
| 229 |
).annotate( |
| 230 |
value=F('name'), |
| 231 |
).union( |
| 232 |
cte.join( |
| 233 |
Region.objects.all().annotate( |
| 234 |
value=F('name'), |
| 235 |
), |
| 236 |
parent_id=cte.col.name, |
| 237 |
), |
| 238 |
all=True, |
| 239 |
) |
| 240 |
cte = With.recursive(make_regions_cte) |
| 241 |
query = cte.queryset().with_cte(cte) |
| 242 |
|
| 243 |
exclude_leaves = With(cte.queryset().filter( |
| 244 |
parent__name='sun', |
| 245 |
).annotate( |
| 246 |
value=Concat(F('name'), F('name')) |
| 247 |
), name='value_cte') |
| 248 |
|
| 249 |
query = query.annotate( |
| 250 |
_exclude_leaves=Exists( |
| 251 |
exclude_leaves.queryset().filter( |
| 252 |
name=OuterRef("name"), |
| 253 |
value=OuterRef("value"), |
| 254 |
) |
| 255 |
) |
| 256 |
).filter(_exclude_leaves=True).with_cte(exclude_leaves) |
| 257 |
print(query.query) |
| 258 |
|
| 259 |
# Nothing should be returned. |
| 260 |
self.assertFalse(query) |
| 261 |
|
| 262 |
def test_alias_as_subquery(self): |
| 263 |
# This test covers CTEColumnRef.relabeled_clone |
| 264 |
def make_regions_cte(cte): |
| 265 |
return KeyPair.objects.filter( |
| 266 |
parent__key="level 1", |
| 267 |
).annotate( |
| 268 |
rank=F('value'), |
| 269 |
).union( |
| 270 |
cte.join( |
| 271 |
KeyPair.objects.all().order_by(), |
| 272 |
parent_id=cte.col.id, |
| 273 |
).annotate( |
| 274 |
rank=F('value'), |
| 275 |
), |
| 276 |
all=True, |
| 277 |
) |
| 278 |
cte = With.recursive(make_regions_cte) |
| 279 |
children = cte.queryset().with_cte(cte) |
| 280 |
|
| 281 |
xdups = With(cte.queryset().filter( |
| 282 |
parent__key="level 1", |
| 283 |
).annotate( |
| 284 |
rank=F('value') |
| 285 |
).values('id', 'rank'), name='xdups') |
| 286 |
|
| 287 |
children = children.annotate( |
| 288 |
_exclude=Exists( |
| 289 |
( |
| 290 |
xdups.queryset().filter( |
| 291 |
id=OuterRef("id"), |
| 292 |
rank=OuterRef("rank"), |
| 293 |
) |
| 294 |
) |
| 295 |
) |
| 296 |
).filter(_exclude=True).with_cte(xdups) |
| 297 |
|
| 298 |
print(children.query) |
| 299 |
query = KeyPair.objects.filter(parent__in=children) |
| 300 |
print(query.query) |
| 301 |
print(children.query) |
| 302 |
self.assertEqual(query.get().key, 'level 3') |
| 303 |
# Tests the case in which children's query was modified since it was |
| 304 |
# used in a subquery to define `query` above. |
| 305 |
self.assertEqual( |
| 306 |
list(c.key for c in children), |
| 307 |
['level 2', 'level 2'] |
| 308 |
) |
| 309 |
|
| 310 |
def test_materialized(self): |
| 311 |
# This test covers MATERIALIZED option in SQL query |
| 312 |
def make_regions_cte(cte): |
| 313 |
return KeyPair.objects.all() |
| 314 |
cte = With.recursive(make_regions_cte, materialized=True) |
| 315 |
|
| 316 |
query = KeyPair.objects.with_cte(cte) |
| 317 |
print(query.query) |
| 318 |
self.assertTrue( |
| 319 |
str(query.query).startswith('WITH RECURSIVE "cte" AS MATERIALIZED') |
| 320 |
) |
| 321 |
|
| 322 |
def test_recursive_self_queryset(self): |
| 323 |
def make_regions_cte(cte): |
| 324 |
return Region.objects.filter( |
| 325 |
pk="earth" |
| 326 |
).values("pk").union( |
| 327 |
cte.join(Region, parent=cte.col.pk).values("pk") |
| 328 |
) |
| 329 |
cte = With.recursive(make_regions_cte) |
| 330 |
queryset = cte.queryset().with_cte(cte).order_by("pk") |
| 331 |
print(queryset.query) |
| 332 |
self.assertEqual(list(queryset), [ |
| 333 |
{'pk': 'earth'}, |
| 334 |
{'pk': 'moon'}, |
| 335 |
]) |