-
Notifications
You must be signed in to change notification settings - Fork 5
Add easy way to annotate Route QS with "level" #131
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
from django.db.models.expressions import Func | ||
|
||
|
||
class CharCount(Func): | ||
""" | ||
Count the occurrences of a char within a field. | ||
|
||
Works by finding the difference in length between the whole string, and the | ||
string with the char removed. | ||
""" | ||
template = "CHAR_LENGTH(%(field)s) - CHAR_LENGTH(REPLACE(%(field)s, '%(char)s', ''))" | ||
|
||
def __init__(self, field, *, char, **extra): | ||
""" | ||
Add some validation to the invocation. | ||
|
||
"Char" must always: | ||
|
||
- be passed as a keyword argument | ||
- be exactly one character. | ||
""" | ||
if len(char) != 1: | ||
raise ValueError('CharCount must count exactly one char.') | ||
super().__init__(field, char=char, **extra) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
from polymorphic.managers import PolymorphicManager | ||
|
||
from .exceptions import InvalidURL | ||
from .expressions import CharCount | ||
from .utils import split_path | ||
|
||
|
||
|
@@ -72,3 +73,16 @@ def move_branch(self, old_url, new_url): | |
Value(new_url), | ||
Substr('url', len(old_url) + 1), # 1 indexed | ||
)) | ||
|
||
def with_level(self, level=None): | ||
""" | ||
Annotate the queryset with the (1-indexed) level of each item. | ||
|
||
The level reflects the number of forward slashes in the path. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we guarantee elsewhere that a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, it's a strange necessity of conman -- it makes other similar operations easy. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. On the whole, it shouldn't cause too many issues, I hope. |
||
|
||
If "level" is passed in, the queryset will be filtered by the level. | ||
""" | ||
qs = self.annotate(level=CharCount('url', char='/')) | ||
if level is None: | ||
return qs | ||
return qs.filter(level=level) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -136,6 +136,16 @@ def handle(self, request, path): | |
# Deal with the request | ||
return handler.handle(request, path) | ||
|
||
@property | ||
def level(self): | ||
"""Fetch the one-indexed 'level' of this item in the URL tree.""" | ||
return self.url.count('/') | ||
|
||
@level.setter | ||
def level(self, new_value): | ||
"""Silently fails to allow queryset annotation to work.""" | ||
pass | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are you sure the annotation is used instead of the property if it exists? Or does that not matter? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's not that the annotation is used, exactly, it's that when an annotated object is instantiated, the attribute is set. Without this, and with the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see - the annotation is used for sql-level operations like filtering, but the descriptor whenever we're in python. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Exactly :) |
||
|
||
def move_to(self, new_url, *, move_children): | ||
""" | ||
Move this Route to a new url. | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
from django.db import connection | ||
from django.test import TestCase | ||
from django.test.utils import CaptureQueriesContext | ||
|
||
from conman.routes.expressions import CharCount | ||
from conman.routes.models import Route | ||
|
||
from .factories import RouteFactory | ||
|
||
|
||
class TestCharCount(TestCase): | ||
"""Tests for CharCount.""" | ||
def test_query(self): | ||
"""Match the exact value of the generated query.""" | ||
with CaptureQueriesContext(connection): | ||
# The "only" here is handy to keep the query as short as possible. | ||
list(Route.objects.only('id').annotate(level=CharCount('url', char='/'))) | ||
# Excuse the line wrapping here -- I wasn't sure of a nice way to do it. | ||
# I decided it was better to just keep it simple. | ||
expected = ( | ||
'SELECT "routes_route"."id", ' + | ||
'CHAR_LENGTH("routes_route"."url") - ' + | ||
'''CHAR_LENGTH(REPLACE("routes_route"."url", '/', '')) AS "level" ''' + | ||
'FROM "routes_route"' | ||
) | ||
self.assertEqual(connection.queries[0]['sql'], expected) | ||
|
||
def test_annotation(self): | ||
"""Test the expression can be used for annotation.""" | ||
RouteFactory.create(url='/sixth/level/path/including/root/') | ||
route = Route.objects.annotate(level=CharCount('url', char='/')).get() | ||
self.assertEqual(route.level, 6) # The number of "/" in the path. | ||
|
||
def test_calling_format(self): | ||
"""Ensure the 'char' argument is always a keyword-arg.""" | ||
with self.assertRaises(TypeError): | ||
CharCount('url', 'a') | ||
|
||
def test_char_length(self): | ||
"""Ensure 'char' length is always 1.""" | ||
msg = 'CharCount must count exactly one char.' | ||
for not_a_char in ['', 'no']: | ||
with self.subTest(char=not_a_char): | ||
with self.assertRaisesMessage(ValueError, msg): | ||
CharCount('url', char=not_a_char) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see why you chose 1-indexed, but I'm not sure that's the best api. It seems more natural to me to care about how many parts the url has rather than the number of
/
separators.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I wasn't sure about it myself. I went for this simply because the implementation was marginally easier -- you'll probably not be the last person to think it's strange -- I'll look into changing it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
d3963e4