1/*-------------------------------------------------------------------------
4 * Routines for mapping between append parent(s) and children
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/optimizer/util/appendinfo.c
13 *-------------------------------------------------------------------------
47 * make_append_rel_info
48 * Build an AppendRelInfo for the parent-child pair
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.
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).
77 * For paranoia's sake, we match type/collation as well as attribute name.
89 int oldnatts = old_tupdesc->
natts;
90 int newnatts = new_tupdesc->
natts;
94 /* Initialize reverse-translation array with all entries zero */
96 appinfo->parent_colnos = pcolnos =
99 for (old_attno = 0; old_attno < oldnatts; old_attno++)
108 if (att->attisdropped)
110 /* Just put NULL into this list entry */
115 atttypid = att->atttypid;
116 atttypmod = att->atttypmod;
117 attcollation = att->attcollation;
120 * When we are generating the "translation list" for the parent table
121 * of an inheritance set, no need to search for matches.
123 if (oldrelation == newrelation)
131 pcolnos[old_attno] = old_attno + 1;
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.
144 if (new_attno >= newnatts ||
145 (att =
TupleDescAttr(new_tupdesc, new_attno))->attisdropped ||
152 elog(
ERROR,
"could not find inherited attribute \"%s\" of relation \"%s\"",
155 Assert(new_attno >= 0 && new_attno < newnatts);
161 /* Found it, check type and collation match */
162 if (atttypid != att->atttypid || atttypmod != att->atttypmod)
164 (
errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
165 errmsg(
"attribute \"%s\" of relation \"%s\" does not match parent's type",
167 if (attcollation != att->attcollation)
169 (
errcode(ERRCODE_INVALID_COLUMN_DEFINITION),
170 errmsg(
"attribute \"%s\" of relation \"%s\" does not match parent's collation",
179 pcolnos[new_attno] = old_attno + 1;
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
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.
196 * Note: this is not hugely different from what pullup_replace_vars() does;
197 * maybe we should try to fold the two routines together.
209 /* If there's nothing to adjust, don't call this function. */
210 Assert(nappinfos >= 1 && appinfos != NULL);
212 /* Should never be translating a Query tree. */
234 return (
Node *) var;
/* no changes needed */
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
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?
257 * If var->varreturningtype is not VAR_RETURNING_DEFAULT, then that
258 * also needs to be copied to the translated Var. That too would fail
259 * if the translation wasn't a Var, but that should never happen since
260 * a non-default var->varreturningtype is only used for Vars referring
261 * to the result relation, which should never be a flattened UNION ALL
265 for (cnt = 0; cnt < nappinfos; cnt++)
269 appinfo = appinfos[cnt];
277 /* it's now a generated Var, so drop any syntactic labeling */
279 var->varattnosyn = 0;
285 elog(
ERROR,
"attribute %d of relation \"%s\" does not exist",
290 elog(
ERROR,
"attribute %d of relation \"%s\" does not exist",
295 ((
Var *) newnode)->varnullingrels = var->varnullingrels;
300 elog(
ERROR,
"failed to apply returningtype to a non-Var");
301 if (var->varnullingrels != NULL)
302 elog(
ERROR,
"failed to apply nullingrels to a non-Var");
309 * Whole-row Var: if we are dealing with named rowtypes, we
310 * can use a whole-row Var for the child table plus a coercion
311 * step to convert the tuple layout to the parent's rowtype.
312 * Otherwise we have to generate a RowExpr.
325 /* Make sure the Var node has the right type ID, too */
333 * Build a RowExpr containing the translated variables.
335 * In practice var->vartype will always be RECORDOID here,
336 * so we need to come up with some suitable column names.
337 * We use the parent RTE's column names.
339 * Note: we can't get here for inheritance cases, so there
340 * is no need to worry that translated_vars might contain
351 rowexpr->
args = fields;
352 rowexpr->row_typeid = var->vartype;
354 rowexpr->colnames =
copyObject(rte->eref->colnames);
358 elog(
ERROR,
"failed to apply returningtype to a non-Var");
359 if (var->varnullingrels != NULL)
360 elog(
ERROR,
"failed to apply nullingrels to a non-Var");
362 return (
Node *) rowexpr;
365 /* system attributes don't need any other translation */
370 * If it's a ROWID_VAR placeholder, see if we've reached a leaf
371 * target rel, for which we can translate the Var to a specific
372 * instantiation. We should never be asked to translate to a set
373 * of relids containing more than one leaf target rel, so the
374 * answer will be unique. If we're still considering non-leaf
375 * inheritance levels, return the ROWID_VAR Var as-is.
378 Index leaf_relid = 0;
380 for (cnt = 0; cnt < nappinfos; cnt++)
386 elog(
ERROR,
"cannot translate to multiple leaf relids");
398 /* Substitute the Var given in the RowIdentityVarInfo */
400 /* ... but use the correct relid */
401 var->
varno = leaf_relid;
402 /* identity vars shouldn't have nulling rels */
403 Assert(var->varnullingrels == NULL);
404 /* varnosyn in the RowIdentityVarInfo is probably wrong */
406 var->varattnosyn = 0;
411 * This leaf rel can't return the desired value, so
412 * substitute a NULL of the correct type.
426 for (cnt = 0; cnt < nappinfos; cnt++)
436 return (
Node *) cexpr;
440 /* Copy the PlaceHolderVar node with correct mutation of subnodes */
446 /* now fix PlaceHolderVar's relid sets */
450 nappinfos, appinfos);
451 /* as above, we needn't touch phnullingrels */
455 /* Shouldn't need to handle planner auxiliary nodes here */
462 * We have to process RestrictInfo nodes specially. (Note: although
463 * set_append_rel_pathlist will hide RestrictInfos in the parent's
464 * baserestrictinfo list from us, it doesn't hide those in joininfo.)
471 /* Copy all flat-copiable fields, notably including rinfo_serial */
474 /* Recursively fix the clause itself */
478 /* and the modified version, if an OR clause */
479 newinfo->orclause = (
Expr *)
482 /* adjust relid sets too */
500 * Reset cached derivative fields, since these might need to have
501 * different values when considering the child relation. Note we
502 * don't reset left_ec/right_ec: each child variable is implicitly
503 * equivalent to its parent, so still a member of the same EC if any.
505 newinfo->eval_cost.startup = -1;
506 newinfo->norm_selec = -1;
507 newinfo->outer_selec = -1;
508 newinfo->left_em = NULL;
509 newinfo->right_em = NULL;
510 newinfo->scansel_cache =
NIL;
511 newinfo->left_bucketsize = -1;
512 newinfo->right_bucketsize = -1;
513 newinfo->left_mcvfreq = -1;
514 newinfo->right_mcvfreq = -1;
516 return (
Node *) newinfo;
520 * NOTE: we do not need to recurse into sublinks, because they should
521 * already have been converted to subplans before we see them.
525 /* We should never see these Query substructures, either. */
533 * adjust_appendrel_attrs_multilevel
534 * Apply Var translations from an appendrel parent down to a child.
536 * Replace Vars in the "node" expression that reference "parentrel" with
537 * the appropriate Vars for "childrel". childrel can be more than one
538 * inheritance level removed from parentrel.
548 /* Recurse if immediate parent is not the top parent. */
549 if (childrel->parent != parentrel)
551 if (childrel->parent)
556 elog(
ERROR,
"childrel is not a child of parentrel");
559 /* Now translate for this child. */
570 * Substitute child relids for parent relids in a Relid set. The array of
571 * appinfos specifies the substitutions to be performed.
579 for (cnt = 0; cnt < nappinfos; cnt++)
583 /* Remove parent, add child */
586 /* Make a copy if we are changing the set. */
595 /* If we made any changes, return the modified copy. */
599 /* Otherwise, return the original set without modification. */
604 * Substitute child's relids for parent's relids in a Relid set.
605 * The childrel can be multiple inheritance levels below the parent.
616 * If the given relids set doesn't contain any of the parent relids, it
617 * will remain unchanged.
622 /* Recurse if immediate parent is not the top parent. */
623 if (childrel->parent != parentrel)
625 if (childrel->parent)
630 elog(
ERROR,
"childrel is not a child of parentrel");
633 /* Now translate for this child. */
644 * adjust_inherited_attnums
645 * Translate an integer list of attribute numbers from parent to child.
653 /* This should only happen for an inheritance case, not UNION ALL */
656 /* Look up each attribute in the AppendRelInfo's translated_vars list */
662 /* Look up the translation of this column: it must be a Var */
663 if (parentattno <= 0 ||
665 elog(
ERROR,
"attribute %d of relation \"%s\" does not exist",
668 if (childvar == NULL || !
IsA(childvar,
Var))
669 elog(
ERROR,
"attribute %d of relation \"%s\" does not exist",
678 * adjust_inherited_attnums_multilevel
679 * As above, but traverse multiple inheritance levels as needed.
688 elog(
ERROR,
"child rel %d not found in append_rel_array", child_relid);
690 /* Recurse if immediate parent is not the top parent. */
696 /* Now translate for this child */
701 * get_translated_update_targetlist
702 * Get the processed_tlist of an UPDATE query, translated as needed to
703 * match a child target relation.
705 * Optionally also return the list of target column numbers translated
706 * to this target relation. (The resnos in processed_tlist MUST NOT be
707 * relied on for this purpose.)
711 List **processed_tlist,
List **update_colnos)
713 /* This is pretty meaningless for commands other than UPDATE. */
715 if (relid ==
root->parse->resultRelation)
718 * Non-inheritance case, so it's easy. The caller might be expecting
719 * a tree it can scribble on, though, so copy.
728 *processed_tlist = (
List *)
737 root->parse->resultRelation);
742 * find_appinfos_by_relids
743 * Find AppendRelInfo structures for base relations listed in relids.
745 * The relids argument is typically a join relation's relids, which can
746 * include outer-join RT indexes in addition to baserels. We silently
747 * ignore the outer joins.
749 * The AppendRelInfos are returned in an array, which can be pfree'd by the
750 * caller. *nappinfos is set to the number of entries in the array.
759 /* Allocate an array that's certainly big enough */
770 /* Probably i is an OJ index, but let's check */
773 /* It's a base rel, but we lack an append_rel_array entry */
774 elog(
ERROR,
"child rel %d not found in append_rel_array",
i);
777 appinfos[cnt++] = appinfo;
784/*****************************************************************************
786 * ROW-IDENTITY VARIABLE MANAGEMENT
788 * This code lacks a good home, perhaps. We choose to keep it here because
789 * adjust_appendrel_attrs_mutator() is its principal co-conspirator. That
790 * function does most of what is needed to expand ROWID_VAR Vars into the
793 *****************************************************************************/
796 * add_row_identity_var
797 * Register a row-identity column to be used in UPDATE/DELETE/MERGE.
799 * The Var must be equal(), aside from varno, to any other row-identity
800 * column with the same rowid_name. Thus, for example, "wholerow"
801 * row identities had better use vartype == RECORDOID.
803 * rtindex is currently redundant with rowid_var->varno, but we specify
804 * it as a separate parameter in case this is ever generalized to support
805 * non-Var expressions. (We could reasonably handle expressions over
806 * Vars of the specified rtindex, but for now that seems unnecessary.)
810 Index rtindex,
const char *rowid_name)
817 /* For now, the argument must be just a Var of the given rtindex */
821 Assert(orig_var->varnullingrels == NULL);
824 * If we're doing non-inherited UPDATE/DELETE/MERGE, there's little need
825 * for ROWID_VAR shenanigans. Just shove the presented Var into the
826 * processed_tlist, and we're done.
828 if (rtindex ==
root->parse->resultRelation)
839 * Otherwise, rtindex should reference a leaf target relation that's being
840 * added to the query during expand_inherited_rtentry().
843 Assert(
root->append_rel_array[rtindex] != NULL);
846 * We have to find a matching RowIdentityVarInfo, or make one if there is
847 * none. To allow using equal() to match the vars, change the varno to
848 * ROWID_VAR, leaving all else alone.
851 /* This could eventually become ChangeVarNodes() */
854 /* Look for an existing row-id column of the same name */
855 foreach(lc,
root->row_identity_vars)
858 if (strcmp(rowid_name, ridinfo->
rowidname) != 0)
862 /* Found a match; we need only record that rtindex needs it too */
868 /* Ooops, can't handle this */
869 elog(
ERROR,
"conflicting uses of row-identity name \"%s\"",
874 /* No request yet, so add a new RowIdentityVarInfo */
877 /* for the moment, estimate width using just the datatype info */
885 /* Change rowid_var into a reference to this row_identity_vars entry */
888 /* Push the ROWID_VAR reference variable into processed_tlist */
897 * add_row_identity_columns
899 * This function adds the row identity columns needed by the core code.
900 * FDWs might call add_row_identity_var() for themselves to add nonstandard
901 * columns. (Duplicate requests are fine.)
909 char relkind = target_relation->
rd_rel->relkind;
914 if (relkind == RELKIND_RELATION ||
915 relkind == RELKIND_MATVIEW ||
916 relkind == RELKIND_PARTITIONED_TABLE)
919 * Emit CTID so that executor can find the row to merge, update or
930 else if (relkind == RELKIND_FOREIGN_TABLE)
933 * Let the foreign table's FDW add whatever junk TLEs it wants.
941 target_rte, target_relation);
944 * For UPDATE, we need to make the FDW fetch unchanged columns by
945 * asking it to fetch a whole-row Var. That's because the top-level
946 * targetlist only contains entries for changed columns, but
947 * ExecUpdate will need to build the complete new tuple. (Actually,
948 * we only really need this in UPDATEs that are not pushed to the
949 * remote side, but it's hard to tell if that will be the case at the
950 * point when this function is called.)
952 * We will also need the whole row if there are any row triggers, so
953 * that the executor will have the "old" row to pass to the trigger.
954 * Alas, this misses system columns.
973 * distribute_row_identity_vars
975 * After we have finished identifying all the row identity columns
976 * needed by an inherited UPDATE/DELETE/MERGE query, make sure that
977 * these columns will be generated by all the target relations.
979 * This is more or less like what build_base_rel_tlists() does,
980 * except that it would not understand what to do with ROWID_VAR Vars.
981 * Since that function runs before inheritance relations are expanded,
982 * it will never see any such Vars anyway.
988 int result_relation =
parse->resultRelation;
994 * There's nothing to do if this isn't an inherited UPDATE/DELETE/MERGE.
1003 if (!target_rte->
inh)
1010 * Ordinarily, we expect that leaf result relation(s) will have added some
1011 * ROWID_VAR Vars to the query. However, it's possible that constraint
1012 * exclusion suppressed every leaf relation. The executor will get upset
1013 * if the plan has no row identity columns at all, even though it will
1014 * certainly process no rows. Handle this edge case by re-opening the top
1015 * result relation and adding the row identity columns it would have used,
1016 * as preprocess_targetlist() would have done if it weren't marked "inh".
1017 * Then re-run build_base_rel_tlists() to ensure that the added columns
1018 * get propagated to the relation's reltarget. (This is a bit ugly, but
1019 * it seems better to confine the ugliness and extra cycles to this
1020 * unusual corner case.)
1022 if (
root->row_identity_vars ==
NIL)
1028 target_rte, target_relation);
1031 /* There are no ROWID_VAR Vars in this case, so we're done. */
1036 * Dig through the processed_tlist to find the ROWID_VAR reference Vars,
1037 * and forcibly copy them into the reltarget list of the topmost target
1038 * relation. That's sufficient because they'll be copied to the
1039 * individual leaf target rels (with appropriate translation) later,
1040 * during appendrel expansion --- see set_append_rel_size().
1044 foreach(lc,
root->processed_tlist)
1053 /* reltarget cost and width will be computed later */
void distribute_row_identity_vars(PlannerInfo *root)
void get_translated_update_targetlist(PlannerInfo *root, Index relid, List **processed_tlist, List **update_colnos)
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
static void make_inh_translation_list(Relation oldrelation, Relation newrelation, Index newvarno, AppendRelInfo *appinfo)
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Relids adjust_child_relids_multilevel(PlannerInfo *root, Relids relids, RelOptInfo *childrel, RelOptInfo *parentrel)
List * adjust_inherited_attnums_multilevel(PlannerInfo *root, List *attnums, Index child_relid, Index top_parent_relid)
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, RelOptInfo *childrel, RelOptInfo *parentrel)
void add_row_identity_columns(PlannerInfo *root, Index rtindex, RangeTblEntry *target_rte, Relation target_relation)
static Node * adjust_appendrel_attrs_mutator(Node *node, adjust_appendrel_attrs_context *context)
AppendRelInfo * make_append_rel_info(Relation parentrel, Relation childrel, Index parentRTindex, Index childRTindex)
Relids adjust_child_relids(Relids relids, int nappinfos, AppendRelInfo **appinfos)
void add_row_identity_var(PlannerInfo *root, Var *orig_var, Index rtindex, const char *rowid_name)
List * adjust_inherited_attnums(List *attnums, AppendRelInfo *context)
#define InvalidAttrNumber
Bitmapset * bms_make_singleton(int x)
int bms_next_member(const Bitmapset *a, int prevbit)
Bitmapset * bms_del_member(Bitmapset *a, int x)
int bms_num_members(const Bitmapset *a)
bool bms_is_member(int x, const Bitmapset *a)
Bitmapset * bms_add_member(Bitmapset *a, int x)
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Bitmapset * bms_copy(const Bitmapset *a)
#define OidIsValid(objectId)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
bool equal(const void *a, const void *b)
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
void build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
if(TABLE==NULL||TABLE_index==NULL)
List * lappend(List *list, void *datum)
List * lappend_int(List *list, int datum)
char * get_rel_name(Oid relid)
int32 get_typavgwidth(Oid typid, int32 typmod)
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
char * pstrdup(const char *in)
void pfree(void *pointer)
void * palloc0(Size size)
Oid exprType(const Node *expr)
int32 exprTypmod(const Node *expr)
#define expression_tree_mutator(n, m, c)
#define IsA(nodeptr, _type_)
#define rt_fetch(rangetable_index, rangetable)
FormData_pg_attribute * Form_pg_attribute
static int list_length(const List *l)
static void * list_nth(const List *list, int n)
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
#define RelationGetRelid(relation)
#define RelationGetDescr(relation)
#define RelationGetRelationName(relation)
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
RelOptInfo * find_base_rel_ignore_join(PlannerInfo *root, int relid)
AddForeignUpdateTargets_function AddForeignUpdateTargets
Relids leaf_result_relids
struct PathTarget * reltarget
bool trig_delete_before_row
bool trig_delete_after_row
VarReturningType varreturningtype
AppendRelInfo ** appinfos
#define SelfItemPointerAttributeNumber
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCacheAttName(Oid relid, const char *attname)
void table_close(Relation relation, LOCKMODE lockmode)
Relation table_open(Oid relationId, LOCKMODE lockmode)
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)