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