LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - appendinfo.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 94.7 % 337 319
Test Date: 2026-09-03 09:15:55 Functions: 100.0 % 14 14
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 71.1 % 218 155

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * appendinfo.c
       4                 :             :  *    Routines for mapping between append parent(s) and children
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/optimizer/util/appendinfo.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include "access/htup_details.h"
      18                 :             : #include "access/sysattr.h"
      19                 :             : #include "access/table.h"
      20                 :             : #include "foreign/fdwapi.h"
      21                 :             : #include "nodes/makefuncs.h"
      22                 :             : #include "nodes/nodeFuncs.h"
      23                 :             : #include "optimizer/appendinfo.h"
      24                 :             : #include "optimizer/pathnode.h"
      25                 :             : #include "optimizer/planmain.h"
      26                 :             : #include "parser/parsetree.h"
      27                 :             : #include "utils/lsyscache.h"
      28                 :             : #include "utils/rel.h"
      29                 :             : #include "utils/syscache.h"
      30                 :             : 
      31                 :             : 
      32                 :             : typedef struct
      33                 :             : {
      34                 :             :     PlannerInfo *root;
      35                 :             :     int         nappinfos;
      36                 :             :     AppendRelInfo **appinfos;
      37                 :             : } adjust_appendrel_attrs_context;
      38                 :             : 
      39                 :             : static void make_inh_translation_list(Relation oldrelation,
      40                 :             :                                       Relation newrelation,
      41                 :             :                                       Index newvarno,
      42                 :             :                                       AppendRelInfo *appinfo);
      43                 :             : static Node *adjust_appendrel_attrs_mutator(Node *node,
      44                 :             :                                             adjust_appendrel_attrs_context *context);
      45                 :             : 
      46                 :             : 
      47                 :             : /*
      48                 :             :  * make_append_rel_info
      49                 :             :  *    Build an AppendRelInfo for the parent-child pair
      50                 :             :  */
      51                 :             : AppendRelInfo *
      52                 :       35488 : make_append_rel_info(Relation parentrel, Relation childrel,
      53                 :             :                      Index parentRTindex, Index childRTindex)
      54                 :             : {
      55                 :       35488 :     AppendRelInfo *appinfo = makeNode(AppendRelInfo);
      56                 :             : 
      57                 :       35488 :     appinfo->parent_relid = parentRTindex;
      58                 :       35488 :     appinfo->child_relid = childRTindex;
      59                 :       35488 :     appinfo->parent_reltype = parentrel->rd_rel->reltype;
      60                 :       35488 :     appinfo->child_reltype = childrel->rd_rel->reltype;
      61                 :       35488 :     make_inh_translation_list(parentrel, childrel, childRTindex, appinfo);
      62                 :       35487 :     appinfo->parent_reloid = RelationGetRelid(parentrel);
      63                 :             : 
      64                 :       35487 :     return appinfo;
      65                 :             : }
      66                 :             : 
      67                 :             : /*
      68                 :             :  * make_inh_translation_list
      69                 :             :  *    Build the list of translations from parent Vars to child Vars for
      70                 :             :  *    an inheritance child, as well as a reverse-translation array.
      71                 :             :  *
      72                 :             :  * The reverse-translation array has an entry for each child relation
      73                 :             :  * column, which is either the 1-based index of the corresponding parent
      74                 :             :  * column, or 0 if there's no match (that happens for dropped child columns,
      75                 :             :  * as well as child columns beyond those of the parent, which are allowed in
      76                 :             :  * traditional inheritance though not partitioning).
      77                 :             :  *
      78                 :             :  * For paranoia's sake, we match type/collation as well as attribute name.
      79                 :             :  */
      80                 :             : static void
      81                 :       35488 : make_inh_translation_list(Relation oldrelation, Relation newrelation,
      82                 :             :                           Index newvarno,
      83                 :             :                           AppendRelInfo *appinfo)
      84                 :             : {
      85                 :       35488 :     List       *vars = NIL;
      86                 :             :     AttrNumber *pcolnos;
      87                 :       35488 :     TupleDesc   old_tupdesc = RelationGetDescr(oldrelation);
      88                 :       35488 :     TupleDesc   new_tupdesc = RelationGetDescr(newrelation);
      89                 :       35488 :     Oid         new_relid = RelationGetRelid(newrelation);
      90                 :       35488 :     int         oldnatts = old_tupdesc->natts;
      91                 :       35488 :     int         newnatts = new_tupdesc->natts;
      92                 :             :     int         old_attno;
      93                 :       35488 :     int         new_attno = 0;
      94                 :             : 
      95                 :             :     /* Initialize reverse-translation array with all entries zero */
      96                 :       35488 :     appinfo->num_child_cols = newnatts;
      97                 :       35488 :     appinfo->parent_colnos = pcolnos = palloc0_array(AttrNumber, newnatts);
      98                 :             : 
      99         [ +  + ]:      129317 :     for (old_attno = 0; old_attno < oldnatts; old_attno++)
     100                 :             :     {
     101                 :             :         Form_pg_attribute att;
     102                 :             :         char       *attname;
     103                 :             :         Oid         atttypid;
     104                 :             :         int32       atttypmod;
     105                 :             :         Oid         attcollation;
     106                 :             : 
     107                 :       93830 :         att = TupleDescAttr(old_tupdesc, old_attno);
     108         [ +  + ]:       93830 :         if (att->attisdropped)
     109                 :             :         {
     110                 :             :             /* Just put NULL into this list entry */
     111                 :        2643 :             vars = lappend(vars, NULL);
     112                 :        2643 :             continue;
     113                 :             :         }
     114                 :       91187 :         attname = NameStr(att->attname);
     115                 :       91187 :         atttypid = att->atttypid;
     116                 :       91187 :         atttypmod = att->atttypmod;
     117                 :       91187 :         attcollation = att->attcollation;
     118                 :             : 
     119                 :             :         /*
     120                 :             :          * When we are generating the "translation list" for the parent table
     121                 :             :          * of an inheritance set, no need to search for matches.
     122                 :             :          */
     123         [ +  + ]:       91187 :         if (oldrelation == newrelation)
     124                 :             :         {
     125                 :        6063 :             vars = lappend(vars, makeVar(newvarno,
     126                 :        6063 :                                          (AttrNumber) (old_attno + 1),
     127                 :             :                                          atttypid,
     128                 :             :                                          atttypmod,
     129                 :             :                                          attcollation,
     130                 :             :                                          0));
     131                 :        6063 :             pcolnos[old_attno] = old_attno + 1;
     132                 :        6063 :             continue;
     133                 :             :         }
     134                 :             : 
     135                 :             :         /*
     136                 :             :          * Otherwise we have to search for the matching column by name.
     137                 :             :          * There's no guarantee it'll have the same column position, because
     138                 :             :          * of cases like ALTER TABLE ADD COLUMN and multiple inheritance.
     139                 :             :          * However, in simple cases, the relative order of columns is mostly
     140                 :             :          * the same in both relations, so try the column of newrelation that
     141                 :             :          * follows immediately after the one that we just found, and if that
     142                 :             :          * fails, let syscache handle it.
     143                 :             :          */
     144         [ +  + ]:       85124 :         if (new_attno >= newnatts ||
     145         [ +  + ]:       83288 :             (att = TupleDescAttr(new_tupdesc, new_attno))->attisdropped ||
     146         [ +  + ]:       82428 :             strcmp(attname, NameStr(att->attname)) != 0)
     147                 :             :         {
     148                 :             :             HeapTuple   newtup;
     149                 :             : 
     150                 :        7047 :             newtup = SearchSysCacheAttName(new_relid, attname);
     151         [ -  + ]:        7047 :             if (!HeapTupleIsValid(newtup))
     152         [ #  # ]:           0 :                 elog(ERROR, "could not find inherited attribute \"%s\" of relation \"%s\"",
     153                 :             :                      attname, RelationGetRelationName(newrelation));
     154                 :        7047 :             new_attno = ((Form_pg_attribute) GETSTRUCT(newtup))->attnum - 1;
     155                 :             :             Assert(new_attno >= 0 && new_attno < newnatts);
     156                 :        7047 :             ReleaseSysCache(newtup);
     157                 :             : 
     158                 :        7047 :             att = TupleDescAttr(new_tupdesc, new_attno);
     159                 :             :         }
     160                 :             : 
     161                 :             :         /* Found it, check type and collation match */
     162   [ +  +  -  + ]:       85124 :         if (atttypid != att->atttypid || atttypmod != att->atttypmod)
     163         [ +  - ]:           1 :             ereport(ERROR,
     164                 :             :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
     165                 :             :                      errmsg("attribute \"%s\" of relation \"%s\" does not match parent's type",
     166                 :             :                             attname, RelationGetRelationName(newrelation))));
     167         [ -  + ]:       85123 :         if (attcollation != att->attcollation)
     168         [ #  # ]:           0 :             ereport(ERROR,
     169                 :             :                     (errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
     170                 :             :                      errmsg("attribute \"%s\" of relation \"%s\" does not match parent's collation",
     171                 :             :                             attname, RelationGetRelationName(newrelation))));
     172                 :             : 
     173                 :       85123 :         vars = lappend(vars, makeVar(newvarno,
     174                 :       85123 :                                      (AttrNumber) (new_attno + 1),
     175                 :             :                                      atttypid,
     176                 :             :                                      atttypmod,
     177                 :             :                                      attcollation,
     178                 :             :                                      0));
     179                 :       85123 :         pcolnos[new_attno] = old_attno + 1;
     180                 :       85123 :         new_attno++;
     181                 :             :     }
     182                 :             : 
     183                 :       35487 :     appinfo->translated_vars = vars;
     184                 :       35487 : }
     185                 :             : 
     186                 :             : /*
     187                 :             :  * adjust_appendrel_attrs
     188                 :             :  *    Copy the specified query or expression and translate Vars referring to a
     189                 :             :  *    parent rel to refer to the corresponding child rel instead.  We also
     190                 :             :  *    update rtindexes appearing outside Vars, such as resultRelation and
     191                 :             :  *    jointree relids.
     192                 :             :  *
     193                 :             :  * Note: this is only applied after conversion of sublinks to subplans,
     194                 :             :  * so we don't need to cope with recursion into sub-queries.
     195                 :             :  *
     196                 :             :  * Note: this is not hugely different from what pullup_replace_vars() does;
     197                 :             :  * maybe we should try to fold the two routines together.
     198                 :             :  */
     199                 :             : Node *
     200                 :      241233 : adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos,
     201                 :             :                        AppendRelInfo **appinfos)
     202                 :             : {
     203                 :             :     adjust_appendrel_attrs_context context;
     204                 :             : 
     205                 :      241233 :     context.root = root;
     206                 :      241233 :     context.nappinfos = nappinfos;
     207                 :      241233 :     context.appinfos = appinfos;
     208                 :             : 
     209                 :             :     /* If there's nothing to adjust, don't call this function. */
     210                 :             :     Assert(nappinfos >= 1 && appinfos != NULL);
     211                 :             : 
     212                 :             :     /* Should never be translating a Query tree. */
     213                 :             :     Assert(node == NULL || !IsA(node, Query));
     214                 :             : 
     215                 :      241233 :     return adjust_appendrel_attrs_mutator(node, &context);
     216                 :             : }
     217                 :             : 
     218                 :             : static Node *
     219                 :     1262019 : adjust_appendrel_attrs_mutator(Node *node,
     220                 :             :                                adjust_appendrel_attrs_context *context)
     221                 :             : {
     222                 :     1262019 :     AppendRelInfo **appinfos = context->appinfos;
     223                 :     1262019 :     int         nappinfos = context->nappinfos;
     224                 :             :     int         cnt;
     225                 :             : 
     226         [ +  + ]:     1262019 :     if (node == NULL)
     227                 :      238343 :         return NULL;
     228         [ +  + ]:     1023676 :     if (IsA(node, Var))
     229                 :             :     {
     230                 :      454012 :         Var        *var = (Var *) copyObject(node);
     231                 :      454012 :         AppendRelInfo *appinfo = NULL;
     232                 :             : 
     233         [ -  + ]:      454012 :         if (var->varlevelsup != 0)
     234                 :           0 :             return (Node *) var;    /* no changes needed */
     235                 :             : 
     236                 :             :         /*
     237                 :             :          * You might think we need to adjust var->varnullingrels, but that
     238                 :             :          * shouldn't need any changes.  It will contain outer-join relids,
     239                 :             :          * while the transformation we are making affects only baserels.
     240                 :             :          * Below, we just merge var->varnullingrels into the translated Var.
     241                 :             :          * (We must merge not just copy: the child Var could have some
     242                 :             :          * nullingrel bits set already, and we mustn't drop those.)
     243                 :             :          *
     244                 :             :          * If var->varnullingrels isn't empty, and the translation wouldn't be
     245                 :             :          * a Var, we have to fail.  One could imagine wrapping the translated
     246                 :             :          * expression in a PlaceHolderVar, but that won't work because this is
     247                 :             :          * typically used after freezing placeholders.  Fortunately, the case
     248                 :             :          * appears unreachable at the moment.  We can see nonempty
     249                 :             :          * var->varnullingrels here, but only in cases involving partitionwise
     250                 :             :          * joining, and in such cases the translations will always be Vars.
     251                 :             :          * (Non-Var translations occur only for appendrels made by flattening
     252                 :             :          * UNION ALL subqueries.)  Should we need to make this work in future,
     253                 :             :          * a possible fix is to mandate that prepjointree.c create PHVs for
     254                 :             :          * all non-Var outputs of such subqueries, and then we could look up
     255                 :             :          * the pre-existing PHV here.  Or perhaps just wrap the translations
     256                 :             :          * that way to begin with?
     257                 :             :          *
     258                 :             :          * If var->varreturningtype is not VAR_RETURNING_DEFAULT, then that
     259                 :             :          * also needs to be copied to the translated Var.  That too would fail
     260                 :             :          * if the translation wasn't a Var, but that should never happen since
     261                 :             :          * a non-default var->varreturningtype is only used for Vars referring
     262                 :             :          * to the result relation, which should never be a flattened UNION ALL
     263                 :             :          * subquery.
     264                 :             :          */
     265                 :             : 
     266         [ +  + ]:      570684 :         for (cnt = 0; cnt < nappinfos; cnt++)
     267                 :             :         {
     268         [ +  + ]:      535990 :             if (var->varno == appinfos[cnt]->parent_relid)
     269                 :             :             {
     270                 :      419318 :                 appinfo = appinfos[cnt];
     271                 :      419318 :                 break;
     272                 :             :             }
     273                 :             :         }
     274                 :             : 
     275         [ +  + ]:      454012 :         if (appinfo)
     276                 :             :         {
     277                 :      419318 :             var->varno = appinfo->child_relid;
     278                 :             :             /* it's now a generated Var, so drop any syntactic labeling */
     279                 :      419318 :             var->varnosyn = 0;
     280                 :      419318 :             var->varattnosyn = 0;
     281         [ +  + ]:      419318 :             if (var->varattno > 0)
     282                 :             :             {
     283                 :             :                 Node       *newnode;
     284                 :             : 
     285         [ -  + ]:      404568 :                 if (var->varattno > list_length(appinfo->translated_vars))
     286         [ #  # ]:           0 :                     elog(ERROR, "attribute %d of relation \"%s\" does not exist",
     287                 :             :                          var->varattno, get_rel_name(appinfo->parent_reloid));
     288                 :      404568 :                 newnode = copyObject(list_nth(appinfo->translated_vars,
     289                 :             :                                               var->varattno - 1));
     290         [ -  + ]:      404568 :                 if (newnode == NULL)
     291         [ #  # ]:           0 :                     elog(ERROR, "attribute %d of relation \"%s\" does not exist",
     292                 :             :                          var->varattno, get_rel_name(appinfo->parent_reloid));
     293         [ +  + ]:      404568 :                 if (IsA(newnode, Var))
     294                 :             :                 {
     295                 :      396822 :                     Var        *newvar = (Var *) newnode;
     296                 :             : 
     297                 :      396822 :                     newvar->varreturningtype = var->varreturningtype;
     298                 :      396822 :                     newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
     299                 :      396822 :                                                              var->varnullingrels);
     300                 :             :                 }
     301                 :             :                 else
     302                 :             :                 {
     303         [ -  + ]:        7746 :                     if (var->varreturningtype != VAR_RETURNING_DEFAULT)
     304         [ #  # ]:           0 :                         elog(ERROR, "failed to apply returningtype to a non-Var");
     305         [ -  + ]:        7746 :                     if (var->varnullingrels != NULL)
     306         [ #  # ]:           0 :                         elog(ERROR, "failed to apply nullingrels to a non-Var");
     307                 :             :                 }
     308                 :      404568 :                 return newnode;
     309                 :             :             }
     310         [ +  + ]:       14750 :             else if (var->varattno == 0)
     311                 :             :             {
     312                 :             :                 /*
     313                 :             :                  * Whole-row Var: if we are dealing with named rowtypes, we
     314                 :             :                  * can use a whole-row Var for the child table plus a coercion
     315                 :             :                  * step to convert the tuple layout to the parent's rowtype.
     316                 :             :                  * Otherwise we have to generate a RowExpr.
     317                 :             :                  */
     318         [ +  + ]:         870 :                 if (OidIsValid(appinfo->child_reltype))
     319                 :             :                 {
     320                 :             :                     Assert(var->vartype == appinfo->parent_reltype);
     321         [ +  + ]:         826 :                     if (appinfo->parent_reltype != appinfo->child_reltype)
     322                 :             :                     {
     323                 :         660 :                         ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
     324                 :             : 
     325                 :         660 :                         r->arg = (Expr *) var;
     326                 :         660 :                         r->resulttype = appinfo->parent_reltype;
     327                 :         660 :                         r->convertformat = COERCE_IMPLICIT_CAST;
     328                 :         660 :                         r->location = -1;
     329                 :             :                         /* Make sure the Var node has the right type ID, too */
     330                 :         660 :                         var->vartype = appinfo->child_reltype;
     331                 :         660 :                         return (Node *) r;
     332                 :             :                     }
     333                 :             :                 }
     334                 :             :                 else
     335                 :             :                 {
     336                 :             :                     /*
     337                 :             :                      * Build a RowExpr containing the translated variables.
     338                 :             :                      *
     339                 :             :                      * In practice var->vartype will always be RECORDOID here,
     340                 :             :                      * so we need to come up with some suitable column names.
     341                 :             :                      * We use the parent RTE's column names.
     342                 :             :                      *
     343                 :             :                      * Note: we can't get here for inheritance cases, so there
     344                 :             :                      * is no need to worry that translated_vars might contain
     345                 :             :                      * some dummy NULLs.
     346                 :             :                      */
     347                 :             :                     RowExpr    *rowexpr;
     348                 :             :                     List       *fields;
     349                 :             :                     RangeTblEntry *rte;
     350                 :             : 
     351                 :          44 :                     rte = rt_fetch(appinfo->parent_relid,
     352                 :             :                                    context->root->parse->rtable);
     353                 :          44 :                     fields = copyObject(appinfo->translated_vars);
     354                 :          44 :                     rowexpr = makeNode(RowExpr);
     355                 :          44 :                     rowexpr->args = fields;
     356                 :          44 :                     rowexpr->row_typeid = var->vartype;
     357                 :          44 :                     rowexpr->row_format = COERCE_IMPLICIT_CAST;
     358                 :          44 :                     rowexpr->colnames = copyObject(rte->eref->colnames);
     359                 :          44 :                     rowexpr->location = -1;
     360                 :             : 
     361         [ -  + ]:          44 :                     if (var->varreturningtype != VAR_RETURNING_DEFAULT)
     362         [ #  # ]:           0 :                         elog(ERROR, "failed to apply returningtype to a non-Var");
     363         [ -  + ]:          44 :                     if (var->varnullingrels != NULL)
     364         [ #  # ]:           0 :                         elog(ERROR, "failed to apply nullingrels to a non-Var");
     365                 :             : 
     366                 :          44 :                     return (Node *) rowexpr;
     367                 :             :                 }
     368                 :             :             }
     369                 :             :             /* system attributes don't need any other translation */
     370                 :             :         }
     371         [ +  + ]:       34694 :         else if (var->varno == ROWID_VAR)
     372                 :             :         {
     373                 :             :             /*
     374                 :             :              * If it's a ROWID_VAR placeholder, see if we've reached a leaf
     375                 :             :              * target rel, for which we can translate the Var to a specific
     376                 :             :              * instantiation.  We should never be asked to translate to a set
     377                 :             :              * of relids containing more than one leaf target rel, so the
     378                 :             :              * answer will be unique.  If we're still considering non-leaf
     379                 :             :              * inheritance levels, return the ROWID_VAR Var as-is.
     380                 :             :              */
     381                 :       15830 :             Relids      leaf_result_relids = context->root->leaf_result_relids;
     382                 :       15830 :             Index       leaf_relid = 0;
     383                 :             : 
     384         [ +  + ]:       31660 :             for (cnt = 0; cnt < nappinfos; cnt++)
     385                 :             :             {
     386         [ +  + ]:       15830 :                 if (bms_is_member(appinfos[cnt]->child_relid,
     387                 :             :                                   leaf_result_relids))
     388                 :             :                 {
     389         [ -  + ]:       13964 :                     if (leaf_relid)
     390         [ #  # ]:           0 :                         elog(ERROR, "cannot translate to multiple leaf relids");
     391                 :       13964 :                     leaf_relid = appinfos[cnt]->child_relid;
     392                 :             :                 }
     393                 :             :             }
     394                 :             : 
     395         [ +  + ]:       15830 :             if (leaf_relid)
     396                 :             :             {
     397                 :             :                 RowIdentityVarInfo *ridinfo = (RowIdentityVarInfo *)
     398                 :       13964 :                     list_nth(context->root->row_identity_vars, var->varattno - 1);
     399                 :             : 
     400         [ +  + ]:       13964 :                 if (bms_is_member(leaf_relid, ridinfo->rowidrels))
     401                 :             :                 {
     402                 :             :                     /* Substitute the Var given in the RowIdentityVarInfo */
     403                 :       13914 :                     var = copyObject(ridinfo->rowidvar);
     404                 :             :                     /* ... but use the correct relid */
     405                 :       13914 :                     var->varno = leaf_relid;
     406                 :             :                     /* identity vars shouldn't have nulling rels */
     407                 :             :                     Assert(var->varnullingrels == NULL);
     408                 :             :                     /* varnosyn in the RowIdentityVarInfo is probably wrong */
     409                 :       13914 :                     var->varnosyn = 0;
     410                 :       13914 :                     var->varattnosyn = 0;
     411                 :             :                 }
     412                 :             :                 else
     413                 :             :                 {
     414                 :             :                     /*
     415                 :             :                      * This leaf rel can't return the desired value, so
     416                 :             :                      * substitute a NULL of the correct type.
     417                 :             :                      */
     418                 :          50 :                     return (Node *) makeNullConst(var->vartype,
     419                 :             :                                                   var->vartypmod,
     420                 :             :                                                   var->varcollid);
     421                 :             :                 }
     422                 :             :             }
     423                 :             :         }
     424                 :       48690 :         return (Node *) var;
     425                 :             :     }
     426         [ +  + ]:      569664 :     if (IsA(node, CurrentOfExpr))
     427                 :             :     {
     428                 :         152 :         CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
     429                 :             : 
     430         [ +  - ]:         152 :         for (cnt = 0; cnt < nappinfos; cnt++)
     431                 :             :         {
     432                 :         152 :             AppendRelInfo *appinfo = appinfos[cnt];
     433                 :             : 
     434         [ +  - ]:         152 :             if (cexpr->cvarno == appinfo->parent_relid)
     435                 :             :             {
     436                 :         152 :                 cexpr->cvarno = appinfo->child_relid;
     437                 :         152 :                 break;
     438                 :             :             }
     439                 :             :         }
     440                 :         152 :         return (Node *) cexpr;
     441                 :             :     }
     442         [ +  + ]:      569512 :     if (IsA(node, PlaceHolderVar))
     443                 :             :     {
     444                 :             :         /* Copy the PlaceHolderVar node with correct mutation of subnodes */
     445                 :             :         PlaceHolderVar *phv;
     446                 :             : 
     447                 :        2692 :         phv = (PlaceHolderVar *) expression_tree_mutator(node,
     448                 :             :                                                          adjust_appendrel_attrs_mutator,
     449                 :             :                                                          context);
     450                 :             :         /* now fix PlaceHolderVar's relid sets */
     451         [ +  - ]:        2692 :         if (phv->phlevelsup == 0)
     452                 :             :         {
     453                 :        2692 :             phv->phrels = adjust_child_relids(phv->phrels,
     454                 :             :                                               nappinfos, appinfos);
     455                 :             :             /* as above, we needn't touch phnullingrels */
     456                 :             :         }
     457                 :        2692 :         return (Node *) phv;
     458                 :             :     }
     459                 :             :     /* Shouldn't need to handle planner auxiliary nodes here */
     460                 :             :     Assert(!IsA(node, SpecialJoinInfo));
     461                 :             :     Assert(!IsA(node, AppendRelInfo));
     462                 :             :     Assert(!IsA(node, PlaceHolderInfo));
     463                 :             :     Assert(!IsA(node, MinMaxAggInfo));
     464                 :             : 
     465                 :             :     /*
     466                 :             :      * We have to process RestrictInfo nodes specially.  (Note: although
     467                 :             :      * set_append_rel_pathlist will hide RestrictInfos in the parent's
     468                 :             :      * baserestrictinfo list from us, it doesn't hide those in joininfo.)
     469                 :             :      */
     470         [ +  + ]:      566820 :     if (IsA(node, RestrictInfo))
     471                 :             :     {
     472                 :       33582 :         RestrictInfo *oldinfo = (RestrictInfo *) node;
     473                 :       33582 :         RestrictInfo *newinfo = makeNode(RestrictInfo);
     474                 :             : 
     475                 :             :         /* Copy all flat-copiable fields, notably including rinfo_serial */
     476                 :       33582 :         memcpy(newinfo, oldinfo, sizeof(RestrictInfo));
     477                 :             : 
     478                 :             :         /* Recursively fix the clause itself */
     479                 :       33582 :         newinfo->clause = (Expr *)
     480                 :       33582 :             adjust_appendrel_attrs_mutator((Node *) oldinfo->clause, context);
     481                 :             : 
     482                 :             :         /* and the modified version, if an OR clause */
     483                 :       33582 :         newinfo->orclause = (Expr *)
     484                 :       33582 :             adjust_appendrel_attrs_mutator((Node *) oldinfo->orclause, context);
     485                 :             : 
     486                 :             :         /* adjust relid sets too */
     487                 :       33582 :         newinfo->clause_relids = adjust_child_relids(oldinfo->clause_relids,
     488                 :             :                                                      context->nappinfos,
     489                 :             :                                                      context->appinfos);
     490                 :       33582 :         newinfo->required_relids = adjust_child_relids(oldinfo->required_relids,
     491                 :             :                                                        context->nappinfos,
     492                 :             :                                                        context->appinfos);
     493                 :       33582 :         newinfo->outer_relids = adjust_child_relids(oldinfo->outer_relids,
     494                 :             :                                                     context->nappinfos,
     495                 :             :                                                     context->appinfos);
     496                 :       33582 :         newinfo->left_relids = adjust_child_relids(oldinfo->left_relids,
     497                 :             :                                                    context->nappinfos,
     498                 :             :                                                    context->appinfos);
     499                 :       33582 :         newinfo->right_relids = adjust_child_relids(oldinfo->right_relids,
     500                 :             :                                                     context->nappinfos,
     501                 :             :                                                     context->appinfos);
     502                 :             : 
     503                 :             :         /*
     504                 :             :          * Reset cached derivative fields, since these might need to have
     505                 :             :          * different values when considering the child relation.  Note we
     506                 :             :          * don't reset left_ec/right_ec: each child variable is implicitly
     507                 :             :          * equivalent to its parent, so still a member of the same EC if any.
     508                 :             :          */
     509                 :       33582 :         newinfo->eval_cost.startup = -1;
     510                 :       33582 :         newinfo->norm_selec = -1;
     511                 :       33582 :         newinfo->outer_selec = -1;
     512                 :       33582 :         newinfo->left_em = NULL;
     513                 :       33582 :         newinfo->right_em = NULL;
     514                 :       33582 :         newinfo->scansel_cache = NIL;
     515                 :       33582 :         newinfo->left_bucketsize = -1;
     516                 :       33582 :         newinfo->right_bucketsize = -1;
     517                 :       33582 :         newinfo->left_mcvfreq = -1;
     518                 :       33582 :         newinfo->right_mcvfreq = -1;
     519                 :             : 
     520                 :       33582 :         return (Node *) newinfo;
     521                 :             :     }
     522                 :             : 
     523                 :             :     /*
     524                 :             :      * We have to process RelAggInfo nodes specially.
     525                 :             :      */
     526         [ +  + ]:      533238 :     if (IsA(node, RelAggInfo))
     527                 :             :     {
     528                 :       15460 :         RelAggInfo *oldinfo = (RelAggInfo *) node;
     529                 :       15460 :         RelAggInfo *newinfo = makeNode(RelAggInfo);
     530                 :             : 
     531                 :       15460 :         newinfo->target = (PathTarget *)
     532                 :       15460 :             adjust_appendrel_attrs_mutator((Node *) oldinfo->target,
     533                 :             :                                            context);
     534                 :             : 
     535                 :       15460 :         newinfo->agg_input = (PathTarget *)
     536                 :       15460 :             adjust_appendrel_attrs_mutator((Node *) oldinfo->agg_input,
     537                 :             :                                            context);
     538                 :             : 
     539                 :       15460 :         newinfo->group_clauses = oldinfo->group_clauses;
     540                 :             : 
     541                 :       15460 :         newinfo->group_exprs = (List *)
     542                 :       15460 :             adjust_appendrel_attrs_mutator((Node *) oldinfo->group_exprs,
     543                 :             :                                            context);
     544                 :             : 
     545                 :       15460 :         return (Node *) newinfo;
     546                 :             :     }
     547                 :             : 
     548                 :             :     /*
     549                 :             :      * We have to process PathTarget nodes specially.
     550                 :             :      */
     551         [ +  + ]:      517778 :     if (IsA(node, PathTarget))
     552                 :             :     {
     553                 :       30920 :         PathTarget *oldtarget = (PathTarget *) node;
     554                 :       30920 :         PathTarget *newtarget = makeNode(PathTarget);
     555                 :             : 
     556                 :             :         /* Copy all flat-copiable fields */
     557                 :       30920 :         memcpy(newtarget, oldtarget, sizeof(PathTarget));
     558                 :             : 
     559                 :       30920 :         newtarget->exprs = (List *)
     560                 :       30920 :             adjust_appendrel_attrs_mutator((Node *) oldtarget->exprs,
     561                 :             :                                            context);
     562                 :             : 
     563         [ +  - ]:       30920 :         if (oldtarget->sortgrouprefs)
     564                 :             :         {
     565                 :       30920 :             Size        nbytes = list_length(oldtarget->exprs) * sizeof(Index);
     566                 :             : 
     567                 :       30920 :             newtarget->sortgrouprefs = (Index *) palloc(nbytes);
     568                 :       30920 :             memcpy(newtarget->sortgrouprefs, oldtarget->sortgrouprefs, nbytes);
     569                 :             :         }
     570                 :             : 
     571                 :       30920 :         return (Node *) newtarget;
     572                 :             :     }
     573                 :             : 
     574                 :             :     /*
     575                 :             :      * NOTE: we do not need to recurse into sublinks, because they should
     576                 :             :      * already have been converted to subplans before we see them.
     577                 :             :      */
     578                 :             :     Assert(!IsA(node, SubLink));
     579                 :             :     Assert(!IsA(node, Query));
     580                 :             :     /* We should never see these Query substructures, either. */
     581                 :             :     Assert(!IsA(node, RangeTblRef));
     582                 :             :     Assert(!IsA(node, JoinExpr));
     583                 :             : 
     584                 :      486858 :     return expression_tree_mutator(node, adjust_appendrel_attrs_mutator, context);
     585                 :             : }
     586                 :             : 
     587                 :             : /*
     588                 :             :  * adjust_appendrel_attrs_multilevel
     589                 :             :  *    Apply Var translations from an appendrel parent down to a child.
     590                 :             :  *
     591                 :             :  * Replace Vars in the "node" expression that reference "parentrel" with
     592                 :             :  * the appropriate Vars for "childrel".  childrel can be more than one
     593                 :             :  * inheritance level removed from parentrel.
     594                 :             :  */
     595                 :             : Node *
     596                 :       39554 : adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node,
     597                 :             :                                   RelOptInfo *childrel,
     598                 :             :                                   RelOptInfo *parentrel)
     599                 :             : {
     600                 :             :     AppendRelInfo **appinfos;
     601                 :             :     int         nappinfos;
     602                 :             : 
     603                 :             :     /* Recurse if immediate parent is not the top parent. */
     604         [ +  + ]:       39554 :     if (childrel->parent != parentrel)
     605                 :             :     {
     606         [ +  - ]:       13584 :         if (childrel->parent)
     607                 :       13584 :             node = adjust_appendrel_attrs_multilevel(root, node,
     608                 :       13584 :                                                      childrel->parent,
     609                 :             :                                                      parentrel);
     610                 :             :         else
     611         [ #  # ]:           0 :             elog(ERROR, "childrel is not a child of parentrel");
     612                 :             :     }
     613                 :             : 
     614                 :             :     /* Now translate for this child. */
     615                 :       39554 :     appinfos = find_appinfos_by_relids(root, childrel->relids, &nappinfos);
     616                 :             : 
     617                 :       39554 :     node = adjust_appendrel_attrs(root, node, nappinfos, appinfos);
     618                 :             : 
     619                 :       39554 :     pfree(appinfos);
     620                 :             : 
     621                 :       39554 :     return node;
     622                 :             : }
     623                 :             : 
     624                 :             : /*
     625                 :             :  * Substitute child relids for parent relids in a Relid set.  The array of
     626                 :             :  * appinfos specifies the substitutions to be performed.
     627                 :             :  */
     628                 :             : Relids
     629                 :      197528 : adjust_child_relids(Relids relids, int nappinfos, AppendRelInfo **appinfos)
     630                 :             : {
     631                 :      197528 :     Bitmapset  *result = NULL;
     632                 :             :     int         cnt;
     633                 :             : 
     634         [ +  + ]:      534596 :     for (cnt = 0; cnt < nappinfos; cnt++)
     635                 :             :     {
     636                 :      337068 :         AppendRelInfo *appinfo = appinfos[cnt];
     637                 :             : 
     638                 :             :         /* Remove parent, add child */
     639         [ +  + ]:      337068 :         if (bms_is_member(appinfo->parent_relid, relids))
     640                 :             :         {
     641                 :             :             /* Make a copy if we are changing the set. */
     642         [ +  + ]:      214844 :             if (!result)
     643                 :      154214 :                 result = bms_copy(relids);
     644                 :             : 
     645                 :      214844 :             result = bms_del_member(result, appinfo->parent_relid);
     646                 :      214844 :             result = bms_add_member(result, appinfo->child_relid);
     647                 :             :         }
     648                 :             :     }
     649                 :             : 
     650                 :             :     /* If we made any changes, return the modified copy. */
     651         [ +  + ]:      197528 :     if (result)
     652                 :      154214 :         return result;
     653                 :             : 
     654                 :             :     /* Otherwise, return the original set without modification. */
     655                 :       43314 :     return relids;
     656                 :             : }
     657                 :             : 
     658                 :             : /*
     659                 :             :  * Substitute child's relids for parent's relids in a Relid set.
     660                 :             :  * The childrel can be multiple inheritance levels below the parent.
     661                 :             :  */
     662                 :             : Relids
     663                 :         967 : adjust_child_relids_multilevel(PlannerInfo *root, Relids relids,
     664                 :             :                                RelOptInfo *childrel,
     665                 :             :                                RelOptInfo *parentrel)
     666                 :             : {
     667                 :             :     AppendRelInfo **appinfos;
     668                 :             :     int         nappinfos;
     669                 :             : 
     670                 :             :     /*
     671                 :             :      * If the given relids set doesn't contain any of the parent relids, it
     672                 :             :      * will remain unchanged.
     673                 :             :      */
     674         [ -  + ]:         967 :     if (!bms_overlap(relids, parentrel->relids))
     675                 :           0 :         return relids;
     676                 :             : 
     677                 :             :     /* Recurse if immediate parent is not the top parent. */
     678         [ +  + ]:         967 :     if (childrel->parent != parentrel)
     679                 :             :     {
     680         [ +  - ]:         120 :         if (childrel->parent)
     681                 :         120 :             relids = adjust_child_relids_multilevel(root, relids,
     682                 :         120 :                                                     childrel->parent,
     683                 :             :                                                     parentrel);
     684                 :             :         else
     685         [ #  # ]:           0 :             elog(ERROR, "childrel is not a child of parentrel");
     686                 :             :     }
     687                 :             : 
     688                 :             :     /* Now translate for this child. */
     689                 :         967 :     appinfos = find_appinfos_by_relids(root, childrel->relids, &nappinfos);
     690                 :             : 
     691                 :         967 :     relids = adjust_child_relids(relids, nappinfos, appinfos);
     692                 :             : 
     693                 :         967 :     pfree(appinfos);
     694                 :             : 
     695                 :         967 :     return relids;
     696                 :             : }
     697                 :             : 
     698                 :             : /*
     699                 :             :  * adjust_inherited_attnums
     700                 :             :  *    Translate an integer list of attribute numbers from parent to child.
     701                 :             :  */
     702                 :             : List *
     703                 :        4154 : adjust_inherited_attnums(List *attnums, AppendRelInfo *context)
     704                 :             : {
     705                 :        4154 :     List       *result = NIL;
     706                 :             :     ListCell   *lc;
     707                 :             : 
     708                 :             :     /* This should only happen for an inheritance case, not UNION ALL */
     709                 :             :     Assert(OidIsValid(context->parent_reloid));
     710                 :             : 
     711                 :             :     /* Look up each attribute in the AppendRelInfo's translated_vars list */
     712   [ +  -  +  +  :        9384 :     foreach(lc, attnums)
                   +  + ]
     713                 :             :     {
     714                 :        5230 :         AttrNumber  parentattno = lfirst_int(lc);
     715                 :             :         Var        *childvar;
     716                 :             : 
     717                 :             :         /* Look up the translation of this column: it must be a Var */
     718   [ +  -  -  + ]:       10460 :         if (parentattno <= 0 ||
     719                 :        5230 :             parentattno > list_length(context->translated_vars))
     720         [ #  # ]:           0 :             elog(ERROR, "attribute %d of relation \"%s\" does not exist",
     721                 :             :                  parentattno, get_rel_name(context->parent_reloid));
     722                 :        5230 :         childvar = (Var *) list_nth(context->translated_vars, parentattno - 1);
     723   [ +  -  -  + ]:        5230 :         if (childvar == NULL || !IsA(childvar, Var))
     724         [ #  # ]:           0 :             elog(ERROR, "attribute %d of relation \"%s\" does not exist",
     725                 :             :                  parentattno, get_rel_name(context->parent_reloid));
     726                 :             : 
     727                 :        5230 :         result = lappend_int(result, childvar->varattno);
     728                 :             :     }
     729                 :        4154 :     return result;
     730                 :             : }
     731                 :             : 
     732                 :             : /*
     733                 :             :  * adjust_inherited_attnums_multilevel
     734                 :             :  *    As above, but traverse multiple inheritance levels as needed.
     735                 :             :  */
     736                 :             : List *
     737                 :        4154 : adjust_inherited_attnums_multilevel(PlannerInfo *root, List *attnums,
     738                 :             :                                     Index child_relid, Index top_parent_relid)
     739                 :             : {
     740                 :        4154 :     AppendRelInfo *appinfo = root->append_rel_array[child_relid];
     741                 :             : 
     742         [ -  + ]:        4154 :     if (!appinfo)
     743         [ #  # ]:           0 :         elog(ERROR, "child rel %d not found in append_rel_array", child_relid);
     744                 :             : 
     745                 :             :     /* Recurse if immediate parent is not the top parent. */
     746         [ +  + ]:        4154 :     if (appinfo->parent_relid != top_parent_relid)
     747                 :         677 :         attnums = adjust_inherited_attnums_multilevel(root, attnums,
     748                 :             :                                                       appinfo->parent_relid,
     749                 :             :                                                       top_parent_relid);
     750                 :             : 
     751                 :             :     /* Now translate for this child */
     752                 :        4154 :     return adjust_inherited_attnums(attnums, appinfo);
     753                 :             : }
     754                 :             : 
     755                 :             : /*
     756                 :             :  * get_translated_update_targetlist
     757                 :             :  *    Get the processed_tlist of an UPDATE query, translated as needed to
     758                 :             :  *    match a child target relation.
     759                 :             :  *
     760                 :             :  * Optionally also return the list of target column numbers translated
     761                 :             :  * to this target relation.  (The resnos in processed_tlist MUST NOT be
     762                 :             :  * relied on for this purpose.)
     763                 :             :  */
     764                 :             : void
     765                 :          57 : get_translated_update_targetlist(PlannerInfo *root, Index relid,
     766                 :             :                                  List **processed_tlist, List **update_colnos)
     767                 :             : {
     768                 :             :     /* This is pretty meaningless for commands other than UPDATE. */
     769                 :             :     Assert(root->parse->commandType == CMD_UPDATE);
     770         [ +  + ]:          57 :     if (relid == root->parse->resultRelation)
     771                 :             :     {
     772                 :             :         /*
     773                 :             :          * Non-inheritance case, so it's easy.  The caller might be expecting
     774                 :             :          * a tree it can scribble on, though, so copy.
     775                 :             :          */
     776                 :          37 :         *processed_tlist = copyObject(root->processed_tlist);
     777         [ +  - ]:          37 :         if (update_colnos)
     778                 :          37 :             *update_colnos = copyObject(root->update_colnos);
     779                 :             :     }
     780                 :             :     else
     781                 :             :     {
     782                 :             :         Assert(bms_is_member(relid, root->all_result_relids));
     783                 :          20 :         *processed_tlist = (List *)
     784                 :          20 :             adjust_appendrel_attrs_multilevel(root,
     785                 :          20 :                                               (Node *) root->processed_tlist,
     786                 :             :                                               find_base_rel(root, relid),
     787                 :          20 :                                               find_base_rel(root, root->parse->resultRelation));
     788         [ +  - ]:          20 :         if (update_colnos)
     789                 :          20 :             *update_colnos =
     790                 :          20 :                 adjust_inherited_attnums_multilevel(root, root->update_colnos,
     791                 :             :                                                     relid,
     792                 :          20 :                                                     root->parse->resultRelation);
     793                 :             :     }
     794                 :          57 : }
     795                 :             : 
     796                 :             : /*
     797                 :             :  * find_appinfos_by_relids
     798                 :             :  *      Find AppendRelInfo structures for base relations listed in relids.
     799                 :             :  *
     800                 :             :  * The relids argument is typically a join relation's relids, which can
     801                 :             :  * include outer-join RT indexes in addition to baserels.  We silently
     802                 :             :  * ignore the outer joins.
     803                 :             :  *
     804                 :             :  * The AppendRelInfos are returned in an array, which can be pfree'd by the
     805                 :             :  * caller. *nappinfos is set to the number of entries in the array.
     806                 :             :  */
     807                 :             : AppendRelInfo **
     808                 :       83383 : find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
     809                 :             : {
     810                 :             :     AppendRelInfo **appinfos;
     811                 :       83383 :     int         cnt = 0;
     812                 :             :     int         i;
     813                 :             : 
     814                 :             :     /* Allocate an array that's certainly big enough */
     815                 :       83383 :     appinfos = palloc_array(AppendRelInfo *, bms_num_members(relids));
     816                 :             : 
     817                 :       83383 :     i = -1;
     818         [ +  + ]:      209951 :     while ((i = bms_next_member(relids, i)) >= 0)
     819                 :             :     {
     820                 :      126568 :         AppendRelInfo *appinfo = root->append_rel_array[i];
     821                 :             : 
     822         [ +  + ]:      126568 :         if (!appinfo)
     823                 :             :         {
     824                 :             :             /* Probably i is an OJ index, but let's check */
     825         [ +  - ]:        2976 :             if (find_base_rel_ignore_join(root, i) == NULL)
     826                 :        2976 :                 continue;
     827                 :             :             /* It's a base rel, but we lack an append_rel_array entry */
     828         [ #  # ]:           0 :             elog(ERROR, "child rel %d not found in append_rel_array", i);
     829                 :             :         }
     830                 :             : 
     831                 :      123592 :         appinfos[cnt++] = appinfo;
     832                 :             :     }
     833                 :       83383 :     *nappinfos = cnt;
     834                 :       83383 :     return appinfos;
     835                 :             : }
     836                 :             : 
     837                 :             : 
     838                 :             : /*****************************************************************************
     839                 :             :  *
     840                 :             :  *      ROW-IDENTITY VARIABLE MANAGEMENT
     841                 :             :  *
     842                 :             :  * This code lacks a good home, perhaps.  We choose to keep it here because
     843                 :             :  * adjust_appendrel_attrs_mutator() is its principal co-conspirator.  That
     844                 :             :  * function does most of what is needed to expand ROWID_VAR Vars into the
     845                 :             :  * right things.
     846                 :             :  *
     847                 :             :  *****************************************************************************/
     848                 :             : 
     849                 :             : /*
     850                 :             :  * add_row_identity_var
     851                 :             :  *    Register a row-identity column to be used in UPDATE/DELETE/MERGE.
     852                 :             :  *
     853                 :             :  * The Var must be equal(), aside from varno, to any other row-identity
     854                 :             :  * column with the same rowid_name.  Thus, for example, "wholerow"
     855                 :             :  * row identities had better use vartype == RECORDOID.
     856                 :             :  *
     857                 :             :  * rtindex is currently redundant with rowid_var->varno, but we specify
     858                 :             :  * it as a separate parameter in case this is ever generalized to support
     859                 :             :  * non-Var expressions.  (We could reasonably handle expressions over
     860                 :             :  * Vars of the specified rtindex, but for now that seems unnecessary.)
     861                 :             :  */
     862                 :             : void
     863                 :       22402 : add_row_identity_var(PlannerInfo *root, Var *orig_var,
     864                 :             :                      Index rtindex, const char *rowid_name)
     865                 :             : {
     866                 :             :     TargetEntry *tle;
     867                 :             :     Var        *rowid_var;
     868                 :             :     RowIdentityVarInfo *ridinfo;
     869                 :             :     ListCell   *lc;
     870                 :             : 
     871                 :             :     /* For now, the argument must be just a Var of the given rtindex */
     872                 :             :     Assert(IsA(orig_var, Var));
     873                 :             :     Assert(orig_var->varno == rtindex);
     874                 :             :     Assert(orig_var->varlevelsup == 0);
     875                 :             :     Assert(orig_var->varnullingrels == NULL);
     876                 :             : 
     877                 :             :     /*
     878                 :             :      * If we're doing non-inherited UPDATE/DELETE/MERGE, there's little need
     879                 :             :      * for ROWID_VAR shenanigans.  Just shove the presented Var into the
     880                 :             :      * processed_tlist, and we're done.
     881                 :             :      */
     882         [ +  + ]:       22402 :     if (rtindex == root->parse->resultRelation)
     883                 :             :     {
     884                 :       13318 :         tle = makeTargetEntry((Expr *) orig_var,
     885                 :       13318 :                               list_length(root->processed_tlist) + 1,
     886                 :             :                               pstrdup(rowid_name),
     887                 :             :                               true);
     888                 :       13318 :         root->processed_tlist = lappend(root->processed_tlist, tle);
     889                 :       13318 :         return;
     890                 :             :     }
     891                 :             : 
     892                 :             :     /*
     893                 :             :      * Otherwise, rtindex should reference a leaf target relation that's being
     894                 :             :      * added to the query during expand_inherited_rtentry().
     895                 :             :      */
     896                 :             :     Assert(bms_is_member(rtindex, root->leaf_result_relids));
     897                 :             :     Assert(root->append_rel_array[rtindex] != NULL);
     898                 :             : 
     899                 :             :     /*
     900                 :             :      * We have to find a matching RowIdentityVarInfo, or make one if there is
     901                 :             :      * none.  To allow using equal() to match the vars, change the varno to
     902                 :             :      * ROWID_VAR, leaving all else alone.
     903                 :             :      */
     904                 :        9084 :     rowid_var = copyObject(orig_var);
     905                 :             :     /* This could eventually become ChangeVarNodes() */
     906                 :        9084 :     rowid_var->varno = ROWID_VAR;
     907                 :             : 
     908                 :             :     /* Look for an existing row-id column of the same name */
     909   [ +  +  +  +  :       13693 :     foreach(lc, root->row_identity_vars)
                   +  + ]
     910                 :             :     {
     911                 :        8963 :         ridinfo = (RowIdentityVarInfo *) lfirst(lc);
     912         [ +  + ]:        8963 :         if (strcmp(rowid_name, ridinfo->rowidname) != 0)
     913                 :        4609 :             continue;
     914         [ +  - ]:        4354 :         if (equal(rowid_var, ridinfo->rowidvar))
     915                 :             :         {
     916                 :             :             /* Found a match; we need only record that rtindex needs it too */
     917                 :        4354 :             ridinfo->rowidrels = bms_add_member(ridinfo->rowidrels, rtindex);
     918                 :        4354 :             return;
     919                 :             :         }
     920                 :             :         else
     921                 :             :         {
     922                 :             :             /* Ooops, can't handle this */
     923         [ #  # ]:           0 :             elog(ERROR, "conflicting uses of row-identity name \"%s\"",
     924                 :             :                  rowid_name);
     925                 :             :         }
     926                 :             :     }
     927                 :             : 
     928                 :             :     /* No request yet, so add a new RowIdentityVarInfo */
     929                 :        4730 :     ridinfo = makeNode(RowIdentityVarInfo);
     930                 :        4730 :     ridinfo->rowidvar = copyObject(rowid_var);
     931                 :             :     /* for the moment, estimate width using just the datatype info */
     932                 :        4730 :     ridinfo->rowidwidth = get_typavgwidth(exprType((Node *) rowid_var),
     933                 :             :                                           exprTypmod((Node *) rowid_var));
     934                 :        4730 :     ridinfo->rowidname = pstrdup(rowid_name);
     935                 :        4730 :     ridinfo->rowidrels = bms_make_singleton(rtindex);
     936                 :             : 
     937                 :        4730 :     root->row_identity_vars = lappend(root->row_identity_vars, ridinfo);
     938                 :             : 
     939                 :             :     /* Change rowid_var into a reference to this row_identity_vars entry */
     940                 :        4730 :     rowid_var->varattno = list_length(root->row_identity_vars);
     941                 :             : 
     942                 :             :     /* Push the ROWID_VAR reference variable into processed_tlist */
     943                 :        4730 :     tle = makeTargetEntry((Expr *) rowid_var,
     944                 :        4730 :                           list_length(root->processed_tlist) + 1,
     945                 :             :                           pstrdup(rowid_name),
     946                 :             :                           true);
     947                 :        4730 :     root->processed_tlist = lappend(root->processed_tlist, tle);
     948                 :             : }
     949                 :             : 
     950                 :             : /*
     951                 :             :  * add_row_identity_columns
     952                 :             :  *
     953                 :             :  * This function adds the row identity columns needed by the core code.
     954                 :             :  * FDWs might call add_row_identity_var() for themselves to add nonstandard
     955                 :             :  * columns.  (Duplicate requests are fine.)
     956                 :             :  */
     957                 :             : void
     958                 :       18006 : add_row_identity_columns(PlannerInfo *root, Index rtindex,
     959                 :             :                          RangeTblEntry *target_rte,
     960                 :             :                          Relation target_relation)
     961                 :             : {
     962                 :       18006 :     CmdType     commandType = root->parse->commandType;
     963                 :       18006 :     char        relkind = target_relation->rd_rel->relkind;
     964                 :             :     Var        *var;
     965                 :             : 
     966                 :             :     Assert(commandType == CMD_UPDATE || commandType == CMD_DELETE || commandType == CMD_MERGE);
     967                 :             : 
     968   [ +  +  +  + ]:       18006 :     if (relkind == RELKIND_RELATION ||
     969         [ +  + ]:         479 :         relkind == RELKIND_MATVIEW ||
     970                 :             :         relkind == RELKIND_PARTITIONED_TABLE)
     971                 :             :     {
     972                 :             :         /*
     973                 :             :          * Emit CTID so that executor can find the row to merge, update or
     974                 :             :          * delete.
     975                 :             :          */
     976                 :       17560 :         var = makeVar(rtindex,
     977                 :             :                       SelfItemPointerAttributeNumber,
     978                 :             :                       TIDOID,
     979                 :             :                       -1,
     980                 :             :                       InvalidOid,
     981                 :             :                       0);
     982                 :       17560 :         add_row_identity_var(root, var, rtindex, "ctid");
     983                 :             :     }
     984         [ +  + ]:         446 :     else if (relkind == RELKIND_FOREIGN_TABLE)
     985                 :             :     {
     986                 :             :         /*
     987                 :             :          * Let the foreign table's FDW add whatever junk TLEs it wants.
     988                 :             :          */
     989                 :             :         FdwRoutine *fdwroutine;
     990                 :             : 
     991                 :         205 :         fdwroutine = GetFdwRoutineForRelation(target_relation, false);
     992                 :             : 
     993         [ +  + ]:         205 :         if (fdwroutine->AddForeignUpdateTargets != NULL)
     994                 :         198 :             fdwroutine->AddForeignUpdateTargets(root, rtindex,
     995                 :             :                                                 target_rte, target_relation);
     996                 :             : 
     997                 :             :         /*
     998                 :             :          * For UPDATE, we need to make the FDW fetch unchanged columns by
     999                 :             :          * asking it to fetch a whole-row Var.  That's because the top-level
    1000                 :             :          * targetlist only contains entries for changed columns, but
    1001                 :             :          * ExecUpdate will need to build the complete new tuple.  (Actually,
    1002                 :             :          * we only really need this in UPDATEs that are not pushed to the
    1003                 :             :          * remote side, but it's hard to tell if that will be the case at the
    1004                 :             :          * point when this function is called.)
    1005                 :             :          *
    1006                 :             :          * We will also need the whole row if there are any row triggers, so
    1007                 :             :          * that the executor will have the "old" row to pass to the trigger.
    1008                 :             :          * Alas, this misses system columns.
    1009                 :             :          */
    1010         [ +  + ]:         205 :         if (commandType == CMD_UPDATE ||
    1011         [ +  + ]:          90 :             (target_relation->trigdesc &&
    1012         [ +  + ]:          15 :              (target_relation->trigdesc->trig_delete_after_row ||
    1013         [ +  + ]:           9 :               target_relation->trigdesc->trig_delete_before_row)))
    1014                 :             :         {
    1015                 :         123 :             var = makeVar(rtindex,
    1016                 :             :                           InvalidAttrNumber,
    1017                 :             :                           RECORDOID,
    1018                 :             :                           -1,
    1019                 :             :                           InvalidOid,
    1020                 :             :                           0);
    1021                 :         123 :             add_row_identity_var(root, var, rtindex, "wholerow");
    1022                 :             :         }
    1023                 :             :     }
    1024                 :       18006 : }
    1025                 :             : 
    1026                 :             : /*
    1027                 :             :  * distribute_row_identity_vars
    1028                 :             :  *
    1029                 :             :  * After we have finished identifying all the row identity columns
    1030                 :             :  * needed by an inherited UPDATE/DELETE/MERGE query, make sure that
    1031                 :             :  * these columns will be generated by all the target relations.
    1032                 :             :  *
    1033                 :             :  * This is more or less like what build_base_rel_tlists() does,
    1034                 :             :  * except that it would not understand what to do with ROWID_VAR Vars.
    1035                 :             :  * Since that function runs before inheritance relations are expanded,
    1036                 :             :  * it will never see any such Vars anyway.
    1037                 :             :  */
    1038                 :             : void
    1039                 :      249129 : distribute_row_identity_vars(PlannerInfo *root)
    1040                 :             : {
    1041                 :      249129 :     Query      *parse = root->parse;
    1042                 :      249129 :     int         result_relation = parse->resultRelation;
    1043                 :             :     RangeTblEntry *target_rte;
    1044                 :             :     RelOptInfo *target_rel;
    1045                 :             :     ListCell   *lc;
    1046                 :             : 
    1047                 :             :     /*
    1048                 :             :      * There's nothing to do if this isn't an inherited UPDATE/DELETE/MERGE.
    1049                 :             :      */
    1050   [ +  +  +  + ]:      249129 :     if (parse->commandType != CMD_UPDATE && parse->commandType != CMD_DELETE &&
    1051         [ +  + ]:      234785 :         parse->commandType != CMD_MERGE)
    1052                 :             :     {
    1053                 :             :         Assert(root->row_identity_vars == NIL);
    1054                 :      233306 :         return;
    1055                 :             :     }
    1056                 :       15823 :     target_rte = rt_fetch(result_relation, parse->rtable);
    1057         [ +  + ]:       15823 :     if (!target_rte->inh)
    1058                 :             :     {
    1059                 :             :         Assert(root->row_identity_vars == NIL);
    1060                 :       13451 :         return;
    1061                 :             :     }
    1062                 :             : 
    1063                 :             :     /*
    1064                 :             :      * Ordinarily, we expect that leaf result relation(s) will have added some
    1065                 :             :      * ROWID_VAR Vars to the query.  However, it's possible that constraint
    1066                 :             :      * exclusion suppressed every leaf relation.  The executor will get upset
    1067                 :             :      * if the plan has no row identity columns at all, even though it will
    1068                 :             :      * certainly process no rows.  Handle this edge case by re-opening the top
    1069                 :             :      * result relation and adding the row identity columns it would have used,
    1070                 :             :      * as preprocess_targetlist() would have done if it weren't marked "inh".
    1071                 :             :      * Then re-run build_base_rel_tlists() to ensure that the added columns
    1072                 :             :      * get propagated to the relation's reltarget.  (This is a bit ugly, but
    1073                 :             :      * it seems better to confine the ugliness and extra cycles to this
    1074                 :             :      * unusual corner case.)
    1075                 :             :      */
    1076         [ +  + ]:        2372 :     if (root->row_identity_vars == NIL)
    1077                 :             :     {
    1078                 :             :         Relation    target_relation;
    1079                 :             : 
    1080                 :          28 :         target_relation = table_open(target_rte->relid, NoLock);
    1081                 :          28 :         add_row_identity_columns(root, result_relation,
    1082                 :             :                                  target_rte, target_relation);
    1083                 :          28 :         table_close(target_relation, NoLock);
    1084                 :          28 :         build_base_rel_tlists(root, root->processed_tlist);
    1085                 :             :         /* There are no ROWID_VAR Vars in this case, so we're done. */
    1086                 :          28 :         return;
    1087                 :             :     }
    1088                 :             : 
    1089                 :             :     /*
    1090                 :             :      * Dig through the processed_tlist to find the ROWID_VAR reference Vars,
    1091                 :             :      * and forcibly copy them into the reltarget list of the topmost target
    1092                 :             :      * relation.  That's sufficient because they'll be copied to the
    1093                 :             :      * individual leaf target rels (with appropriate translation) later,
    1094                 :             :      * during appendrel expansion --- see set_append_rel_size().
    1095                 :             :      */
    1096                 :        2344 :     target_rel = find_base_rel(root, result_relation);
    1097                 :             : 
    1098   [ +  -  +  +  :        9851 :     foreach(lc, root->processed_tlist)
                   +  + ]
    1099                 :             :     {
    1100                 :        7507 :         TargetEntry *tle = lfirst(lc);
    1101                 :        7507 :         Var        *var = (Var *) tle->expr;
    1102                 :             : 
    1103   [ +  -  +  +  :        7507 :         if (var && IsA(var, Var) && var->varno == ROWID_VAR)
                   +  + ]
    1104                 :             :         {
    1105                 :        4730 :             target_rel->reltarget->exprs =
    1106                 :        4730 :                 lappend(target_rel->reltarget->exprs, copyObject(var));
    1107                 :             :             /* reltarget cost and width will be computed later */
    1108                 :             :         }
    1109                 :             :     }
    1110                 :             : }
        

Generated by: LCOV version 2.0-1