Opened 12 years ago

Closed 11 years ago

Last modified 11 years ago

#18333 closed Bug (fixed)

Aggregating an annotated field does not quote the alias column name

Reported by: Michael Manfre Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: aggregate, annotate
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given the below code snippet from aggregation.BaseAggregateTestCase.test_aggregate_annotation:

vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(Avg("num_authors"))

The generated SQL does not quote the annotated field "num_authors" when used with the aggregate function. Generated SQL is of the form:

SELECT AVG(num_authors) FROM (... subquery ...)

Attachments (2)

django-ticket18333.diff (508 bytes ) - added by Michael Manfre 12 years ago.
django-ticket18333.2.diff (951 bytes ) - added by Michael Manfre 12 years ago.

Download all attachments as: .zip

Change History (10)

by Michael Manfre, 12 years ago

Attachment: django-ticket18333.diff added

by Michael Manfre, 12 years ago

Attachment: django-ticket18333.2.diff added

comment:1 by Michael Manfre, 12 years ago

I'm not aware of any databases that need to quote '*', but just in case there are I provided two patches. The second preloads the cache with '*' to prevent quoting it. Most commonly encountered by COUNT(*). Regardless of which patch is chosen (if any), 3rd party backends can override quote_cache to either have or omit this initial alias.

comment:2 by Luke Plant, 12 years ago

Is there a bug caused by this behaviour? I can't see it at the moment.

comment:3 by Anssi Kääriäinen, 12 years ago

Seems like if you use a SQL reserved keyword as the key in annotate, then you will get a broken query. No testing done here.

comment:4 by Luke Plant, 12 years ago

Needs tests: set
Triage Stage: UnreviewedAccepted

Ah, I see, I was just thinking about characters that can't be part of keyword arguments anyway, so thought there wasn't an issue.

comment:5 by Michael Manfre, 11 years ago

Updated pull request with test. https://github.com/django/django/pull/1674

comment:6 by Michael Manfre, 11 years ago

Needs tests: unset

comment:7 by Tim Graham <timograham@…>, 11 years ago

Resolution: fixed
Status: newclosed

In 9a041807fcde7ff7245696a743196d31ec7c7b5c:

Fixed #18333 - Quoted annotated column names

comment:8 by Anssi Kääriäinen <akaariai@…>, 11 years ago

In 9027da65d3590a3bd319490d78c86ef09cd04f9e:

Added '*' to quote_cache

The commit for #18333 missed quote_cache default value for *.
Refs #18333.

Note: See TracTickets for help on using tickets.
Back to Top