1 /*-------------------------------------------------------------------------
2  *
3  * appendinfo.c
4  *	  Routines for mapping between append parent(s) and children
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/optimizer/path/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 {
32 	PlannerInfo *root;
33 	int			nappinfos;
34 	AppendRelInfo **appinfos;
35 } adjust_appendrel_attrs_context;
36 
37 static void make_inh_translation_list(Relation oldrelation,
38 									  Relation newrelation,
39 									  Index newvarno,
40 									  AppendRelInfo *appinfo);
41 static Node *adjust_appendrel_attrs_mutator(Node *node,
42 											adjust_appendrel_attrs_context *context);
43 
44 
45 /*
46  * make_append_rel_info
47  *	  Build an AppendRelInfo for the parent-child pair
48  */
49 AppendRelInfo *
make_append_rel_info(Relation parentrel,Relation childrel,Index parentRTindex,Index childRTindex)50 make_append_rel_info(Relation parentrel, Relation childrel,
51 					 Index parentRTindex, Index childRTindex)
52 {
53 	AppendRelInfo *appinfo = makeNode(AppendRelInfo);
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
make_inh_translation_list(Relation oldrelation,Relation newrelation,Index newvarno,AppendRelInfo * appinfo)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 *
adjust_appendrel_attrs(PlannerInfo * root,Node * node,int nappinfos,AppendRelInfo ** appinfos)195 adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos,
196 					   AppendRelInfo **appinfos)
197 {
198 	adjust_appendrel_attrs_context context;
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 *
adjust_appendrel_attrs_mutator(Node * node,adjust_appendrel_attrs_context * context)214 adjust_appendrel_attrs_mutator(Node *node,
215 							   adjust_appendrel_attrs_context *context)
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 					{
273 						ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
274 
275 						r->arg = (Expr *) var;
276 						r->resulttype = appinfo->parent_reltype;
277 						r->convertformat = COERCE_IMPLICIT_CAST;
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 			{
342 				RowIdentityVarInfo *ridinfo = (RowIdentityVarInfo *)
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 
390 		phv = (PlaceHolderVar *) expression_tree_mutator(node,
391 														 adjust_appendrel_attrs_mutator,
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);
430 		newinfo->required_relids = adjust_child_relids(oldinfo->required_relids,
431 													   context->nappinfos,
432 													   context->appinfos);
433 		newinfo->outer_relids = adjust_child_relids(oldinfo->outer_relids,
434 													context->nappinfos,
435 													context->appinfos);
436 		newinfo->nullable_relids = adjust_child_relids(oldinfo->nullable_relids,
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 
476 	return expression_tree_mutator(node, adjust_appendrel_attrs_mutator,
477 								   (void *) context);
478 }
479 
480 /*
481  * adjust_appendrel_attrs_multilevel
482  *	  Apply Var translations from a toplevel appendrel parent down to a child.
483  *
484  * In some cases we need to translate expressions referencing a parent relation
485  * to reference an appendrel child that's multiple levels removed from it.
486  */
487 Node *
adjust_appendrel_attrs_multilevel(PlannerInfo * root,Node * node,Relids child_relids,Relids top_parent_relids)488 adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node,
489 								  Relids child_relids,
490 								  Relids top_parent_relids)
491 {
492 	AppendRelInfo **appinfos;
493 	Bitmapset  *parent_relids = NULL;
494 	int			nappinfos;
495 	int			cnt;
496 
497 	Assert(bms_num_members(child_relids) == bms_num_members(top_parent_relids));
498 
499 	appinfos = find_appinfos_by_relids(root, child_relids, &nappinfos);
500 
501 	/* Construct relids set for the immediate parent of given child. */
502 	for (cnt = 0; cnt < nappinfos; cnt++)
503 	{
504 		AppendRelInfo *appinfo = appinfos[cnt];
505 
506 		parent_relids = bms_add_member(parent_relids, appinfo->parent_relid);
507 	}
508 
509 	/* Recurse if immediate parent is not the top parent. */
510 	if (!bms_equal(parent_relids, top_parent_relids))
511 		node = adjust_appendrel_attrs_multilevel(root, node, parent_relids,
512 												 top_parent_relids);
513 
514 	/* Now translate for this child */
515 	node = adjust_appendrel_attrs(root, node, nappinfos, appinfos);
516 
517 	pfree(appinfos);
518 
519 	return node;
520 }
521 
522 /*
523  * Substitute child relids for parent relids in a Relid set.  The array of
524  * appinfos specifies the substitutions to be performed.
525  */
526 Relids
adjust_child_relids(Relids relids,int nappinfos,AppendRelInfo ** appinfos)527 adjust_child_relids(Relids relids, int nappinfos, AppendRelInfo **appinfos)
528 {
529 	Bitmapset  *result = NULL;
530 	int			cnt;
531 
532 	for (cnt = 0; cnt < nappinfos; cnt++)
533 	{
534 		AppendRelInfo *appinfo = appinfos[cnt];
535 
536 		/* Remove parent, add child */
537 		if (bms_is_member(appinfo->parent_relid, relids))
538 		{
539 			/* Make a copy if we are changing the set. */
540 			if (!result)
541 				result = bms_copy(relids);
542 
543 			result = bms_del_member(result, appinfo->parent_relid);
544 			result = bms_add_member(result, appinfo->child_relid);
545 		}
546 	}
547 
548 	/* If we made any changes, return the modified copy. */
549 	if (result)
550 		return result;
551 
552 	/* Otherwise, return the original set without modification. */
553 	return relids;
554 }
555 
556 /*
557  * Replace any relid present in top_parent_relids with its child in
558  * child_relids. Members of child_relids can be multiple levels below top
559  * parent in the partition hierarchy.
560  */
561 Relids
adjust_child_relids_multilevel(PlannerInfo * root,Relids relids,Relids child_relids,Relids top_parent_relids)562 adjust_child_relids_multilevel(PlannerInfo *root, Relids relids,
563 							   Relids child_relids, Relids top_parent_relids)
564 {
565 	AppendRelInfo **appinfos;
566 	int			nappinfos;
567 	Relids		parent_relids = NULL;
568 	Relids		result;
569 	Relids		tmp_result = NULL;
570 	int			cnt;
571 
572 	/*
573 	 * If the given relids set doesn't contain any of the top parent relids,
574 	 * it will remain unchanged.
575 	 */
576 	if (!bms_overlap(relids, top_parent_relids))
577 		return relids;
578 
579 	appinfos = find_appinfos_by_relids(root, child_relids, &nappinfos);
580 
581 	/* Construct relids set for the immediate parent of the given child. */
582 	for (cnt = 0; cnt < nappinfos; cnt++)
583 	{
584 		AppendRelInfo *appinfo = appinfos[cnt];
585 
586 		parent_relids = bms_add_member(parent_relids, appinfo->parent_relid);
587 	}
588 
589 	/* Recurse if immediate parent is not the top parent. */
590 	if (!bms_equal(parent_relids, top_parent_relids))
591 	{
592 		tmp_result = adjust_child_relids_multilevel(root, relids,
593 													parent_relids,
594 													top_parent_relids);
595 		relids = tmp_result;
596 	}
597 
598 	result = adjust_child_relids(relids, nappinfos, appinfos);
599 
600 	/* Free memory consumed by any intermediate result. */
601 	if (tmp_result)
602 		bms_free(tmp_result);
603 	bms_free(parent_relids);
604 	pfree(appinfos);
605 
606 	return result;
607 }
608 
609 /*
610  * adjust_inherited_attnums
611  *	  Translate an integer list of attribute numbers from parent to child.
612  */
613 List *
adjust_inherited_attnums(List * attnums,AppendRelInfo * context)614 adjust_inherited_attnums(List *attnums, AppendRelInfo *context)
615 {
616 	List	   *result = NIL;
617 	ListCell   *lc;
618 
619 	/* This should only happen for an inheritance case, not UNION ALL */
620 	Assert(OidIsValid(context->parent_reloid));
621 
622 	/* Look up each attribute in the AppendRelInfo's translated_vars list */
623 	foreach(lc, attnums)
624 	{
625 		AttrNumber	parentattno = lfirst_int(lc);
626 		Var		   *childvar;
627 
628 		/* Look up the translation of this column: it must be a Var */
629 		if (parentattno <= 0 ||
630 			parentattno > list_length(context->translated_vars))
631 			elog(ERROR, "attribute %d of relation \"%s\" does not exist",
632 				 parentattno, get_rel_name(context->parent_reloid));
633 		childvar = (Var *) list_nth(context->translated_vars, parentattno - 1);
634 		if (childvar == NULL || !IsA(childvar, Var))
635 			elog(ERROR, "attribute %d of relation \"%s\" does not exist",
636 				 parentattno, get_rel_name(context->parent_reloid));
637 
638 		result = lappend_int(result, childvar->varattno);
639 	}
640 	return result;
641 }
642 
643 /*
644  * adjust_inherited_attnums_multilevel
645  *	  As above, but traverse multiple inheritance levels as needed.
646  */
647 List *
adjust_inherited_attnums_multilevel(PlannerInfo * root,List * attnums,Index child_relid,Index top_parent_relid)648 adjust_inherited_attnums_multilevel(PlannerInfo *root, List *attnums,
649 									Index child_relid, Index top_parent_relid)
650 {
651 	AppendRelInfo *appinfo = root->append_rel_array[child_relid];
652 
653 	if (!appinfo)
654 		elog(ERROR, "child rel %d not found in append_rel_array", child_relid);
655 
656 	/* Recurse if immediate parent is not the top parent. */
657 	if (appinfo->parent_relid != top_parent_relid)
658 		attnums = adjust_inherited_attnums_multilevel(root, attnums,
659 													  appinfo->parent_relid,
660 													  top_parent_relid);
661 
662 	/* Now translate for this child */
663 	return adjust_inherited_attnums(attnums, appinfo);
664 }
665 
666 /*
667  * get_translated_update_targetlist
668  *	  Get the processed_tlist of an UPDATE query, translated as needed to
669  *	  match a child target relation.
670  *
671  * Optionally also return the list of target column numbers translated
672  * to this target relation.  (The resnos in processed_tlist MUST NOT be
673  * relied on for this purpose.)
674  */
675 void
get_translated_update_targetlist(PlannerInfo * root,Index relid,List ** processed_tlist,List ** update_colnos)676 get_translated_update_targetlist(PlannerInfo *root, Index relid,
677 								 List **processed_tlist, List **update_colnos)
678 {
679 	/* This is pretty meaningless for commands other than UPDATE. */
680 	Assert(root->parse->commandType == CMD_UPDATE);
681 	if (relid == root->parse->resultRelation)
682 	{
683 		/*
684 		 * Non-inheritance case, so it's easy.  The caller might be expecting
685 		 * a tree it can scribble on, though, so copy.
686 		 */
687 		*processed_tlist = copyObject(root->processed_tlist);
688 		if (update_colnos)
689 			*update_colnos = copyObject(root->update_colnos);
690 	}
691 	else
692 	{
693 		Assert(bms_is_member(relid, root->all_result_relids));
694 		*processed_tlist = (List *)
695 			adjust_appendrel_attrs_multilevel(root,
696 											  (Node *) root->processed_tlist,
697 											  bms_make_singleton(relid),
698 											  bms_make_singleton(root->parse->resultRelation));
699 		if (update_colnos)
700 			*update_colnos =
701 				adjust_inherited_attnums_multilevel(root, root->update_colnos,
702 													relid,
703 													root->parse->resultRelation);
704 	}
705 }
706 
707 /*
708  * find_appinfos_by_relids
709  * 		Find AppendRelInfo structures for all relations specified by relids.
710  *
711  * The AppendRelInfos are returned in an array, which can be pfree'd by the
712  * caller. *nappinfos is set to the number of entries in the array.
713  */
714 AppendRelInfo **
find_appinfos_by_relids(PlannerInfo * root,Relids relids,int * nappinfos)715 find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
716 {
717 	AppendRelInfo **appinfos;
718 	int			cnt = 0;
719 	int			i;
720 
721 	*nappinfos = bms_num_members(relids);
722 	appinfos = (AppendRelInfo **) palloc(sizeof(AppendRelInfo *) * *nappinfos);
723 
724 	i = -1;
725 	while ((i = bms_next_member(relids, i)) >= 0)
726 	{
727 		AppendRelInfo *appinfo = root->append_rel_array[i];
728 
729 		if (!appinfo)
730 			elog(ERROR, "child rel %d not found in append_rel_array", i);
731 
732 		appinfos[cnt++] = appinfo;
733 	}
734 	return appinfos;
735 }
736 
737 
738 /*****************************************************************************
739  *
740  *		ROW-IDENTITY VARIABLE MANAGEMENT
741  *
742  * This code lacks a good home, perhaps.  We choose to keep it here because
743  * adjust_appendrel_attrs_mutator() is its principal co-conspirator.  That
744  * function does most of what is needed to expand ROWID_VAR Vars into the
745  * right things.
746  *
747  *****************************************************************************/
748 
749 /*
750  * add_row_identity_var
751  *	  Register a row-identity column to be used in UPDATE/DELETE.
752  *
753  * The Var must be equal(), aside from varno, to any other row-identity
754  * column with the same rowid_name.  Thus, for example, "wholerow"
755  * row identities had better use vartype == RECORDOID.
756  *
757  * rtindex is currently redundant with rowid_var->varno, but we specify
758  * it as a separate parameter in case this is ever generalized to support
759  * non-Var expressions.  (We could reasonably handle expressions over
760  * Vars of the specified rtindex, but for now that seems unnecessary.)
761  */
762 void
add_row_identity_var(PlannerInfo * root,Var * orig_var,Index rtindex,const char * rowid_name)763 add_row_identity_var(PlannerInfo *root, Var *orig_var,
764 					 Index rtindex, const char *rowid_name)
765 {
766 	TargetEntry *tle;
767 	Var		   *rowid_var;
768 	RowIdentityVarInfo *ridinfo;
769 	ListCell   *lc;
770 
771 	/* For now, the argument must be just a Var of the given rtindex */
772 	Assert(IsA(orig_var, Var));
773 	Assert(orig_var->varno == rtindex);
774 	Assert(orig_var->varlevelsup == 0);
775 
776 	/*
777 	 * If we're doing non-inherited UPDATE/DELETE, there's little need for
778 	 * ROWID_VAR shenanigans.  Just shove the presented Var into the
779 	 * processed_tlist, and we're done.
780 	 */
781 	if (rtindex == root->parse->resultRelation)
782 	{
783 		tle = makeTargetEntry((Expr *) orig_var,
784 							  list_length(root->processed_tlist) + 1,
785 							  pstrdup(rowid_name),
786 							  true);
787 		root->processed_tlist = lappend(root->processed_tlist, tle);
788 		return;
789 	}
790 
791 	/*
792 	 * Otherwise, rtindex should reference a leaf target relation that's being
793 	 * added to the query during expand_inherited_rtentry().
794 	 */
795 	Assert(bms_is_member(rtindex, root->leaf_result_relids));
796 	Assert(root->append_rel_array[rtindex] != NULL);
797 
798 	/*
799 	 * We have to find a matching RowIdentityVarInfo, or make one if there is
800 	 * none.  To allow using equal() to match the vars, change the varno to
801 	 * ROWID_VAR, leaving all else alone.
802 	 */
803 	rowid_var = copyObject(orig_var);
804 	/* This could eventually become ChangeVarNodes() */
805 	rowid_var->varno = ROWID_VAR;
806 
807 	/* Look for an existing row-id column of the same name */
808 	foreach(lc, root->row_identity_vars)
809 	{
810 		ridinfo = (RowIdentityVarInfo *) lfirst(lc);
811 		if (strcmp(rowid_name, ridinfo->rowidname) != 0)
812 			continue;
813 		if (equal(rowid_var, ridinfo->rowidvar))
814 		{
815 			/* Found a match; we need only record that rtindex needs it too */
816 			ridinfo->rowidrels = bms_add_member(ridinfo->rowidrels, rtindex);
817 			return;
818 		}
819 		else
820 		{
821 			/* Ooops, can't handle this */
822 			elog(ERROR, "conflicting uses of row-identity name \"%s\"",
823 				 rowid_name);
824 		}
825 	}
826 
827 	/* No request yet, so add a new RowIdentityVarInfo */
828 	ridinfo = makeNode(RowIdentityVarInfo);
829 	ridinfo->rowidvar = copyObject(rowid_var);
830 	/* for the moment, estimate width using just the datatype info */
831 	ridinfo->rowidwidth = get_typavgwidth(exprType((Node *) rowid_var),
832 										  exprTypmod((Node *) rowid_var));
833 	ridinfo->rowidname = pstrdup(rowid_name);
834 	ridinfo->rowidrels = bms_make_singleton(rtindex);
835 
836 	root->row_identity_vars = lappend(root->row_identity_vars, ridinfo);
837 
838 	/* Change rowid_var into a reference to this row_identity_vars entry */
839 	rowid_var->varattno = list_length(root->row_identity_vars);
840 
841 	/* Push the ROWID_VAR reference variable into processed_tlist */
842 	tle = makeTargetEntry((Expr *) rowid_var,
843 						  list_length(root->processed_tlist) + 1,
844 						  pstrdup(rowid_name),
845 						  true);
846 	root->processed_tlist = lappend(root->processed_tlist, tle);
847 }
848 
849 /*
850  * add_row_identity_columns
851  *
852  * This function adds the row identity columns needed by the core code.
853  * FDWs might call add_row_identity_var() for themselves to add nonstandard
854  * columns.  (Duplicate requests are fine.)
855  */
856 void
add_row_identity_columns(PlannerInfo * root,Index rtindex,RangeTblEntry * target_rte,Relation target_relation)857 add_row_identity_columns(PlannerInfo *root, Index rtindex,
858 						 RangeTblEntry *target_rte,
859 						 Relation target_relation)
860 {
861 	CmdType		commandType = root->parse->commandType;
862 	char		relkind = target_relation->rd_rel->relkind;
863 	Var		   *var;
864 
865 	Assert(commandType == CMD_UPDATE || commandType == CMD_DELETE);
866 
867 	if (relkind == RELKIND_RELATION ||
868 		relkind == RELKIND_MATVIEW ||
869 		relkind == RELKIND_PARTITIONED_TABLE)
870 	{
871 		/*
872 		 * Emit CTID so that executor can find the row to update or delete.
873 		 */
874 		var = makeVar(rtindex,
875 					  SelfItemPointerAttributeNumber,
876 					  TIDOID,
877 					  -1,
878 					  InvalidOid,
879 					  0);
880 		add_row_identity_var(root, var, rtindex, "ctid");
881 	}
882 	else if (relkind == RELKIND_FOREIGN_TABLE)
883 	{
884 		/*
885 		 * Let the foreign table's FDW add whatever junk TLEs it wants.
886 		 */
887 		FdwRoutine *fdwroutine;
888 
889 		fdwroutine = GetFdwRoutineForRelation(target_relation, false);
890 
891 		if (fdwroutine->AddForeignUpdateTargets != NULL)
892 			fdwroutine->AddForeignUpdateTargets(root, rtindex,
893 												target_rte, target_relation);
894 
895 		/*
896 		 * For UPDATE, we need to make the FDW fetch unchanged columns by
897 		 * asking it to fetch a whole-row Var.  That's because the top-level
898 		 * targetlist only contains entries for changed columns, but
899 		 * ExecUpdate will need to build the complete new tuple.  (Actually,
900 		 * we only really need this in UPDATEs that are not pushed to the
901 		 * remote side, but it's hard to tell if that will be the case at the
902 		 * point when this function is called.)
903 		 *
904 		 * We will also need the whole row if there are any row triggers, so
905 		 * that the executor will have the "old" row to pass to the trigger.
906 		 * Alas, this misses system columns.
907 		 */
908 		if (commandType == CMD_UPDATE ||
909 			(target_relation->trigdesc &&
910 			 (target_relation->trigdesc->trig_delete_after_row ||
911 			  target_relation->trigdesc->trig_delete_before_row)))
912 		{
913 			var = makeVar(rtindex,
914 						  InvalidAttrNumber,
915 						  RECORDOID,
916 						  -1,
917 						  InvalidOid,
918 						  0);
919 			add_row_identity_var(root, var, rtindex, "wholerow");
920 		}
921 	}
922 }
923 
924 /*
925  * distribute_row_identity_vars
926  *
927  * After we have finished identifying all the row identity columns
928  * needed by an inherited UPDATE/DELETE query, make sure that these
929  * columns will be generated by all the target relations.
930  *
931  * This is more or less like what build_base_rel_tlists() does,
932  * except that it would not understand what to do with ROWID_VAR Vars.
933  * Since that function runs before inheritance relations are expanded,
934  * it will never see any such Vars anyway.
935  */
936 void
distribute_row_identity_vars(PlannerInfo * root)937 distribute_row_identity_vars(PlannerInfo *root)
938 {
939 	Query	   *parse = root->parse;
940 	int			result_relation = parse->resultRelation;
941 	RangeTblEntry *target_rte;
942 	RelOptInfo *target_rel;
943 	ListCell   *lc;
944 
945 	/* There's nothing to do if this isn't an inherited UPDATE/DELETE. */
946 	if (parse->commandType != CMD_UPDATE && parse->commandType != CMD_DELETE)
947 	{
948 		Assert(root->row_identity_vars == NIL);
949 		return;
950 	}
951 	target_rte = rt_fetch(result_relation, parse->rtable);
952 	if (!target_rte->inh)
953 	{
954 		Assert(root->row_identity_vars == NIL);
955 		return;
956 	}
957 
958 	/*
959 	 * Ordinarily, we expect that leaf result relation(s) will have added some
960 	 * ROWID_VAR Vars to the query.  However, it's possible that constraint
961 	 * exclusion suppressed every leaf relation.  The executor will get upset
962 	 * if the plan has no row identity columns at all, even though it will
963 	 * certainly process no rows.  Handle this edge case by re-opening the top
964 	 * result relation and adding the row identity columns it would have used,
965 	 * as preprocess_targetlist() would have done if it weren't marked "inh".
966 	 * (This is a bit ugly, but it seems better to confine the ugliness and
967 	 * extra cycles to this unusual corner case.)  We needn't worry about
968 	 * fixing the rel's reltarget, as that won't affect the finished plan.
969 	 */
970 	if (root->row_identity_vars == NIL)
971 	{
972 		Relation	target_relation;
973 
974 		target_relation = table_open(target_rte->relid, NoLock);
975 		add_row_identity_columns(root, result_relation,
976 								 target_rte, target_relation);
977 		table_close(target_relation, NoLock);
978 		return;
979 	}
980 
981 	/*
982 	 * Dig through the processed_tlist to find the ROWID_VAR reference Vars,
983 	 * and forcibly copy them into the reltarget list of the topmost target
984 	 * relation.  That's sufficient because they'll be copied to the
985 	 * individual leaf target rels (with appropriate translation) later,
986 	 * during appendrel expansion --- see set_append_rel_size().
987 	 */
988 	target_rel = find_base_rel(root, result_relation);
989 
990 	foreach(lc, root->processed_tlist)
991 	{
992 		TargetEntry *tle = lfirst(lc);
993 		Var		   *var = (Var *) tle->expr;
994 
995 		if (var && IsA(var, Var) && var->varno == ROWID_VAR)
996 		{
997 			target_rel->reltarget->exprs =
998 				lappend(target_rel->reltarget->exprs, copyObject(var));
999 			/* reltarget cost and width will be computed later */
1000 		}
1001 	}
1002 }
1003