Opened 3 years ago

Closed 3 years ago

#33435 closed Cleanup/optimization (fixed)

Subquery.as_sql() generates invalid SQL.

Reported by: M1ha Shvn Owned by: Mohamed Nabil Rady
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: subquery, as_sql
Cc: Simon Charette Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description (last modified by M1ha Shvn)

Since this commit Subquery.as_sql(...) method returns incorrect SQL removing first and last symbols instead of absent breakets. Adding Subquery().query.subquery = True attribute fixes the problem. From my point of view, it should be set in Subquery constructor.

from django.db import connection
from apps.models import App

q = Subquery(App.objects.all())

print(str(q.query))

# Output SQL is valid:
#  'SELECT "apps_app"."id", "apps_app"."name" FROM "apps_app"'

print(q.as_sql(q.query.get_compiler('default'), connection))

# Outptut SQL is invalid (no S letter at the beggining and " symbol at the end):
# ('(ELECT "apps_app"."id", "apps_app"."name" FROM "apps_app)', ())

q.query.subquery = True
print(q.as_sql(q.query.get_compiler('default'), connection))

# Outputs correct result
('(SELECT "apps_app"."id", "apps_app"."name" FROM "apps_app")', ())

Change History (7)

comment:1 by M1ha Shvn, 3 years ago

Description: modified (diff)

comment:2 by Mariusz Felisiak, 3 years ago

Cc: Simon Charette added
Summary: Since django 3.0 Subquery.as_sql() generates invalid SQLSubquery.as_sql() generates invalid SQL.
Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

Sounds reasonable.

comment:3 by Simon Charette, 3 years ago

Sounds reasonable to me as well, I'd only suggest we .clone() the query before altering though.

comment:4 by Mohamed Nabil Rady, 3 years ago

Easy pickings: set
Has patch: set
Owner: changed from nobody to Mohamed Nabil Rady
Status: newassigned

Pull request: https://github.com/django/django/pull/15320.

Ran back-end tests and they went fine.

comment:5 by Mariusz Felisiak, 3 years ago

Needs tests: set

comment:6 by Mariusz Felisiak, 3 years ago

Needs tests: unset
Triage Stage: AcceptedReady for checkin

comment:7 by Mariusz Felisiak <felisiak.mariusz@…>, 3 years ago

Resolution: fixed
Status: assignedclosed

In f37face3:

Fixed #33435 -- Fixed invalid SQL generatered by Subquery.as_sql().

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