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

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: Alexander Korotkov <aekorotkov@gmail.com>
Cc: Andrei Lepikhov <lepihov@gmail.com>, Kirill Reshke <reshkekirill@gmail.com>, Tender Wang <tndrwang@gmail.com>, Fujii Masao <masao.fujii@gmail.com>, ammmkilo@163.com, pgsql-bugs@lists.postgresql.org
Date: 2026-03-20T14:30:06Z
Lists: pgsql-bugs
Alexander Korotkov <aekorotkov@gmail.com> writes:
> OK. I've pushed this.

I don't love this patch.  It fixes the functional problem, but it
does nothing to fix the underlying cause of that problem, namely
the abysmal under-documentation of the ChangeVarNodesXXX functions.
There are very specific assumptions about whether the recursion
is starting at a Query or not, and the code will do the wrong
thing if invoked at the wrong node level.

In particular, imagine that ChangeVarNodes_walker is invoked
directly on a Query node, something that ChangeVarNodesExtended
is careful not to do.  It will increment sublevels_up immediately
and thus process the contents of the Query with sublevels_up==1,
meaning it will not recognize local Vars as needing adjustment.

At the very least we need to add comments, but I wonder if we
don't actually need an Assert that ChangeVarNodesWalkExpression
is not invoked directly on a Query.  It would have done the
right thing before this patch, but now it won't.  That's an
okay tradeoff for fixing the bare-Var case, but not documenting
what you did is not okay.

			regards, tom lane



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