Re: Assert failure in CTE inlining with view and correlated subquery

From: Richard Guo <guofenglinux(at)gmail(dot)com>
To: Tomas Vondra <tomas(dot)vondra(at)enterprisedb(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Assert failure in CTE inlining with view and correlated subquery
Date: 2022-04-21 07:28:32
Message-ID: CAMbWs4-M4t6b7qGz=Tbits642WzR77aQ4qRwm1KNBskqzEfLUg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, Apr 21, 2022 at 5:33 AM Tomas Vondra <tomas(dot)vondra(at)enterprisedb(dot)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

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Richard Guo 2022-04-21 07:51:53 Re: Assert failure in CTE inlining with view and correlated subquery
Previous Message John Naylor 2022-04-21 07:09:20 Re: A qsort template