Re: BUG #19435: Error: "No relation entry for relid 2" Triggered by Complex Join with Self-Referencing Tables

Alexander Korotkov <aekorotkov@gmail.com>

From: Alexander Korotkov <aekorotkov@gmail.com>
To: Andrei Lepikhov <lepihov@gmail.com>
Cc: Tender Wang <tndrwang@gmail.com>, Kirill Reshke <reshkekirill@gmail.com>, Fujii Masao <masao.fujii@gmail.com>, ammmkilo@163.com, pgsql-bugs@lists.postgresql.org
Date: 2026-05-25T19:26:51Z
Lists: pgsql-bugs

Attachments

Hi, Andrei!

On Fri, May 22, 2026 at 1:16 PM Andrei Lepikhov <lepihov@gmail.com> wrote:
> On 22/04/2026 17:10, Alexander Korotkov wrote:
> > On Fri, Mar 27, 2026 at 3:19 AM Tender Wang <tndrwang@gmail.com> wrote:
> >>> but I'm unsure, in general, that this approach is conservative enough.
> >>> Maybe we shouldn’t change this logic and invent one more optimisation
> >>> ‘deduplication’ stage later, before the selectivity estimation stage.
> >
> > I have another approach about to deduplication of RestrictInfo's.  The
> > field, which differs in this case, is outer_relids.  AFAICS,
> > outer_relids and incompatible_relids serves as the restriction on what
> > we can do with RestrictInfo.  So, what we can do is to ignore both
> > outer_relids and incompatible_relids during comparison, but compose a
> > union of their values for remaining RestrictInfo.  That means that
> > remaining RestrictInfo will ancest all the restrictions, and that
> > should be safe.
> >
> > What do you think?
>
> Thank you for all the work you’ve put into de-duplicating clauses.
>
> I agree that using the union of outer_relids and incompatible_relids is the
> strictest common constraint. There shouldn’t be any issues, so this approach
> should work.
>
> However, the new function relies on a hand-picked list of "semantic" fields. If
> someone adds another field to RestrictInfo, this function could break without
> warning unless they remember to update it. We should add comment hooks that say,
> "If you add a field here, update analyzejoins.c too."
>
> Also, de-duplication happens in several places. If we change the logic in
> add_non_redundant_clauses, maybe we should review the update_eclasses() code as
> well.

Please, check the updated patch.  Now restrict_infos_logically_equal()
uses old save/restore approach.  Also added guardian comment to
RestrictInfo.  update_eclasses() switched to use
restrict_infos_logically_equal() to compare RestrictInfos.

------
Regards,
Alexander Korotkov
Supabase

Commits

  1. Further improve commentary about ChangeVarNodesWalkExpression()

  2. Improve commentary about ChangeVarNodesWalkExpression().

  3. Fix self-join removal to update bare Var references in join clauses

  4. Implement Self-Join Elimination