Re: Assert failure in CTE inlining with view and correlated subquery - Mailing list pgsql-hackers

From Richard Guo
Subject Re: Assert failure in CTE inlining with view and correlated subquery
Date
Msg-id CAMbWs4-M4t6b7qGz=Tbits642WzR77aQ4qRwm1KNBskqzEfLUg@mail.gmail.com
Whole thread Raw
In response to Assert failure in CTE inlining with view and correlated subquery  (Tomas Vondra <tomas.vondra@enterprisedb.com>)
List pgsql-hackers

On Thu, Apr 21, 2022 at 5:33 AM Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:

The difference between plans in (2) and (3) is interesting, because it
seems the CTE got inlined, so why was the refcount not decremented?

The query is not actually referencing the cte. So the cte range table
entry would not appear anywhere in the query tree. That's why refcount
is not decremented after inline cte walker.

If we explicitly reference the cte in the query, say in the targetlist,
it would then work.

# explain (costs off) SELECT * FROM results_agg ORDER BY 1;
              QUERY PLAN
---------------------------------------
 Sort
   Sort Key: r.run
   ->  HashAggregate
         Group Key: r.run
         ->  Seq Scan on results r
         SubPlan 1
           ->  Seq Scan on results
                 Filter: (run = r.run)
(8 rows)

IMO the culprit is that we incorrectly set cterefcount to one while
actually the cte is not referenced at all.

Thanks
Richard 

pgsql-hackers by date:

Previous
From: John Naylor
Date:
Subject: Re: A qsort template
Next
From: Richard Guo
Date:
Subject: Re: Assert failure in CTE inlining with view and correlated subquery