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