This repository has been archived by the owner on Apr 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Add easy way to annotate Route QS with "level" #131
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
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='/fifth/level/zero/indexed/path/') | ||
route = Route.objects.annotate(level=CharCount('url', char='/')).get() | ||
# The number of "/" in the path minus one for zero-indexing. | ||
self.assertEqual(route.level, 5) | ||
|
||
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
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 comment
The 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
@property
, a "can't set attribute" error is raised.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 - 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 comment
The reason will be displayed to describe this comment to others. Learn more.
Exactly :)