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