@@ -758,10 +758,23 @@ ChangeVarNodesExtended(Node *node, int rt_index, int new_index,
758
758
context .sublevels_up = sublevels_up ;
759
759
context .change_RangeTblRef = change_RangeTblRef ;
760
760
761
+ /*
762
+ * Must be prepared to start with a Query or a bare expression tree; if
763
+ * it's a Query, go straight to query_tree_walker to make sure that
764
+ * sublevels_up doesn't get incremented prematurely.
765
+ */
761
766
if (node && IsA (node , Query ))
762
767
{
763
768
Query * qry = (Query * ) node ;
764
769
770
+ /*
771
+ * If we are starting at a Query, and sublevels_up is zero, then we
772
+ * must also fix rangetable indexes in the Query itself --- namely
773
+ * resultRelation, mergeTargetRelation, exclRelIndex and rowMarks
774
+ * entries. sublevels_up cannot be zero when recursing into a
775
+ * subquery, so there's no need to have the same logic inside
776
+ * ChangeVarNodes_walker.
777
+ */
765
778
if (sublevels_up == 0 )
766
779
{
767
780
ListCell * l ;
@@ -772,6 +785,7 @@ ChangeVarNodesExtended(Node *node, int rt_index, int new_index,
772
785
if (qry -> mergeTargetRelation == rt_index )
773
786
qry -> mergeTargetRelation = new_index ;
774
787
788
+ /* this is unlikely to ever be used, but ... */
775
789
if (qry -> onConflict && qry -> onConflict -> exclRelIndex == rt_index )
776
790
qry -> onConflict -> exclRelIndex = new_index ;
777
791
0 commit comments