Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * inherit.c
4 : * Routines to process child relations in inheritance trees
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/optimizer/util/inherit.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : #include "postgres.h"
16 :
17 : #include "access/sysattr.h"
18 : #include "access/table.h"
19 : #include "catalog/partition.h"
20 : #include "catalog/pg_inherits.h"
21 : #include "catalog/pg_type.h"
22 : #include "miscadmin.h"
23 : #include "nodes/makefuncs.h"
24 : #include "optimizer/appendinfo.h"
25 : #include "optimizer/inherit.h"
26 : #include "optimizer/optimizer.h"
27 : #include "optimizer/pathnode.h"
28 : #include "optimizer/plancat.h"
29 : #include "optimizer/planmain.h"
30 : #include "optimizer/planner.h"
31 : #include "optimizer/prep.h"
32 : #include "optimizer/restrictinfo.h"
33 : #include "parser/parsetree.h"
34 : #include "parser/parse_relation.h"
35 : #include "partitioning/partdesc.h"
36 : #include "partitioning/partprune.h"
37 : #include "utils/rel.h"
38 :
39 :
40 : static void expand_partitioned_rtentry(PlannerInfo *root, RelOptInfo *relinfo,
41 : RangeTblEntry *parentrte,
42 : Index parentRTindex, Relation parentrel,
43 : Bitmapset *parent_updatedCols,
44 : PlanRowMark *top_parentrc, LOCKMODE lockmode);
45 : static void expand_single_inheritance_child(PlannerInfo *root,
46 : RangeTblEntry *parentrte,
47 : Index parentRTindex, Relation parentrel,
48 : PlanRowMark *top_parentrc, Relation childrel,
49 : RangeTblEntry **childrte_p,
50 : Index *childRTindex_p);
51 : static Bitmapset *translate_col_privs(const Bitmapset *parent_privs,
52 : List *translated_vars);
53 : static Bitmapset *translate_col_privs_multilevel(PlannerInfo *root,
54 : RelOptInfo *rel,
55 : RelOptInfo *parent_rel,
56 : Bitmapset *parent_cols);
57 : static void expand_appendrel_subquery(PlannerInfo *root, RelOptInfo *rel,
58 : RangeTblEntry *rte, Index rti);
59 :
60 :
61 : /*
62 : * expand_inherited_rtentry
63 : * Expand a rangetable entry that has the "inh" bit set.
64 : *
65 : * "inh" is only allowed in two cases: RELATION and SUBQUERY RTEs.
66 : *
67 : * "inh" on a plain RELATION RTE means that it is a partitioned table or the
68 : * parent of a traditional-inheritance set. In this case we must add entries
69 : * for all the interesting child tables to the query's rangetable, and build
70 : * additional planner data structures for them, including RelOptInfos,
71 : * AppendRelInfos, and possibly PlanRowMarks.
72 : *
73 : * Note that the original RTE is considered to represent the whole inheritance
74 : * set. In the case of traditional inheritance, the first of the generated
75 : * RTEs is an RTE for the same table, but with inh = false, to represent the
76 : * parent table in its role as a simple member of the inheritance set. For
77 : * partitioning, we don't need a second RTE because the partitioned table
78 : * itself has no data and need not be scanned.
79 : *
80 : * "inh" on a SUBQUERY RTE means that it's the parent of a UNION ALL group,
81 : * which is treated as an appendrel similarly to inheritance cases; however,
82 : * we already made RTEs and AppendRelInfos for the subqueries. We only need
83 : * to build RelOptInfos for them, which is done by expand_appendrel_subquery.
84 : */
85 : void
86 20990 : expand_inherited_rtentry(PlannerInfo *root, RelOptInfo *rel,
87 : RangeTblEntry *rte, Index rti)
88 : {
89 : Oid parentOID;
90 : Relation oldrelation;
91 : LOCKMODE lockmode;
92 : PlanRowMark *oldrc;
93 20990 : bool old_isParent = false;
94 20990 : int old_allMarkTypes = 0;
95 :
96 : Assert(rte->inh); /* else caller error */
97 :
98 20990 : if (rte->rtekind == RTE_SUBQUERY)
99 : {
100 4644 : expand_appendrel_subquery(root, rel, rte, rti);
101 4644 : return;
102 : }
103 :
104 : Assert(rte->rtekind == RTE_RELATION);
105 :
106 16346 : parentOID = rte->relid;
107 :
108 : /*
109 : * We used to check has_subclass() here, but there's no longer any need
110 : * to, because subquery_planner already did.
111 : */
112 :
113 : /*
114 : * The rewriter should already have obtained an appropriate lock on each
115 : * relation named in the query, so we can open the parent relation without
116 : * locking it. However, for each child relation we add to the query, we
117 : * must obtain an appropriate lock, because this will be the first use of
118 : * those relations in the parse/rewrite/plan pipeline. Child rels should
119 : * use the same lockmode as their parent.
120 : */
121 16346 : oldrelation = table_open(parentOID, NoLock);
122 16346 : lockmode = rte->rellockmode;
123 :
124 : /*
125 : * If parent relation is selected FOR UPDATE/SHARE, we need to mark its
126 : * PlanRowMark as isParent = true, and generate a new PlanRowMark for each
127 : * child.
128 : */
129 16346 : oldrc = get_plan_rowmark(root->rowMarks, rti);
130 16346 : if (oldrc)
131 : {
132 1604 : old_isParent = oldrc->isParent;
133 1604 : oldrc->isParent = true;
134 : /* Save initial value of allMarkTypes before children add to it */
135 1604 : old_allMarkTypes = oldrc->allMarkTypes;
136 : }
137 :
138 : /* Scan the inheritance set and expand it */
139 16346 : if (oldrelation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
140 : {
141 : RTEPermissionInfo *perminfo;
142 :
143 13628 : perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
144 :
145 : /*
146 : * Partitioned table, so set up for partitioning.
147 : */
148 : Assert(rte->relkind == RELKIND_PARTITIONED_TABLE);
149 :
150 : /*
151 : * Recursively expand and lock the partitions. While at it, also
152 : * extract the partition key columns of all the partitioned tables.
153 : */
154 13628 : expand_partitioned_rtentry(root, rel, rte, rti,
155 : oldrelation,
156 : perminfo->updatedCols,
157 : oldrc, lockmode);
158 : }
159 : else
160 : {
161 : /*
162 : * Ordinary table, so process traditional-inheritance children. (Note
163 : * that partitioned tables are not allowed to have inheritance
164 : * children, so it's not possible for both cases to apply.)
165 : */
166 : List *inhOIDs;
167 : ListCell *l;
168 :
169 : /* Scan for all members of inheritance set, acquire needed locks */
170 2718 : inhOIDs = find_all_inheritors(parentOID, lockmode, NULL);
171 :
172 : /*
173 : * We used to special-case the situation where the table no longer has
174 : * any children, by clearing rte->inh and exiting. That no longer
175 : * works, because this function doesn't get run until after decisions
176 : * have been made that depend on rte->inh. We have to treat such
177 : * situations as normal inheritance. The table itself should always
178 : * have been found, though.
179 : */
180 : Assert(inhOIDs != NIL);
181 : Assert(linitial_oid(inhOIDs) == parentOID);
182 :
183 : /* Expand simple_rel_array and friends to hold child objects. */
184 2718 : expand_planner_arrays(root, list_length(inhOIDs));
185 :
186 : /*
187 : * Expand inheritance children in the order the OIDs were returned by
188 : * find_all_inheritors.
189 : */
190 9870 : foreach(l, inhOIDs)
191 : {
192 7154 : Oid childOID = lfirst_oid(l);
193 : Relation newrelation;
194 : RangeTblEntry *childrte;
195 : Index childRTindex;
196 :
197 : /* Open rel if needed; we already have required locks */
198 7154 : if (childOID != parentOID)
199 4436 : newrelation = table_open(childOID, NoLock);
200 : else
201 2718 : newrelation = oldrelation;
202 :
203 : /*
204 : * It is possible that the parent table has children that are temp
205 : * tables of other backends. We cannot safely access such tables
206 : * (because of buffering issues), and the best thing to do seems
207 : * to be to silently ignore them.
208 : */
209 7154 : if (childOID != parentOID && RELATION_IS_OTHER_TEMP(newrelation))
210 : {
211 42 : table_close(newrelation, lockmode);
212 42 : continue;
213 : }
214 :
215 : /* Create RTE and AppendRelInfo, plus PlanRowMark if needed. */
216 7112 : expand_single_inheritance_child(root, rte, rti, oldrelation,
217 : oldrc, newrelation,
218 : &childrte, &childRTindex);
219 :
220 : /* Create the otherrel RelOptInfo too. */
221 7110 : (void) build_simple_rel(root, childRTindex, rel);
222 :
223 : /* Close child relations, but keep locks */
224 7110 : if (childOID != parentOID)
225 4392 : table_close(newrelation, NoLock);
226 : }
227 : }
228 :
229 : /*
230 : * Some children might require different mark types, which would've been
231 : * reported into oldrc. If so, add relevant entries to the top-level
232 : * targetlist and update parent rel's reltarget. This should match what
233 : * preprocess_targetlist() would have added if the mark types had been
234 : * requested originally.
235 : *
236 : * (Someday it might be useful to fold these resjunk columns into the
237 : * row-identity-column management used for UPDATE/DELETE. Today is not
238 : * that day, however.)
239 : */
240 16344 : if (oldrc)
241 : {
242 1604 : int new_allMarkTypes = oldrc->allMarkTypes;
243 : Var *var;
244 : TargetEntry *tle;
245 : char resname[32];
246 1604 : List *newvars = NIL;
247 :
248 : /* Add TID junk Var if needed, unless we had it already */
249 1604 : if (new_allMarkTypes & ~(1 << ROW_MARK_COPY) &&
250 1600 : !(old_allMarkTypes & ~(1 << ROW_MARK_COPY)))
251 : {
252 : /* Need to fetch TID */
253 4 : var = makeVar(oldrc->rti,
254 : SelfItemPointerAttributeNumber,
255 : TIDOID,
256 : -1,
257 : InvalidOid,
258 : 0);
259 4 : snprintf(resname, sizeof(resname), "ctid%u", oldrc->rowmarkId);
260 4 : tle = makeTargetEntry((Expr *) var,
261 4 : list_length(root->processed_tlist) + 1,
262 : pstrdup(resname),
263 : true);
264 4 : root->processed_tlist = lappend(root->processed_tlist, tle);
265 4 : newvars = lappend(newvars, var);
266 : }
267 :
268 : /* Add whole-row junk Var if needed, unless we had it already */
269 1604 : if ((new_allMarkTypes & (1 << ROW_MARK_COPY)) &&
270 46 : !(old_allMarkTypes & (1 << ROW_MARK_COPY)))
271 : {
272 38 : var = makeWholeRowVar(planner_rt_fetch(oldrc->rti, root),
273 38 : oldrc->rti,
274 : 0,
275 : false);
276 38 : snprintf(resname, sizeof(resname), "wholerow%u", oldrc->rowmarkId);
277 38 : tle = makeTargetEntry((Expr *) var,
278 38 : list_length(root->processed_tlist) + 1,
279 : pstrdup(resname),
280 : true);
281 38 : root->processed_tlist = lappend(root->processed_tlist, tle);
282 38 : newvars = lappend(newvars, var);
283 : }
284 :
285 : /* Add tableoid junk Var, unless we had it already */
286 1604 : if (!old_isParent)
287 : {
288 1604 : var = makeVar(oldrc->rti,
289 : TableOidAttributeNumber,
290 : OIDOID,
291 : -1,
292 : InvalidOid,
293 : 0);
294 1604 : snprintf(resname, sizeof(resname), "tableoid%u", oldrc->rowmarkId);
295 1604 : tle = makeTargetEntry((Expr *) var,
296 1604 : list_length(root->processed_tlist) + 1,
297 : pstrdup(resname),
298 : true);
299 1604 : root->processed_tlist = lappend(root->processed_tlist, tle);
300 1604 : newvars = lappend(newvars, var);
301 : }
302 :
303 : /*
304 : * Add the newly added Vars to parent's reltarget. We needn't worry
305 : * about the children's reltargets, they'll be made later.
306 : */
307 1604 : add_vars_to_targetlist(root, newvars, bms_make_singleton(0));
308 : }
309 :
310 16344 : table_close(oldrelation, NoLock);
311 : }
312 :
313 : /*
314 : * expand_partitioned_rtentry
315 : * Recursively expand an RTE for a partitioned table.
316 : */
317 : static void
318 16956 : expand_partitioned_rtentry(PlannerInfo *root, RelOptInfo *relinfo,
319 : RangeTblEntry *parentrte,
320 : Index parentRTindex, Relation parentrel,
321 : Bitmapset *parent_updatedCols,
322 : PlanRowMark *top_parentrc, LOCKMODE lockmode)
323 : {
324 : PartitionDesc partdesc;
325 : Bitmapset *live_parts;
326 : int num_live_parts;
327 : int i;
328 :
329 16956 : check_stack_depth();
330 :
331 : Assert(parentrte->inh);
332 :
333 16956 : partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
334 : parentrel);
335 :
336 : /* A partitioned table should always have a partition descriptor. */
337 : Assert(partdesc);
338 :
339 : /*
340 : * Note down whether any partition key cols are being updated. Though it's
341 : * the root partitioned table's updatedCols we are interested in,
342 : * parent_updatedCols provided by the caller contains the root partrel's
343 : * updatedCols translated to match the attribute ordering of parentrel.
344 : */
345 16956 : if (!root->partColsUpdated)
346 16650 : root->partColsUpdated =
347 16650 : has_partition_attrs(parentrel, parent_updatedCols, NULL);
348 :
349 : /* Nothing further to do here if there are no partitions. */
350 16956 : if (partdesc->nparts == 0)
351 42 : return;
352 :
353 : /*
354 : * Perform partition pruning using restriction clauses assigned to parent
355 : * relation. live_parts will contain PartitionDesc indexes of partitions
356 : * that survive pruning. Below, we will initialize child objects for the
357 : * surviving partitions.
358 : */
359 16914 : relinfo->live_parts = live_parts = prune_append_rel_partitions(relinfo);
360 :
361 : /* Expand simple_rel_array and friends to hold child objects. */
362 16914 : num_live_parts = bms_num_members(live_parts);
363 16914 : if (num_live_parts > 0)
364 16626 : expand_planner_arrays(root, num_live_parts);
365 :
366 : /*
367 : * We also store partition RelOptInfo pointers in the parent relation.
368 : * Since we're palloc0'ing, slots corresponding to pruned partitions will
369 : * contain NULL.
370 : */
371 : Assert(relinfo->part_rels == NULL);
372 16914 : relinfo->part_rels = (RelOptInfo **)
373 16914 : palloc0(relinfo->nparts * sizeof(RelOptInfo *));
374 :
375 : /*
376 : * Create a child RTE for each live partition. Note that unlike
377 : * traditional inheritance, we don't need a child RTE for the partitioned
378 : * table itself, because it's not going to be scanned.
379 : */
380 16914 : i = -1;
381 50344 : while ((i = bms_next_member(live_parts, i)) >= 0)
382 : {
383 33430 : Oid childOID = partdesc->oids[i];
384 : Relation childrel;
385 : RangeTblEntry *childrte;
386 : Index childRTindex;
387 : RelOptInfo *childrelinfo;
388 :
389 : /*
390 : * Open rel, acquiring required locks. If a partition was recently
391 : * detached and subsequently dropped, then opening it will fail. In
392 : * this case, behave as though the partition had been pruned.
393 : */
394 33430 : childrel = try_table_open(childOID, lockmode);
395 33430 : if (childrel == NULL)
396 : {
397 0 : relinfo->live_parts = bms_del_member(relinfo->live_parts, i);
398 0 : continue;
399 : }
400 :
401 : /*
402 : * Temporary partitions belonging to other sessions should have been
403 : * disallowed at definition, but for paranoia's sake, let's double
404 : * check.
405 : */
406 33430 : if (RELATION_IS_OTHER_TEMP(childrel))
407 0 : elog(ERROR, "temporary relation from another session found as partition");
408 :
409 : /* Create RTE and AppendRelInfo, plus PlanRowMark if needed. */
410 33430 : expand_single_inheritance_child(root, parentrte, parentRTindex,
411 : parentrel, top_parentrc, childrel,
412 : &childrte, &childRTindex);
413 :
414 : /* Create the otherrel RelOptInfo too. */
415 33430 : childrelinfo = build_simple_rel(root, childRTindex, relinfo);
416 33430 : relinfo->part_rels[i] = childrelinfo;
417 66860 : relinfo->all_partrels = bms_add_members(relinfo->all_partrels,
418 33430 : childrelinfo->relids);
419 :
420 : /* If this child is itself partitioned, recurse */
421 33430 : if (childrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
422 : {
423 3328 : AppendRelInfo *appinfo = root->append_rel_array[childRTindex];
424 : Bitmapset *child_updatedCols;
425 :
426 3328 : child_updatedCols = translate_col_privs(parent_updatedCols,
427 : appinfo->translated_vars);
428 :
429 3328 : expand_partitioned_rtentry(root, childrelinfo,
430 : childrte, childRTindex,
431 : childrel,
432 : child_updatedCols,
433 : top_parentrc, lockmode);
434 : }
435 :
436 : /* Close child relation, but keep locks */
437 33430 : table_close(childrel, NoLock);
438 : }
439 : }
440 :
441 : /*
442 : * expand_single_inheritance_child
443 : * Build a RangeTblEntry and an AppendRelInfo, plus maybe a PlanRowMark.
444 : *
445 : * We now expand the partition hierarchy level by level, creating a
446 : * corresponding hierarchy of AppendRelInfos and RelOptInfos, where each
447 : * partitioned descendant acts as a parent of its immediate partitions.
448 : * (This is a difference from what older versions of PostgreSQL did and what
449 : * is still done in the case of table inheritance for unpartitioned tables,
450 : * where the hierarchy is flattened during RTE expansion.)
451 : *
452 : * PlanRowMarks still carry the top-parent's RTI, and the top-parent's
453 : * allMarkTypes field still accumulates values from all descendents.
454 : *
455 : * "parentrte" and "parentRTindex" are immediate parent's RTE and
456 : * RTI. "top_parentrc" is top parent's PlanRowMark.
457 : *
458 : * The child RangeTblEntry and its RTI are returned in "childrte_p" and
459 : * "childRTindex_p" resp.
460 : */
461 : static void
462 40542 : expand_single_inheritance_child(PlannerInfo *root, RangeTblEntry *parentrte,
463 : Index parentRTindex, Relation parentrel,
464 : PlanRowMark *top_parentrc, Relation childrel,
465 : RangeTblEntry **childrte_p,
466 : Index *childRTindex_p)
467 : {
468 40542 : Query *parse = root->parse;
469 40542 : Oid parentOID = RelationGetRelid(parentrel);
470 40542 : Oid childOID = RelationGetRelid(childrel);
471 : RangeTblEntry *childrte;
472 : Index childRTindex;
473 : AppendRelInfo *appinfo;
474 : TupleDesc child_tupdesc;
475 : List *parent_colnames;
476 : List *child_colnames;
477 :
478 : /*
479 : * Build an RTE for the child, and attach to query's rangetable list. We
480 : * copy most scalar fields of the parent's RTE, but replace relation OID,
481 : * relkind, and inh for the child. Set the child's securityQuals to
482 : * empty, because we only want to apply the parent's RLS conditions
483 : * regardless of what RLS properties individual children may have. (This
484 : * is an intentional choice to make inherited RLS work like regular
485 : * permissions checks.) The parent securityQuals will be propagated to
486 : * children along with other base restriction clauses, so we don't need to
487 : * do it here. Other infrastructure of the parent RTE has to be
488 : * translated to match the child table's column ordering, which we do
489 : * below, so a "flat" copy is sufficient to start with.
490 : */
491 40542 : childrte = makeNode(RangeTblEntry);
492 40542 : memcpy(childrte, parentrte, sizeof(RangeTblEntry));
493 : Assert(parentrte->rtekind == RTE_RELATION); /* else this is dubious */
494 40542 : childrte->relid = childOID;
495 40542 : childrte->relkind = childrel->rd_rel->relkind;
496 : /* A partitioned child will need to be expanded further. */
497 40542 : if (childrte->relkind == RELKIND_PARTITIONED_TABLE)
498 : {
499 : Assert(childOID != parentOID);
500 3328 : childrte->inh = true;
501 : }
502 : else
503 37214 : childrte->inh = false;
504 40542 : childrte->securityQuals = NIL;
505 :
506 : /* No permission checking for child RTEs. */
507 40542 : childrte->perminfoindex = 0;
508 :
509 : /* Link not-yet-fully-filled child RTE into data structures */
510 40542 : parse->rtable = lappend(parse->rtable, childrte);
511 40542 : childRTindex = list_length(parse->rtable);
512 40542 : *childrte_p = childrte;
513 40542 : *childRTindex_p = childRTindex;
514 :
515 : /*
516 : * Retrieve column not-null constraint information for the child relation
517 : * if its relation OID is different from the parent's.
518 : */
519 40542 : if (childOID != parentOID)
520 37824 : get_relation_notnullatts(root, childrel);
521 :
522 : /*
523 : * Build an AppendRelInfo struct for each parent/child pair.
524 : */
525 40542 : appinfo = make_append_rel_info(parentrel, childrel,
526 : parentRTindex, childRTindex);
527 40540 : root->append_rel_list = lappend(root->append_rel_list, appinfo);
528 :
529 : /* tablesample is probably null, but copy it */
530 40540 : childrte->tablesample = copyObject(parentrte->tablesample);
531 :
532 : /*
533 : * Construct an alias clause for the child, which we can also use as eref.
534 : * This is important so that EXPLAIN will print the right column aliases
535 : * for child-table columns. (Since ruleutils.c doesn't have any easy way
536 : * to reassociate parent and child columns, we must get the child column
537 : * aliases right to start with. Note that setting childrte->alias forces
538 : * ruleutils.c to use these column names, which it otherwise would not.)
539 : */
540 40540 : child_tupdesc = RelationGetDescr(childrel);
541 40540 : parent_colnames = parentrte->eref->colnames;
542 40540 : child_colnames = NIL;
543 153946 : for (int cattno = 0; cattno < child_tupdesc->natts; cattno++)
544 : {
545 113406 : Form_pg_attribute att = TupleDescAttr(child_tupdesc, cattno);
546 : const char *attname;
547 :
548 113406 : if (att->attisdropped)
549 : {
550 : /* Always insert an empty string for a dropped column */
551 2356 : attname = "";
552 : }
553 218194 : else if (appinfo->parent_colnos[cattno] > 0 &&
554 107144 : appinfo->parent_colnos[cattno] <= list_length(parent_colnames))
555 : {
556 : /* Duplicate the query-assigned name for the parent column */
557 107144 : attname = strVal(list_nth(parent_colnames,
558 : appinfo->parent_colnos[cattno] - 1));
559 : }
560 : else
561 : {
562 : /* New column, just use its real name */
563 3906 : attname = NameStr(att->attname);
564 : }
565 113406 : child_colnames = lappend(child_colnames, makeString(pstrdup(attname)));
566 : }
567 :
568 : /*
569 : * We just duplicate the parent's table alias name for each child. If the
570 : * plan gets printed, ruleutils.c has to sort out unique table aliases to
571 : * use, which it can handle.
572 : */
573 40540 : childrte->alias = childrte->eref = makeAlias(parentrte->eref->aliasname,
574 : child_colnames);
575 :
576 : /*
577 : * Store the RTE and appinfo in the respective PlannerInfo arrays, which
578 : * the caller must already have allocated space for.
579 : */
580 : Assert(childRTindex < root->simple_rel_array_size);
581 : Assert(root->simple_rte_array[childRTindex] == NULL);
582 40540 : root->simple_rte_array[childRTindex] = childrte;
583 : Assert(root->append_rel_array[childRTindex] == NULL);
584 40540 : root->append_rel_array[childRTindex] = appinfo;
585 :
586 : /*
587 : * Build a PlanRowMark if parent is marked FOR UPDATE/SHARE.
588 : */
589 40540 : if (top_parentrc)
590 : {
591 2332 : PlanRowMark *childrc = makeNode(PlanRowMark);
592 :
593 2332 : childrc->rti = childRTindex;
594 2332 : childrc->prti = top_parentrc->rti;
595 2332 : childrc->rowmarkId = top_parentrc->rowmarkId;
596 : /* Reselect rowmark type, because relkind might not match parent */
597 2332 : childrc->markType = select_rowmark_type(childrte,
598 : top_parentrc->strength);
599 2332 : childrc->allMarkTypes = (1 << childrc->markType);
600 2332 : childrc->strength = top_parentrc->strength;
601 2332 : childrc->waitPolicy = top_parentrc->waitPolicy;
602 :
603 : /*
604 : * We mark RowMarks for partitioned child tables as parent RowMarks so
605 : * that the executor ignores them (except their existence means that
606 : * the child tables will be locked using the appropriate mode).
607 : */
608 2332 : childrc->isParent = (childrte->relkind == RELKIND_PARTITIONED_TABLE);
609 :
610 : /* Include child's rowmark type in top parent's allMarkTypes */
611 2332 : top_parentrc->allMarkTypes |= childrc->allMarkTypes;
612 :
613 2332 : root->rowMarks = lappend(root->rowMarks, childrc);
614 : }
615 :
616 : /*
617 : * If we are creating a child of the query target relation (only possible
618 : * in UPDATE/DELETE/MERGE), add it to all_result_relids, as well as
619 : * leaf_result_relids if appropriate, and make sure that we generate
620 : * required row-identity data.
621 : */
622 40540 : if (bms_is_member(parentRTindex, root->all_result_relids))
623 : {
624 : /* OK, record the child as a result rel too. */
625 5984 : root->all_result_relids = bms_add_member(root->all_result_relids,
626 : childRTindex);
627 :
628 : /* Non-leaf partitions don't need any row identity info. */
629 5984 : if (childrte->relkind != RELKIND_PARTITIONED_TABLE)
630 : {
631 : Var *rrvar;
632 :
633 5414 : root->leaf_result_relids = bms_add_member(root->leaf_result_relids,
634 : childRTindex);
635 :
636 : /*
637 : * If we have any child target relations, assume they all need to
638 : * generate a junk "tableoid" column. (If only one child survives
639 : * pruning, we wouldn't really need this, but it's not worth
640 : * thrashing about to avoid it.)
641 : */
642 5414 : rrvar = makeVar(childRTindex,
643 : TableOidAttributeNumber,
644 : OIDOID,
645 : -1,
646 : InvalidOid,
647 : 0);
648 5414 : add_row_identity_var(root, rrvar, childRTindex, "tableoid");
649 :
650 : /* Register any row-identity columns needed by this child. */
651 5414 : add_row_identity_columns(root, childRTindex,
652 : childrte, childrel);
653 : }
654 : }
655 40540 : }
656 :
657 : /*
658 : * get_rel_all_updated_cols
659 : * Returns the set of columns of a given "simple" relation that are
660 : * updated by this query.
661 : */
662 : Bitmapset *
663 82 : get_rel_all_updated_cols(PlannerInfo *root, RelOptInfo *rel)
664 : {
665 : Index relid;
666 : RangeTblEntry *rte;
667 : RTEPermissionInfo *perminfo;
668 : Bitmapset *updatedCols,
669 : *extraUpdatedCols;
670 :
671 : Assert(root->parse->commandType == CMD_UPDATE);
672 : Assert(IS_SIMPLE_REL(rel));
673 :
674 : /*
675 : * We obtain updatedCols for the query's result relation. Then, if
676 : * necessary, we map it to the column numbers of the relation for which
677 : * they were requested.
678 : */
679 82 : relid = root->parse->resultRelation;
680 82 : rte = planner_rt_fetch(relid, root);
681 82 : perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
682 :
683 82 : updatedCols = perminfo->updatedCols;
684 :
685 82 : if (rel->relid != relid)
686 : {
687 34 : RelOptInfo *top_parent_rel = find_base_rel(root, relid);
688 :
689 : Assert(IS_OTHER_REL(rel));
690 :
691 34 : updatedCols = translate_col_privs_multilevel(root, rel, top_parent_rel,
692 : updatedCols);
693 : }
694 :
695 : /*
696 : * Now we must check to see if there are any generated columns that depend
697 : * on the updatedCols, and add them to the result.
698 : */
699 82 : extraUpdatedCols = get_dependent_generated_columns(root, rel->relid,
700 : updatedCols);
701 :
702 82 : return bms_union(updatedCols, extraUpdatedCols);
703 : }
704 :
705 : /*
706 : * translate_col_privs
707 : * Translate a bitmapset representing per-column privileges from the
708 : * parent rel's attribute numbering to the child's.
709 : *
710 : * The only surprise here is that we don't translate a parent whole-row
711 : * reference into a child whole-row reference. That would mean requiring
712 : * permissions on all child columns, which is overly strict, since the
713 : * query is really only going to reference the inherited columns. Instead
714 : * we set the per-column bits for all inherited columns.
715 : */
716 : static Bitmapset *
717 3366 : translate_col_privs(const Bitmapset *parent_privs,
718 : List *translated_vars)
719 : {
720 3366 : Bitmapset *child_privs = NULL;
721 : bool whole_row;
722 : int attno;
723 : ListCell *lc;
724 :
725 : /* System attributes have the same numbers in all tables */
726 23562 : for (attno = FirstLowInvalidHeapAttributeNumber + 1; attno < 0; attno++)
727 : {
728 20196 : if (bms_is_member(attno - FirstLowInvalidHeapAttributeNumber,
729 : parent_privs))
730 0 : child_privs = bms_add_member(child_privs,
731 : attno - FirstLowInvalidHeapAttributeNumber);
732 : }
733 :
734 : /* Check if parent has whole-row reference */
735 3366 : whole_row = bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber,
736 : parent_privs);
737 :
738 : /* And now translate the regular user attributes, using the vars list */
739 3366 : attno = InvalidAttrNumber;
740 12094 : foreach(lc, translated_vars)
741 : {
742 8728 : Var *var = lfirst_node(Var, lc);
743 :
744 8728 : attno++;
745 8728 : if (var == NULL) /* ignore dropped columns */
746 126 : continue;
747 17204 : if (whole_row ||
748 8602 : bms_is_member(attno - FirstLowInvalidHeapAttributeNumber,
749 : parent_privs))
750 540 : child_privs = bms_add_member(child_privs,
751 540 : var->varattno - FirstLowInvalidHeapAttributeNumber);
752 : }
753 :
754 3366 : return child_privs;
755 : }
756 :
757 : /*
758 : * translate_col_privs_multilevel
759 : * Recursively translates the column numbers contained in 'parent_cols'
760 : * to the column numbers of a descendant relation given by 'rel'
761 : *
762 : * Note that because this is based on translate_col_privs, it will expand
763 : * a whole-row reference into all inherited columns. This is not an issue
764 : * for current usages, but beware.
765 : */
766 : static Bitmapset *
767 38 : translate_col_privs_multilevel(PlannerInfo *root, RelOptInfo *rel,
768 : RelOptInfo *parent_rel,
769 : Bitmapset *parent_cols)
770 : {
771 : AppendRelInfo *appinfo;
772 :
773 : /* Fast path for easy case. */
774 38 : if (parent_cols == NULL)
775 0 : return NULL;
776 :
777 : /* Recurse if immediate parent is not the top parent. */
778 38 : if (rel->parent != parent_rel)
779 : {
780 4 : if (rel->parent)
781 4 : parent_cols = translate_col_privs_multilevel(root, rel->parent,
782 : parent_rel,
783 : parent_cols);
784 : else
785 0 : elog(ERROR, "rel with relid %u is not a child rel", rel->relid);
786 : }
787 :
788 : /* Now translate for this child. */
789 : Assert(root->append_rel_array != NULL);
790 38 : appinfo = root->append_rel_array[rel->relid];
791 : Assert(appinfo != NULL);
792 :
793 38 : return translate_col_privs(parent_cols, appinfo->translated_vars);
794 : }
795 :
796 : /*
797 : * expand_appendrel_subquery
798 : * Add "other rel" RelOptInfos for the children of an appendrel baserel
799 : *
800 : * "rel" is a subquery relation that has the rte->inh flag set, meaning it
801 : * is a UNION ALL subquery that's been flattened into an appendrel, with
802 : * child subqueries listed in root->append_rel_list. We need to build
803 : * a RelOptInfo for each child relation so that we can plan scans on them.
804 : */
805 : static void
806 4644 : expand_appendrel_subquery(PlannerInfo *root, RelOptInfo *rel,
807 : RangeTblEntry *rte, Index rti)
808 : {
809 : ListCell *l;
810 :
811 15940 : foreach(l, root->append_rel_list)
812 : {
813 11296 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
814 11296 : Index childRTindex = appinfo->child_relid;
815 : RangeTblEntry *childrte;
816 : RelOptInfo *childrel;
817 :
818 : /* append_rel_list contains all append rels; ignore others */
819 11296 : if (appinfo->parent_relid != rti)
820 1146 : continue;
821 :
822 : /* find the child RTE, which should already exist */
823 : Assert(childRTindex < root->simple_rel_array_size);
824 10150 : childrte = root->simple_rte_array[childRTindex];
825 : Assert(childrte != NULL);
826 :
827 : /* Build the child RelOptInfo. */
828 10150 : childrel = build_simple_rel(root, childRTindex, rel);
829 :
830 : /* Child may itself be an inherited rel, either table or subquery. */
831 10150 : if (childrte->inh)
832 212 : expand_inherited_rtentry(root, childrel, childrte, childRTindex);
833 : }
834 4644 : }
835 :
836 :
837 : /*
838 : * apply_child_basequals
839 : * Populate childrel's base restriction quals from parent rel's quals,
840 : * translating Vars using appinfo and re-checking for quals which are
841 : * constant-TRUE or constant-FALSE when applied to this child relation.
842 : *
843 : * If any of the resulting clauses evaluate to constant false or NULL, we
844 : * return false and don't apply any quals. Caller should mark the relation as
845 : * a dummy rel in this case, since it doesn't need to be scanned. Constant
846 : * true quals are ignored.
847 : */
848 : bool
849 50690 : apply_child_basequals(PlannerInfo *root, RelOptInfo *parentrel,
850 : RelOptInfo *childrel, RangeTblEntry *childRTE,
851 : AppendRelInfo *appinfo)
852 : {
853 : List *childquals;
854 : Index cq_min_security;
855 : ListCell *lc;
856 :
857 : /*
858 : * The child rel's targetlist might contain non-Var expressions, which
859 : * means that substitution into the quals could produce opportunities for
860 : * const-simplification, and perhaps even pseudoconstant quals. Therefore,
861 : * transform each RestrictInfo separately to see if it reduces to a
862 : * constant or pseudoconstant. (We must process them separately to keep
863 : * track of the security level of each qual.)
864 : */
865 50690 : childquals = NIL;
866 50690 : cq_min_security = UINT_MAX;
867 79686 : foreach(lc, parentrel->baserestrictinfo)
868 : {
869 29086 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
870 : Node *childqual;
871 : ListCell *lc2;
872 :
873 : Assert(IsA(rinfo, RestrictInfo));
874 29086 : childqual = adjust_appendrel_attrs(root,
875 29086 : (Node *) rinfo->clause,
876 : 1, &appinfo);
877 29086 : childqual = eval_const_expressions(root, childqual);
878 : /* check for flat-out constant */
879 29086 : if (childqual && IsA(childqual, Const))
880 : {
881 192 : if (((Const *) childqual)->constisnull ||
882 192 : !DatumGetBool(((Const *) childqual)->constvalue))
883 : {
884 : /* Restriction reduces to constant FALSE or NULL */
885 90 : return false;
886 : }
887 : /* Restriction reduces to constant TRUE, so drop it */
888 102 : continue;
889 : }
890 : /* might have gotten an AND clause, if so flatten it */
891 57800 : foreach(lc2, make_ands_implicit((Expr *) childqual))
892 : {
893 28906 : Node *onecq = (Node *) lfirst(lc2);
894 : bool pseudoconstant;
895 : RestrictInfo *childrinfo;
896 :
897 : /* check for pseudoconstant (no Vars or volatile functions) */
898 28906 : pseudoconstant =
899 28952 : !contain_vars_of_level(onecq, 0) &&
900 46 : !contain_volatile_functions(onecq);
901 28906 : if (pseudoconstant)
902 : {
903 : /* tell createplan.c to check for gating quals */
904 46 : root->hasPseudoConstantQuals = true;
905 : }
906 : /* reconstitute RestrictInfo with appropriate properties */
907 28906 : childrinfo = make_restrictinfo(root,
908 : (Expr *) onecq,
909 28906 : rinfo->is_pushed_down,
910 28906 : rinfo->has_clone,
911 28906 : rinfo->is_clone,
912 : pseudoconstant,
913 : rinfo->security_level,
914 : NULL, NULL, NULL);
915 :
916 : /* Restriction is proven always false */
917 28906 : if (restriction_is_always_false(root, childrinfo))
918 0 : return false;
919 : /* Restriction is proven always true, so drop it */
920 28906 : if (restriction_is_always_true(root, childrinfo))
921 0 : continue;
922 :
923 28906 : childquals = lappend(childquals, childrinfo);
924 : /* track minimum security level among child quals */
925 28906 : cq_min_security = Min(cq_min_security, rinfo->security_level);
926 : }
927 : }
928 :
929 : /*
930 : * In addition to the quals inherited from the parent, we might have
931 : * securityQuals associated with this particular child node. (Currently
932 : * this can only happen in appendrels originating from UNION ALL;
933 : * inheritance child tables don't have their own securityQuals, see
934 : * expand_single_inheritance_child().) Pull any such securityQuals up
935 : * into the baserestrictinfo for the child. This is similar to
936 : * process_security_barrier_quals() for the parent rel, except that we
937 : * can't make any general deductions from such quals, since they don't
938 : * hold for the whole appendrel.
939 : */
940 50600 : if (childRTE->securityQuals)
941 : {
942 12 : Index security_level = 0;
943 :
944 24 : foreach(lc, childRTE->securityQuals)
945 : {
946 12 : List *qualset = (List *) lfirst(lc);
947 : ListCell *lc2;
948 :
949 24 : foreach(lc2, qualset)
950 : {
951 12 : Expr *qual = (Expr *) lfirst(lc2);
952 :
953 : /* not likely that we'd see constants here, so no check */
954 12 : childquals = lappend(childquals,
955 12 : make_restrictinfo(root, qual,
956 : true,
957 : false, false,
958 : false,
959 : security_level,
960 : NULL, NULL, NULL));
961 12 : cq_min_security = Min(cq_min_security, security_level);
962 : }
963 12 : security_level++;
964 : }
965 : Assert(security_level <= root->qual_security_level);
966 : }
967 :
968 : /*
969 : * OK, we've got all the baserestrictinfo quals for this child.
970 : */
971 50600 : childrel->baserestrictinfo = childquals;
972 50600 : childrel->baserestrict_min_security = cq_min_security;
973 :
974 50600 : return true;
975 : }
|