#29214: Invalid SQL generated when annotating a subquery with an outerref to an
annotated field.
-------------------------------------+-------------------------------------
     Reporter:  Oskar Persson        |                    Owner:  nobody
         Type:  Bug                  |                   Status:  new
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:  queryset             |             Triage Stage:  Accepted
  annotations                        |
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Changes (by Chetan Khanna):

 * cc: Chetan Khanna (added)


Comment:

 Yes. On running the same query, I get the following SQL and traceback:

 {{{
 latest_parent =
 Recursive.objects.filter(link=OuterRef('parent_link')).order_by('id')

 Recursive.objects.filter(parent__isnull=False) \
         .annotate(parent_link=F('parent__link')) \
         .annotate(p=Subquery(latest_parent.values('pk')[:1])) \
         .update(parent_id=F('p'))
 }}}

 SQL:

 {{{
 UPDATE "recursive_model"
    SET "parent_id" = (
         SELECT U0."id"
           FROM "recursive_model" U0
          WHERE U0."link" = T2."link"
          ORDER BY U0."id" ASC
          LIMIT 1
        )
  WHERE "recursive_model"."id" IN (
         SELECT V0."id"
           FROM "recursive_model" V0
          INNER JOIN "recursive_model" V1
             ON (V0."parent_id" = V1."id")
          WHERE V0."parent_id" IS NOT NULL
        )
 }}}

 Traceback:

 {{{
 ProgrammingError: missing FROM-clause entry for table "t2"
 LINE 1: ...."id" FROM "recursive_model" U0 WHERE U0."link" = T2."link" ...
 }}}

 Unfortunately I haven't looked deeper, but I am planning to during this
 weekend. I'll report if I get something else.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/29214#comment:11>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/070.5d88bc10aca6a40cc1334e776213b133%40djangoproject.com.

Reply via email to