1 /*-------------------------------------------------------------------------
4 * Routines to create the desired plan for processing a query.
5 * Planning is complete, we just need to convert the selected
8 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * src/backend/optimizer/plan/createplan.c
15 *-------------------------------------------------------------------------
22 #include "access/stratnum.h"
23 #include "access/sysattr.h"
24 #include "catalog/pg_class.h"
25 #include "foreign/fdwapi.h"
26 #include "miscadmin.h"
27 #include "nodes/makefuncs.h"
28 #include "nodes/nodeFuncs.h"
29 #include "optimizer/clauses.h"
30 #include "optimizer/cost.h"
31 #include "optimizer/paths.h"
32 #include "optimizer/placeholder.h"
33 #include "optimizer/plancat.h"
34 #include "optimizer/planmain.h"
35 #include "optimizer/planner.h"
36 #include "optimizer/predtest.h"
37 #include "optimizer/prep.h"
38 #include "optimizer/restrictinfo.h"
39 #include "optimizer/subselect.h"
40 #include "optimizer/tlist.h"
41 #include "optimizer/var.h"
42 #include "parser/parse_clause.h"
43 #include "parser/parsetree.h"
44 #include "utils/lsyscache.h"
47 static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path);
48 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path);
49 static List *build_path_tlist(PlannerInfo *root, Path *path);
50 static bool use_physical_tlist(PlannerInfo *root, RelOptInfo *rel);
51 static void disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path);
52 static Plan *create_gating_plan(PlannerInfo *root, Plan *plan, List *quals);
53 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
54 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
55 static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path);
56 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
57 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
58 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
59 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
60 List *tlist, List *scan_clauses);
61 static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
62 List *tlist, List *scan_clauses);
63 static Gather *create_gather_plan(PlannerInfo *root,
64 GatherPath *best_path);
65 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
66 List *tlist, List *scan_clauses, bool indexonly);
67 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
68 BitmapHeapPath *best_path,
69 List *tlist, List *scan_clauses);
70 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
71 List **qual, List **indexqual, List **indexECs);
72 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
73 List *tlist, List *scan_clauses);
74 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
75 List *tlist, List *scan_clauses);
76 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
77 List *tlist, List *scan_clauses);
78 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
79 List *tlist, List *scan_clauses);
80 static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
81 List *tlist, List *scan_clauses);
82 static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
83 List *tlist, List *scan_clauses);
84 static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
85 List *tlist, List *scan_clauses);
86 static CustomScan *create_customscan_plan(PlannerInfo *root,
87 CustomPath *best_path,
88 List *tlist, List *scan_clauses);
89 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
90 Plan *outer_plan, Plan *inner_plan);
91 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
92 Plan *outer_plan, Plan *inner_plan);
93 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
94 Plan *outer_plan, Plan *inner_plan);
95 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
96 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
97 static void process_subquery_nestloop_params(PlannerInfo *root,
98 List *subplan_params);
99 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
100 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
101 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
102 static List *get_switched_clauses(List *clauses, Relids outerrelids);
103 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
104 static void copy_path_costsize(Plan *dest, Path *src);
105 static void copy_plan_costsize(Plan *dest, Plan *src);
106 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
107 static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
108 TableSampleClause *tsc);
109 static Gather *make_gather(List *qptlist, List *qpqual,
110 int nworkers, bool single_copy, Plan *subplan);
111 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
112 Oid indexid, List *indexqual, List *indexqualorig,
113 List *indexorderby, List *indexorderbyorig,
114 List *indexorderbyops,
115 ScanDirection indexscandir);
116 static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
117 Index scanrelid, Oid indexid,
118 List *indexqual, List *indexorderby,
120 ScanDirection indexscandir);
121 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
123 List *indexqualorig);
124 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
127 List *bitmapqualorig,
129 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
131 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
132 Index scanrelid, List *functions, bool funcordinality);
133 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
134 Index scanrelid, List *values_lists);
135 static CteScan *make_ctescan(List *qptlist, List *qpqual,
136 Index scanrelid, int ctePlanId, int cteParam);
137 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
138 Index scanrelid, int wtParam);
139 static BitmapAnd *make_bitmap_and(List *bitmapplans);
140 static BitmapOr *make_bitmap_or(List *bitmapplans);
141 static NestLoop *make_nestloop(List *tlist,
142 List *joinclauses, List *otherclauses, List *nestParams,
143 Plan *lefttree, Plan *righttree,
145 static HashJoin *make_hashjoin(List *tlist,
146 List *joinclauses, List *otherclauses,
148 Plan *lefttree, Plan *righttree,
150 static Hash *make_hash(Plan *lefttree,
152 AttrNumber skewColumn,
155 int32 skewColTypmod);
156 static MergeJoin *make_mergejoin(List *tlist,
157 List *joinclauses, List *otherclauses,
160 Oid *mergecollations,
161 int *mergestrategies,
162 bool *mergenullsfirst,
163 Plan *lefttree, Plan *righttree,
165 static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
166 AttrNumber *sortColIdx, Oid *sortOperators,
167 Oid *collations, bool *nullsFirst,
168 double limit_tuples);
169 static Plan *prepare_sort_from_pathkeys(PlannerInfo *root,
170 Plan *lefttree, List *pathkeys,
172 const AttrNumber *reqColIdx,
173 bool adjust_tlist_in_place,
175 AttrNumber **p_sortColIdx,
176 Oid **p_sortOperators,
178 bool **p_nullsFirst);
179 static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
182 static Material *make_material(Plan *lefttree);
187 * Creates the access plan for a query by recursively processing the
188 * desired tree of pathnodes, starting at the node 'best_path'. For
189 * every pathnode found, we create a corresponding plan node containing
190 * appropriate id, target list, and qualification information.
192 * The tlists and quals in the plan tree are still in planner format,
193 * ie, Vars still correspond to the parser's numbering. This will be
194 * fixed later by setrefs.c.
196 * best_path is the best access path
198 * Returns a Plan tree.
201 create_plan(PlannerInfo *root, Path *best_path)
205 /* plan_params should not be in use in current query level */
206 Assert(root->plan_params == NIL);
208 /* Initialize this module's private workspace in PlannerInfo */
209 root->curOuterRels = NULL;
210 root->curOuterParams = NIL;
212 /* Recursively process the path tree */
213 plan = create_plan_recurse(root, best_path);
215 /* Check we successfully assigned all NestLoopParams to plan nodes */
216 if (root->curOuterParams != NIL)
217 elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
220 * Reset plan_params to ensure param IDs used for nestloop params are not
223 root->plan_params = NIL;
229 * create_plan_recurse
230 * Recursive guts of create_plan().
233 create_plan_recurse(PlannerInfo *root, Path *best_path)
237 switch (best_path->pathtype)
242 case T_IndexOnlyScan:
243 case T_BitmapHeapScan:
249 case T_WorkTableScan:
252 plan = create_scan_plan(root, best_path);
257 plan = create_join_plan(root,
258 (JoinPath *) best_path);
261 plan = create_append_plan(root,
262 (AppendPath *) best_path);
265 plan = create_merge_append_plan(root,
266 (MergeAppendPath *) best_path);
269 plan = (Plan *) create_result_plan(root,
270 (ResultPath *) best_path);
273 plan = (Plan *) create_material_plan(root,
274 (MaterialPath *) best_path);
277 plan = create_unique_plan(root,
278 (UniquePath *) best_path);
281 plan = (Plan *) create_gather_plan(root,
282 (GatherPath *) best_path);
285 elog(ERROR, "unrecognized node type: %d",
286 (int) best_path->pathtype);
287 plan = NULL; /* keep compiler quiet */
296 * Create a scan plan for the parent relation of 'best_path'.
299 create_scan_plan(PlannerInfo *root, Path *best_path)
301 RelOptInfo *rel = best_path->parent;
307 * For table scans, rather than using the relation targetlist (which is
308 * only those Vars actually needed by the query), we prefer to generate a
309 * tlist containing all Vars in order. This will allow the executor to
310 * optimize away projection of the table tuples, if possible. (Note that
311 * planner.c may replace the tlist we generate here, forcing projection to
314 if (use_physical_tlist(root, rel))
316 if (best_path->pathtype == T_IndexOnlyScan)
318 /* For index-only scan, the preferred tlist is the index's */
319 tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
323 tlist = build_physical_tlist(root, rel);
324 /* if fail because of dropped cols, use regular method */
326 tlist = build_path_tlist(root, best_path);
331 tlist = build_path_tlist(root, best_path);
335 * Extract the relevant restriction clauses from the parent relation. The
336 * executor must apply all these restrictions during the scan, except for
337 * pseudoconstants which we'll take care of below.
339 scan_clauses = rel->baserestrictinfo;
342 * If this is a parameterized scan, we also need to enforce all the join
343 * clauses available from the outer relation(s).
345 * For paranoia's sake, don't modify the stored baserestrictinfo list.
347 if (best_path->param_info)
348 scan_clauses = list_concat(list_copy(scan_clauses),
349 best_path->param_info->ppi_clauses);
351 switch (best_path->pathtype)
354 plan = (Plan *) create_seqscan_plan(root,
361 plan = (Plan *) create_samplescan_plan(root,
368 plan = (Plan *) create_indexscan_plan(root,
369 (IndexPath *) best_path,
375 case T_IndexOnlyScan:
376 plan = (Plan *) create_indexscan_plan(root,
377 (IndexPath *) best_path,
383 case T_BitmapHeapScan:
384 plan = (Plan *) create_bitmap_scan_plan(root,
385 (BitmapHeapPath *) best_path,
391 plan = (Plan *) create_tidscan_plan(root,
392 (TidPath *) best_path,
398 plan = (Plan *) create_subqueryscan_plan(root,
405 plan = (Plan *) create_functionscan_plan(root,
412 plan = (Plan *) create_valuesscan_plan(root,
419 plan = (Plan *) create_ctescan_plan(root,
425 case T_WorkTableScan:
426 plan = (Plan *) create_worktablescan_plan(root,
433 plan = (Plan *) create_foreignscan_plan(root,
434 (ForeignPath *) best_path,
440 plan = (Plan *) create_customscan_plan(root,
441 (CustomPath *) best_path,
447 elog(ERROR, "unrecognized node type: %d",
448 (int) best_path->pathtype);
449 plan = NULL; /* keep compiler quiet */
454 * If there are any pseudoconstant clauses attached to this node, insert a
455 * gating Result node that evaluates the pseudoconstants as one-time
458 if (root->hasPseudoConstantQuals)
459 plan = create_gating_plan(root, plan, scan_clauses);
465 * Build a target list (ie, a list of TargetEntry) for the Path's output.
468 build_path_tlist(PlannerInfo *root, Path *path)
470 RelOptInfo *rel = path->parent;
475 foreach(v, rel->reltargetlist)
477 /* Do we really need to copy here? Not sure */
478 Node *node = (Node *) copyObject(lfirst(v));
481 * If it's a parameterized path, there might be lateral references in
482 * the tlist, which need to be replaced with Params. There's no need
483 * to remake the TargetEntry nodes, so apply this to each list item
486 if (path->param_info)
487 node = replace_nestloop_params(root, node);
489 tlist = lappend(tlist, makeTargetEntry((Expr *) node,
500 * Decide whether to use a tlist matching relation structure,
501 * rather than only those Vars actually referenced.
504 use_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
510 * We can do this for real relation scans, subquery scans, function scans,
511 * values scans, and CTE scans (but not for, eg, joins).
513 if (rel->rtekind != RTE_RELATION &&
514 rel->rtekind != RTE_SUBQUERY &&
515 rel->rtekind != RTE_FUNCTION &&
516 rel->rtekind != RTE_VALUES &&
517 rel->rtekind != RTE_CTE)
521 * Can't do it with inheritance cases either (mainly because Append
524 if (rel->reloptkind != RELOPT_BASEREL)
528 * Can't do it if any system columns or whole-row Vars are requested.
529 * (This could possibly be fixed but would take some fragile assumptions
530 * in setrefs.c, I think.)
532 for (i = rel->min_attr; i <= 0; i++)
534 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
539 * Can't do it if the rel is required to emit any placeholder expressions,
542 foreach(lc, root->placeholder_list)
544 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
546 if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
547 bms_is_subset(phinfo->ph_eval_at, rel->relids))
555 * disuse_physical_tlist
556 * Switch a plan node back to emitting only Vars actually referenced.
558 * If the plan node immediately above a scan would prefer to get only
559 * needed Vars and not a physical tlist, it must call this routine to
560 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
561 * and Material nodes want this, so they don't have to store useless columns.
564 disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path)
566 /* Only need to undo it for path types handled by create_scan_plan() */
567 switch (path->pathtype)
572 case T_IndexOnlyScan:
573 case T_BitmapHeapScan:
579 case T_WorkTableScan:
582 plan->targetlist = build_path_tlist(root, path);
591 * Deal with pseudoconstant qual clauses
593 * If the node's quals list includes any pseudoconstant quals, put them
594 * into a gating Result node atop the already-built plan. Otherwise,
595 * return the plan as-is.
597 * Note that we don't change cost or size estimates when doing gating.
598 * The costs of qual eval were already folded into the plan's startup cost.
599 * Leaving the size alone amounts to assuming that the gating qual will
600 * succeed, which is the conservative estimate for planning upper queries.
601 * We certainly don't want to assume the output size is zero (unless the
602 * gating qual is actually constant FALSE, and that case is dealt with in
603 * clausesel.c). Interpolating between the two cases is silly, because
604 * it doesn't reflect what will really happen at runtime, and besides which
605 * in most cases we have only a very bad idea of the probability of the gating
609 create_gating_plan(PlannerInfo *root, Plan *plan, List *quals)
611 List *pseudoconstants;
613 /* Sort into desirable execution order while still in RestrictInfo form */
614 quals = order_qual_clauses(root, quals);
616 /* Pull out any pseudoconstant quals from the RestrictInfo list */
617 pseudoconstants = extract_actual_clauses(quals, true);
619 if (!pseudoconstants)
622 return (Plan *) make_result(root,
624 (Node *) pseudoconstants,
630 * Create a join plan for 'best_path' and (recursively) plans for its
631 * inner and outer paths.
634 create_join_plan(PlannerInfo *root, JoinPath *best_path)
639 Relids saveOuterRels = root->curOuterRels;
641 outer_plan = create_plan_recurse(root, best_path->outerjoinpath);
643 /* For a nestloop, include outer relids in curOuterRels for inner side */
644 if (best_path->path.pathtype == T_NestLoop)
645 root->curOuterRels = bms_union(root->curOuterRels,
646 best_path->outerjoinpath->parent->relids);
648 inner_plan = create_plan_recurse(root, best_path->innerjoinpath);
650 switch (best_path->path.pathtype)
653 plan = (Plan *) create_mergejoin_plan(root,
654 (MergePath *) best_path,
659 plan = (Plan *) create_hashjoin_plan(root,
660 (HashPath *) best_path,
665 /* Restore curOuterRels */
666 bms_free(root->curOuterRels);
667 root->curOuterRels = saveOuterRels;
669 plan = (Plan *) create_nestloop_plan(root,
670 (NestPath *) best_path,
675 elog(ERROR, "unrecognized node type: %d",
676 (int) best_path->path.pathtype);
677 plan = NULL; /* keep compiler quiet */
682 * If there are any pseudoconstant clauses attached to this node, insert a
683 * gating Result node that evaluates the pseudoconstants as one-time
686 if (root->hasPseudoConstantQuals)
687 plan = create_gating_plan(root, plan, best_path->joinrestrictinfo);
692 * * Expensive function pullups may have pulled local predicates * into
693 * this path node. Put them in the qpqual of the plan node. * JMH,
696 if (get_loc_restrictinfo(best_path) != NIL)
697 set_qpqual((Plan) plan,
698 list_concat(get_qpqual((Plan) plan),
699 get_actual_clauses(get_loc_restrictinfo(best_path))));
707 * Create an Append plan for 'best_path' and (recursively) plans
710 * Returns a Plan node.
713 create_append_plan(PlannerInfo *root, AppendPath *best_path)
716 List *tlist = build_path_tlist(root, &best_path->path);
717 List *subplans = NIL;
721 * The subpaths list could be empty, if every child was proven empty by
722 * constraint exclusion. In that case generate a dummy plan that returns
725 * Note that an AppendPath with no members is also generated in certain
726 * cases where there was no appending construct at all, but we know the
727 * relation is empty (see set_dummy_rel_pathlist).
729 if (best_path->subpaths == NIL)
731 /* Generate a Result plan with constant-FALSE gating qual */
732 return (Plan *) make_result(root,
734 (Node *) list_make1(makeBoolConst(false,
739 /* Build the plan for each child */
740 foreach(subpaths, best_path->subpaths)
742 Path *subpath = (Path *) lfirst(subpaths);
744 subplans = lappend(subplans, create_plan_recurse(root, subpath));
748 * XXX ideally, if there's just one child, we'd not bother to generate an
749 * Append node but just return the single child. At the moment this does
750 * not work because the varno of the child scan plan won't match the
751 * parent-rel Vars it'll be asked to emit.
754 plan = make_append(subplans, tlist);
756 return (Plan *) plan;
760 * create_merge_append_plan
761 * Create a MergeAppend plan for 'best_path' and (recursively) plans
764 * Returns a Plan node.
767 create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
769 MergeAppend *node = makeNode(MergeAppend);
770 Plan *plan = &node->plan;
771 List *tlist = build_path_tlist(root, &best_path->path);
772 List *pathkeys = best_path->path.pathkeys;
773 List *subplans = NIL;
777 * We don't have the actual creation of the MergeAppend node split out
778 * into a separate make_xxx function. This is because we want to run
779 * prepare_sort_from_pathkeys on it before we do so on the individual
780 * child plans, to make cross-checking the sort info easier.
782 copy_path_costsize(plan, (Path *) best_path);
783 plan->targetlist = tlist;
785 plan->lefttree = NULL;
786 plan->righttree = NULL;
788 /* Compute sort column info, and adjust MergeAppend's tlist as needed */
789 (void) prepare_sort_from_pathkeys(root, plan, pathkeys,
790 best_path->path.parent->relids,
795 &node->sortOperators,
800 * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
801 * even to subplans that don't need an explicit sort, to make sure they
802 * are returning the same sort key columns the MergeAppend expects.
804 foreach(subpaths, best_path->subpaths)
806 Path *subpath = (Path *) lfirst(subpaths);
809 AttrNumber *sortColIdx;
814 /* Build the child plan */
815 subplan = create_plan_recurse(root, subpath);
817 /* Compute sort column info, and adjust subplan's tlist as needed */
818 subplan = prepare_sort_from_pathkeys(root, subplan, pathkeys,
819 subpath->parent->relids,
829 * Check that we got the same sort key information. We just Assert
830 * that the sortops match, since those depend only on the pathkeys;
831 * but it seems like a good idea to check the sort column numbers
832 * explicitly, to ensure the tlists really do match up.
834 Assert(numsortkeys == node->numCols);
835 if (memcmp(sortColIdx, node->sortColIdx,
836 numsortkeys * sizeof(AttrNumber)) != 0)
837 elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
838 Assert(memcmp(sortOperators, node->sortOperators,
839 numsortkeys * sizeof(Oid)) == 0);
840 Assert(memcmp(collations, node->collations,
841 numsortkeys * sizeof(Oid)) == 0);
842 Assert(memcmp(nullsFirst, node->nullsFirst,
843 numsortkeys * sizeof(bool)) == 0);
845 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
846 if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
847 subplan = (Plan *) make_sort(root, subplan, numsortkeys,
848 sortColIdx, sortOperators,
849 collations, nullsFirst,
850 best_path->limit_tuples);
852 subplans = lappend(subplans, subplan);
855 node->mergeplans = subplans;
857 return (Plan *) node;
862 * Create a Result plan for 'best_path'.
863 * This is only used for the case of a query with an empty jointree.
865 * Returns a Plan node.
868 create_result_plan(PlannerInfo *root, ResultPath *best_path)
873 /* The tlist will be installed later, since we have no RelOptInfo */
874 Assert(best_path->path.parent == NULL);
877 /* best_path->quals is just bare clauses */
879 quals = order_qual_clauses(root, best_path->quals);
881 return make_result(root, tlist, (Node *) quals, NULL);
885 * create_material_plan
886 * Create a Material plan for 'best_path' and (recursively) plans
889 * Returns a Plan node.
892 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
897 subplan = create_plan_recurse(root, best_path->subpath);
899 /* We don't want any excess columns in the materialized tuples */
900 disuse_physical_tlist(root, subplan, best_path->subpath);
902 plan = make_material(subplan);
904 copy_path_costsize(&plan->plan, (Path *) best_path);
911 * Create a Unique plan for 'best_path' and (recursively) plans
914 * Returns a Plan node.
917 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
927 AttrNumber *groupColIdx;
931 subplan = create_plan_recurse(root, best_path->subpath);
933 /* Done if we don't need to do any actual unique-ifying */
934 if (best_path->umethod == UNIQUE_PATH_NOOP)
938 * As constructed, the subplan has a "flat" tlist containing just the Vars
939 * needed here and at upper levels. The values we are supposed to
940 * unique-ify may be expressions in these variables. We have to add any
941 * such expressions to the subplan's tlist.
943 * The subplan may have a "physical" tlist if it is a simple scan plan. If
944 * we're going to sort, this should be reduced to the regular tlist, so
945 * that we don't sort more data than we need to. For hashing, the tlist
946 * should be left as-is if we don't need to add any expressions; but if we
947 * do have to add expressions, then a projection step will be needed at
948 * runtime anyway, so we may as well remove unneeded items. Therefore
949 * newtlist starts from build_path_tlist() not just a copy of the
950 * subplan's tlist; and we don't install it into the subplan unless we are
951 * sorting or stuff has to be added.
953 in_operators = best_path->in_operators;
954 uniq_exprs = best_path->uniq_exprs;
956 /* initialize modified subplan tlist as just the "required" vars */
957 newtlist = build_path_tlist(root, &best_path->path);
958 nextresno = list_length(newtlist) + 1;
961 foreach(l, uniq_exprs)
963 Node *uniqexpr = lfirst(l);
966 tle = tlist_member(uniqexpr, newtlist);
969 tle = makeTargetEntry((Expr *) uniqexpr,
973 newtlist = lappend(newtlist, tle);
979 if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
982 * If the top plan node can't do projections and its existing target
983 * list isn't already what we need, we need to add a Result node to
986 if (!is_projection_capable_plan(subplan) &&
987 !tlist_same_exprs(newtlist, subplan->targetlist))
988 subplan = (Plan *) make_result(root, newtlist, NULL, subplan);
990 subplan->targetlist = newtlist;
994 * Build control information showing which subplan output columns are to
995 * be examined by the grouping step. Unfortunately we can't merge this
996 * with the previous loop, since we didn't then know which version of the
997 * subplan tlist we'd end up using.
999 newtlist = subplan->targetlist;
1000 numGroupCols = list_length(uniq_exprs);
1001 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
1004 foreach(l, uniq_exprs)
1006 Node *uniqexpr = lfirst(l);
1009 tle = tlist_member(uniqexpr, newtlist);
1010 if (!tle) /* shouldn't happen */
1011 elog(ERROR, "failed to find unique expression in subplan tlist");
1012 groupColIdx[groupColPos++] = tle->resno;
1015 if (best_path->umethod == UNIQUE_PATH_HASH)
1018 Oid *groupOperators;
1020 numGroups = (long) Min(best_path->path.rows, (double) LONG_MAX);
1023 * Get the hashable equality operators for the Agg node to use.
1024 * Normally these are the same as the IN clause operators, but if
1025 * those are cross-type operators then the equality operators are the
1026 * ones for the IN clause operators' RHS datatype.
1028 groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
1030 foreach(l, in_operators)
1032 Oid in_oper = lfirst_oid(l);
1035 if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
1036 elog(ERROR, "could not find compatible hash operator for operator %u",
1038 groupOperators[groupColPos++] = eq_oper;
1042 * Since the Agg node is going to project anyway, we can give it the
1043 * minimum output tlist, without any stuff we might have added to the
1046 plan = (Plan *) make_agg(root,
1047 build_path_tlist(root, &best_path->path),
1060 List *sortList = NIL;
1062 /* Create an ORDER BY list to sort the input compatibly */
1064 foreach(l, in_operators)
1066 Oid in_oper = lfirst_oid(l);
1070 SortGroupClause *sortcl;
1072 sortop = get_ordering_op_for_equality_op(in_oper, false);
1073 if (!OidIsValid(sortop)) /* shouldn't happen */
1074 elog(ERROR, "could not find ordering operator for equality operator %u",
1078 * The Unique node will need equality operators. Normally these
1079 * are the same as the IN clause operators, but if those are
1080 * cross-type operators then the equality operators are the ones
1081 * for the IN clause operators' RHS datatype.
1083 eqop = get_equality_op_for_ordering_op(sortop, NULL);
1084 if (!OidIsValid(eqop)) /* shouldn't happen */
1085 elog(ERROR, "could not find equality operator for ordering operator %u",
1088 tle = get_tle_by_resno(subplan->targetlist,
1089 groupColIdx[groupColPos]);
1090 Assert(tle != NULL);
1092 sortcl = makeNode(SortGroupClause);
1093 sortcl->tleSortGroupRef = assignSortGroupRef(tle,
1094 subplan->targetlist);
1095 sortcl->eqop = eqop;
1096 sortcl->sortop = sortop;
1097 sortcl->nulls_first = false;
1098 sortcl->hashable = false; /* no need to make this accurate */
1099 sortList = lappend(sortList, sortcl);
1102 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
1103 plan = (Plan *) make_unique(plan, sortList);
1106 /* Adjust output size estimate (other fields should be OK already) */
1107 plan->plan_rows = best_path->path.rows;
1113 * create_gather_plan
1115 * Create a Gather plan for 'best_path' and (recursively) plans
1119 create_gather_plan(PlannerInfo *root, GatherPath *best_path)
1121 Gather *gather_plan;
1124 subplan = create_plan_recurse(root, best_path->subpath);
1126 gather_plan = make_gather(subplan->targetlist,
1128 best_path->num_workers,
1129 best_path->single_copy,
1132 copy_path_costsize(&gather_plan->plan, &best_path->path);
1134 /* use parallel mode for parallel plans. */
1135 root->glob->parallelModeNeeded = true;
1141 /*****************************************************************************
1143 * BASE-RELATION SCAN METHODS
1145 *****************************************************************************/
1149 * create_seqscan_plan
1150 * Returns a seqscan plan for the base relation scanned by 'best_path'
1151 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1154 create_seqscan_plan(PlannerInfo *root, Path *best_path,
1155 List *tlist, List *scan_clauses)
1158 Index scan_relid = best_path->parent->relid;
1160 /* it should be a base rel... */
1161 Assert(scan_relid > 0);
1162 Assert(best_path->parent->rtekind == RTE_RELATION);
1164 /* Sort clauses into best execution order */
1165 scan_clauses = order_qual_clauses(root, scan_clauses);
1167 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1168 scan_clauses = extract_actual_clauses(scan_clauses, false);
1170 /* Replace any outer-relation variables with nestloop params */
1171 if (best_path->param_info)
1173 scan_clauses = (List *)
1174 replace_nestloop_params(root, (Node *) scan_clauses);
1177 scan_plan = make_seqscan(tlist,
1181 copy_path_costsize(&scan_plan->plan, best_path);
1187 * create_samplescan_plan
1188 * Returns a samplescan plan for the base relation scanned by 'best_path'
1189 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1192 create_samplescan_plan(PlannerInfo *root, Path *best_path,
1193 List *tlist, List *scan_clauses)
1195 SampleScan *scan_plan;
1196 Index scan_relid = best_path->parent->relid;
1198 TableSampleClause *tsc;
1200 /* it should be a base rel with a tablesample clause... */
1201 Assert(scan_relid > 0);
1202 rte = planner_rt_fetch(scan_relid, root);
1203 Assert(rte->rtekind == RTE_RELATION);
1204 tsc = rte->tablesample;
1205 Assert(tsc != NULL);
1207 /* Sort clauses into best execution order */
1208 scan_clauses = order_qual_clauses(root, scan_clauses);
1210 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1211 scan_clauses = extract_actual_clauses(scan_clauses, false);
1213 /* Replace any outer-relation variables with nestloop params */
1214 if (best_path->param_info)
1216 scan_clauses = (List *)
1217 replace_nestloop_params(root, (Node *) scan_clauses);
1218 tsc = (TableSampleClause *)
1219 replace_nestloop_params(root, (Node *) tsc);
1222 scan_plan = make_samplescan(tlist,
1227 copy_path_costsize(&scan_plan->scan.plan, best_path);
1233 * create_indexscan_plan
1234 * Returns an indexscan plan for the base relation scanned by 'best_path'
1235 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1237 * We use this for both plain IndexScans and IndexOnlyScans, because the
1238 * qual preprocessing work is the same for both. Note that the caller tells
1239 * us which to build --- we don't look at best_path->path.pathtype, because
1240 * create_bitmap_subplan needs to be able to override the prior decision.
1243 create_indexscan_plan(PlannerInfo *root,
1244 IndexPath *best_path,
1250 List *indexquals = best_path->indexquals;
1251 List *indexorderbys = best_path->indexorderbys;
1252 Index baserelid = best_path->path.parent->relid;
1253 Oid indexoid = best_path->indexinfo->indexoid;
1255 List *stripped_indexquals;
1256 List *fixed_indexquals;
1257 List *fixed_indexorderbys;
1258 List *indexorderbyops = NIL;
1261 /* it should be a base rel... */
1262 Assert(baserelid > 0);
1263 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1266 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
1267 * executor as indexqualorig
1269 stripped_indexquals = get_actual_clauses(indexquals);
1272 * The executor needs a copy with the indexkey on the left of each clause
1273 * and with index Vars substituted for table ones.
1275 fixed_indexquals = fix_indexqual_references(root, best_path);
1278 * Likewise fix up index attr references in the ORDER BY expressions.
1280 fixed_indexorderbys = fix_indexorderby_references(root, best_path);
1283 * The qpqual list must contain all restrictions not automatically handled
1284 * by the index, other than pseudoconstant clauses which will be handled
1285 * by a separate gating plan node. All the predicates in the indexquals
1286 * will be checked (either by the index itself, or by nodeIndexscan.c),
1287 * but if there are any "special" operators involved then they must be
1288 * included in qpqual. The upshot is that qpqual must contain
1289 * scan_clauses minus whatever appears in indexquals.
1291 * In normal cases simple pointer equality checks will be enough to spot
1292 * duplicate RestrictInfos, so we try that first.
1294 * Another common case is that a scan_clauses entry is generated from the
1295 * same EquivalenceClass as some indexqual, and is therefore redundant
1296 * with it, though not equal. (This happens when indxpath.c prefers a
1297 * different derived equality than what generate_join_implied_equalities
1298 * picked for a parameterized scan's ppi_clauses.)
1300 * In some situations (particularly with OR'd index conditions) we may
1301 * have scan_clauses that are not equal to, but are logically implied by,
1302 * the index quals; so we also try a predicate_implied_by() check to see
1303 * if we can discard quals that way. (predicate_implied_by assumes its
1304 * first input contains only immutable functions, so we have to check
1307 * We can also discard quals that are implied by a partial index's
1308 * predicate, but only in a plain SELECT; when scanning a target relation
1309 * of UPDATE/DELETE/SELECT FOR UPDATE, we must leave such quals in the
1310 * plan so that they'll be properly rechecked by EvalPlanQual testing.
1312 * Note: if you change this bit of code you should also look at
1313 * extract_nonindex_conditions() in costsize.c.
1316 foreach(l, scan_clauses)
1318 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1320 Assert(IsA(rinfo, RestrictInfo));
1321 if (rinfo->pseudoconstant)
1322 continue; /* we may drop pseudoconstants here */
1323 if (list_member_ptr(indexquals, rinfo))
1324 continue; /* simple duplicate */
1325 if (is_redundant_derived_clause(rinfo, indexquals))
1326 continue; /* derived from same EquivalenceClass */
1327 if (!contain_mutable_functions((Node *) rinfo->clause))
1329 List *clausel = list_make1(rinfo->clause);
1331 if (predicate_implied_by(clausel, indexquals))
1332 continue; /* provably implied by indexquals */
1333 if (best_path->indexinfo->indpred)
1335 if (baserelid != root->parse->resultRelation &&
1336 get_plan_rowmark(root->rowMarks, baserelid) == NULL)
1337 if (predicate_implied_by(clausel,
1338 best_path->indexinfo->indpred))
1339 continue; /* implied by index predicate */
1342 qpqual = lappend(qpqual, rinfo);
1345 /* Sort clauses into best execution order */
1346 qpqual = order_qual_clauses(root, qpqual);
1348 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1349 qpqual = extract_actual_clauses(qpqual, false);
1352 * We have to replace any outer-relation variables with nestloop params in
1353 * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
1354 * annoying to have to do this separately from the processing in
1355 * fix_indexqual_references --- rethink this when generalizing the inner
1356 * indexscan support. But note we can't really do this earlier because
1357 * it'd break the comparisons to predicates above ... (or would it? Those
1358 * wouldn't have outer refs)
1360 if (best_path->path.param_info)
1362 stripped_indexquals = (List *)
1363 replace_nestloop_params(root, (Node *) stripped_indexquals);
1365 replace_nestloop_params(root, (Node *) qpqual);
1366 indexorderbys = (List *)
1367 replace_nestloop_params(root, (Node *) indexorderbys);
1371 * If there are ORDER BY expressions, look up the sort operators for their
1376 ListCell *pathkeyCell,
1380 * PathKey contains OID of the btree opfamily we're sorting by, but
1381 * that's not quite enough because we need the expression's datatype
1382 * to look up the sort operator in the operator family.
1384 Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
1385 forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
1387 PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
1388 Node *expr = (Node *) lfirst(exprCell);
1389 Oid exprtype = exprType(expr);
1392 /* Get sort operator from opfamily */
1393 sortop = get_opfamily_member(pathkey->pk_opfamily,
1396 pathkey->pk_strategy);
1397 if (!OidIsValid(sortop))
1398 elog(ERROR, "failed to find sort operator for ORDER BY expression");
1399 indexorderbyops = lappend_oid(indexorderbyops, sortop);
1403 /* Finally ready to build the plan node */
1405 scan_plan = (Scan *) make_indexonlyscan(tlist,
1410 fixed_indexorderbys,
1411 best_path->indexinfo->indextlist,
1412 best_path->indexscandir);
1414 scan_plan = (Scan *) make_indexscan(tlist,
1419 stripped_indexquals,
1420 fixed_indexorderbys,
1423 best_path->indexscandir);
1425 copy_path_costsize(&scan_plan->plan, &best_path->path);
1431 * create_bitmap_scan_plan
1432 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
1433 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1435 static BitmapHeapScan *
1436 create_bitmap_scan_plan(PlannerInfo *root,
1437 BitmapHeapPath *best_path,
1441 Index baserelid = best_path->path.parent->relid;
1442 Plan *bitmapqualplan;
1443 List *bitmapqualorig;
1448 BitmapHeapScan *scan_plan;
1450 /* it should be a base rel... */
1451 Assert(baserelid > 0);
1452 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1454 /* Process the bitmapqual tree into a Plan tree and qual lists */
1455 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
1456 &bitmapqualorig, &indexquals,
1460 * The qpqual list must contain all restrictions not automatically handled
1461 * by the index, other than pseudoconstant clauses which will be handled
1462 * by a separate gating plan node. All the predicates in the indexquals
1463 * will be checked (either by the index itself, or by
1464 * nodeBitmapHeapscan.c), but if there are any "special" operators
1465 * involved then they must be added to qpqual. The upshot is that qpqual
1466 * must contain scan_clauses minus whatever appears in indexquals.
1468 * This loop is similar to the comparable code in create_indexscan_plan(),
1469 * but with some differences because it has to compare the scan clauses to
1470 * stripped (no RestrictInfos) indexquals. See comments there for more
1473 * In normal cases simple equal() checks will be enough to spot duplicate
1474 * clauses, so we try that first. We next see if the scan clause is
1475 * redundant with any top-level indexqual by virtue of being generated
1476 * from the same EC. After that, try predicate_implied_by().
1478 * Unlike create_indexscan_plan(), we need take no special thought here
1479 * for partial index predicates; this is because the predicate conditions
1480 * are already listed in bitmapqualorig and indexquals. Bitmap scans have
1481 * to do it that way because predicate conditions need to be rechecked if
1482 * the scan becomes lossy, so they have to be included in bitmapqualorig.
1485 foreach(l, scan_clauses)
1487 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1488 Node *clause = (Node *) rinfo->clause;
1490 Assert(IsA(rinfo, RestrictInfo));
1491 if (rinfo->pseudoconstant)
1492 continue; /* we may drop pseudoconstants here */
1493 if (list_member(indexquals, clause))
1494 continue; /* simple duplicate */
1495 if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
1496 continue; /* derived from same EquivalenceClass */
1497 if (!contain_mutable_functions(clause))
1499 List *clausel = list_make1(clause);
1501 if (predicate_implied_by(clausel, indexquals))
1502 continue; /* provably implied by indexquals */
1504 qpqual = lappend(qpqual, rinfo);
1507 /* Sort clauses into best execution order */
1508 qpqual = order_qual_clauses(root, qpqual);
1510 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1511 qpqual = extract_actual_clauses(qpqual, false);
1514 * When dealing with special operators, we will at this point have
1515 * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
1516 * 'em from bitmapqualorig, since there's no point in making the tests
1519 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
1522 * We have to replace any outer-relation variables with nestloop params in
1523 * the qpqual and bitmapqualorig expressions. (This was already done for
1524 * expressions attached to plan nodes in the bitmapqualplan tree.)
1526 if (best_path->path.param_info)
1529 replace_nestloop_params(root, (Node *) qpqual);
1530 bitmapqualorig = (List *)
1531 replace_nestloop_params(root, (Node *) bitmapqualorig);
1534 /* Finally ready to build the plan node */
1535 scan_plan = make_bitmap_heapscan(tlist,
1541 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1547 * Given a bitmapqual tree, generate the Plan tree that implements it
1549 * As byproducts, we also return in *qual and *indexqual the qual lists
1550 * (in implicit-AND form, without RestrictInfos) describing the original index
1551 * conditions and the generated indexqual conditions. (These are the same in
1552 * simple cases, but when special index operators are involved, the former
1553 * list includes the special conditions while the latter includes the actual
1554 * indexable conditions derived from them.) Both lists include partial-index
1555 * predicates, because we have to recheck predicates as well as index
1556 * conditions if the bitmap scan becomes lossy.
1558 * In addition, we return a list of EquivalenceClass pointers for all the
1559 * top-level indexquals that were possibly-redundantly derived from ECs.
1560 * This allows removal of scan_clauses that are redundant with such quals.
1561 * (We do not attempt to detect such redundancies for quals that are within
1562 * OR subtrees. This could be done in a less hacky way if we returned the
1563 * indexquals in RestrictInfo form, but that would be slower and still pretty
1564 * messy, since we'd have to build new RestrictInfos in many cases.)
1567 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
1568 List **qual, List **indexqual, List **indexECs)
1572 if (IsA(bitmapqual, BitmapAndPath))
1574 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1575 List *subplans = NIL;
1576 List *subquals = NIL;
1577 List *subindexquals = NIL;
1578 List *subindexECs = NIL;
1582 * There may well be redundant quals among the subplans, since a
1583 * top-level WHERE qual might have gotten used to form several
1584 * different index quals. We don't try exceedingly hard to eliminate
1585 * redundancies, but we do eliminate obvious duplicates by using
1586 * list_concat_unique.
1588 foreach(l, apath->bitmapquals)
1595 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1596 &subqual, &subindexqual,
1598 subplans = lappend(subplans, subplan);
1599 subquals = list_concat_unique(subquals, subqual);
1600 subindexquals = list_concat_unique(subindexquals, subindexqual);
1601 /* Duplicates in indexECs aren't worth getting rid of */
1602 subindexECs = list_concat(subindexECs, subindexEC);
1604 plan = (Plan *) make_bitmap_and(subplans);
1605 plan->startup_cost = apath->path.startup_cost;
1606 plan->total_cost = apath->path.total_cost;
1608 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1609 plan->plan_width = 0; /* meaningless */
1611 *indexqual = subindexquals;
1612 *indexECs = subindexECs;
1614 else if (IsA(bitmapqual, BitmapOrPath))
1616 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1617 List *subplans = NIL;
1618 List *subquals = NIL;
1619 List *subindexquals = NIL;
1620 bool const_true_subqual = false;
1621 bool const_true_subindexqual = false;
1625 * Here, we only detect qual-free subplans. A qual-free subplan would
1626 * cause us to generate "... OR true ..." which we may as well reduce
1627 * to just "true". We do not try to eliminate redundant subclauses
1628 * because (a) it's not as likely as in the AND case, and (b) we might
1629 * well be working with hundreds or even thousands of OR conditions,
1630 * perhaps from a long IN list. The performance of list_append_unique
1631 * would be unacceptable.
1633 foreach(l, opath->bitmapquals)
1640 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1641 &subqual, &subindexqual,
1643 subplans = lappend(subplans, subplan);
1645 const_true_subqual = true;
1646 else if (!const_true_subqual)
1647 subquals = lappend(subquals,
1648 make_ands_explicit(subqual));
1649 if (subindexqual == NIL)
1650 const_true_subindexqual = true;
1651 else if (!const_true_subindexqual)
1652 subindexquals = lappend(subindexquals,
1653 make_ands_explicit(subindexqual));
1657 * In the presence of ScalarArrayOpExpr quals, we might have built
1658 * BitmapOrPaths with just one subpath; don't add an OR step.
1660 if (list_length(subplans) == 1)
1662 plan = (Plan *) linitial(subplans);
1666 plan = (Plan *) make_bitmap_or(subplans);
1667 plan->startup_cost = opath->path.startup_cost;
1668 plan->total_cost = opath->path.total_cost;
1670 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1671 plan->plan_width = 0; /* meaningless */
1675 * If there were constant-TRUE subquals, the OR reduces to constant
1676 * TRUE. Also, avoid generating one-element ORs, which could happen
1677 * due to redundancy elimination or ScalarArrayOpExpr quals.
1679 if (const_true_subqual)
1681 else if (list_length(subquals) <= 1)
1684 *qual = list_make1(make_orclause(subquals));
1685 if (const_true_subindexqual)
1687 else if (list_length(subindexquals) <= 1)
1688 *indexqual = subindexquals;
1690 *indexqual = list_make1(make_orclause(subindexquals));
1693 else if (IsA(bitmapqual, IndexPath))
1695 IndexPath *ipath = (IndexPath *) bitmapqual;
1700 /* Use the regular indexscan plan build machinery... */
1701 iscan = (IndexScan *) create_indexscan_plan(root, ipath,
1703 Assert(IsA(iscan, IndexScan));
1704 /* then convert to a bitmap indexscan */
1705 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1708 iscan->indexqualorig);
1709 plan->startup_cost = 0.0;
1710 plan->total_cost = ipath->indextotalcost;
1712 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1713 plan->plan_width = 0; /* meaningless */
1714 *qual = get_actual_clauses(ipath->indexclauses);
1715 *indexqual = get_actual_clauses(ipath->indexquals);
1716 foreach(l, ipath->indexinfo->indpred)
1718 Expr *pred = (Expr *) lfirst(l);
1721 * We know that the index predicate must have been implied by the
1722 * query condition as a whole, but it may or may not be implied by
1723 * the conditions that got pushed into the bitmapqual. Avoid
1724 * generating redundant conditions.
1726 if (!predicate_implied_by(list_make1(pred), ipath->indexclauses))
1728 *qual = lappend(*qual, pred);
1729 *indexqual = lappend(*indexqual, pred);
1733 foreach(l, ipath->indexquals)
1735 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1737 if (rinfo->parent_ec)
1738 subindexECs = lappend(subindexECs, rinfo->parent_ec);
1740 *indexECs = subindexECs;
1744 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1745 plan = NULL; /* keep compiler quiet */
1752 * create_tidscan_plan
1753 * Returns a tidscan plan for the base relation scanned by 'best_path'
1754 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1757 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1758 List *tlist, List *scan_clauses)
1761 Index scan_relid = best_path->path.parent->relid;
1762 List *tidquals = best_path->tidquals;
1765 /* it should be a base rel... */
1766 Assert(scan_relid > 0);
1767 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1769 /* Sort clauses into best execution order */
1770 scan_clauses = order_qual_clauses(root, scan_clauses);
1772 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1773 scan_clauses = extract_actual_clauses(scan_clauses, false);
1775 /* Replace any outer-relation variables with nestloop params */
1776 if (best_path->path.param_info)
1779 replace_nestloop_params(root, (Node *) tidquals);
1780 scan_clauses = (List *)
1781 replace_nestloop_params(root, (Node *) scan_clauses);
1785 * Remove any clauses that are TID quals. This is a bit tricky since the
1786 * tidquals list has implicit OR semantics.
1788 ortidquals = tidquals;
1789 if (list_length(ortidquals) > 1)
1790 ortidquals = list_make1(make_orclause(ortidquals));
1791 scan_clauses = list_difference(scan_clauses, ortidquals);
1793 scan_plan = make_tidscan(tlist,
1798 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1804 * create_subqueryscan_plan
1805 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1806 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1808 static SubqueryScan *
1809 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1810 List *tlist, List *scan_clauses)
1812 SubqueryScan *scan_plan;
1813 Index scan_relid = best_path->parent->relid;
1815 /* it should be a subquery base rel... */
1816 Assert(scan_relid > 0);
1817 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1819 /* Sort clauses into best execution order */
1820 scan_clauses = order_qual_clauses(root, scan_clauses);
1822 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1823 scan_clauses = extract_actual_clauses(scan_clauses, false);
1825 /* Replace any outer-relation variables with nestloop params */
1826 if (best_path->param_info)
1828 scan_clauses = (List *)
1829 replace_nestloop_params(root, (Node *) scan_clauses);
1830 process_subquery_nestloop_params(root,
1831 best_path->parent->subplan_params);
1834 scan_plan = make_subqueryscan(tlist,
1837 best_path->parent->subplan);
1839 copy_path_costsize(&scan_plan->scan.plan, best_path);
1845 * create_functionscan_plan
1846 * Returns a functionscan plan for the base relation scanned by 'best_path'
1847 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1849 static FunctionScan *
1850 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1851 List *tlist, List *scan_clauses)
1853 FunctionScan *scan_plan;
1854 Index scan_relid = best_path->parent->relid;
1858 /* it should be a function base rel... */
1859 Assert(scan_relid > 0);
1860 rte = planner_rt_fetch(scan_relid, root);
1861 Assert(rte->rtekind == RTE_FUNCTION);
1862 functions = rte->functions;
1864 /* Sort clauses into best execution order */
1865 scan_clauses = order_qual_clauses(root, scan_clauses);
1867 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1868 scan_clauses = extract_actual_clauses(scan_clauses, false);
1870 /* Replace any outer-relation variables with nestloop params */
1871 if (best_path->param_info)
1873 scan_clauses = (List *)
1874 replace_nestloop_params(root, (Node *) scan_clauses);
1875 /* The function expressions could contain nestloop params, too */
1876 functions = (List *) replace_nestloop_params(root, (Node *) functions);
1879 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
1880 functions, rte->funcordinality);
1882 copy_path_costsize(&scan_plan->scan.plan, best_path);
1888 * create_valuesscan_plan
1889 * Returns a valuesscan plan for the base relation scanned by 'best_path'
1890 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1893 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
1894 List *tlist, List *scan_clauses)
1896 ValuesScan *scan_plan;
1897 Index scan_relid = best_path->parent->relid;
1901 /* it should be a values base rel... */
1902 Assert(scan_relid > 0);
1903 rte = planner_rt_fetch(scan_relid, root);
1904 Assert(rte->rtekind == RTE_VALUES);
1905 values_lists = rte->values_lists;
1907 /* Sort clauses into best execution order */
1908 scan_clauses = order_qual_clauses(root, scan_clauses);
1910 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1911 scan_clauses = extract_actual_clauses(scan_clauses, false);
1913 /* Replace any outer-relation variables with nestloop params */
1914 if (best_path->param_info)
1916 scan_clauses = (List *)
1917 replace_nestloop_params(root, (Node *) scan_clauses);
1918 /* The values lists could contain nestloop params, too */
1919 values_lists = (List *)
1920 replace_nestloop_params(root, (Node *) values_lists);
1923 scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
1926 copy_path_costsize(&scan_plan->scan.plan, best_path);
1932 * create_ctescan_plan
1933 * Returns a ctescan plan for the base relation scanned by 'best_path'
1934 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1937 create_ctescan_plan(PlannerInfo *root, Path *best_path,
1938 List *tlist, List *scan_clauses)
1941 Index scan_relid = best_path->parent->relid;
1943 SubPlan *ctesplan = NULL;
1946 PlannerInfo *cteroot;
1951 Assert(scan_relid > 0);
1952 rte = planner_rt_fetch(scan_relid, root);
1953 Assert(rte->rtekind == RTE_CTE);
1954 Assert(!rte->self_reference);
1957 * Find the referenced CTE, and locate the SubPlan previously made for it.
1959 levelsup = rte->ctelevelsup;
1961 while (levelsup-- > 0)
1963 cteroot = cteroot->parent_root;
1964 if (!cteroot) /* shouldn't happen */
1965 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1969 * Note: cte_plan_ids can be shorter than cteList, if we are still working
1970 * on planning the CTEs (ie, this is a side-reference from another CTE).
1971 * So we mustn't use forboth here.
1974 foreach(lc, cteroot->parse->cteList)
1976 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1978 if (strcmp(cte->ctename, rte->ctename) == 0)
1982 if (lc == NULL) /* shouldn't happen */
1983 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
1984 if (ndx >= list_length(cteroot->cte_plan_ids))
1985 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1986 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
1987 Assert(plan_id > 0);
1988 foreach(lc, cteroot->init_plans)
1990 ctesplan = (SubPlan *) lfirst(lc);
1991 if (ctesplan->plan_id == plan_id)
1994 if (lc == NULL) /* shouldn't happen */
1995 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1998 * We need the CTE param ID, which is the sole member of the SubPlan's
2001 cte_param_id = linitial_int(ctesplan->setParam);
2003 /* Sort clauses into best execution order */
2004 scan_clauses = order_qual_clauses(root, scan_clauses);
2006 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2007 scan_clauses = extract_actual_clauses(scan_clauses, false);
2009 /* Replace any outer-relation variables with nestloop params */
2010 if (best_path->param_info)
2012 scan_clauses = (List *)
2013 replace_nestloop_params(root, (Node *) scan_clauses);
2016 scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
2017 plan_id, cte_param_id);
2019 copy_path_costsize(&scan_plan->scan.plan, best_path);
2025 * create_worktablescan_plan
2026 * Returns a worktablescan plan for the base relation scanned by 'best_path'
2027 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2029 static WorkTableScan *
2030 create_worktablescan_plan(PlannerInfo *root, Path *best_path,
2031 List *tlist, List *scan_clauses)
2033 WorkTableScan *scan_plan;
2034 Index scan_relid = best_path->parent->relid;
2037 PlannerInfo *cteroot;
2039 Assert(scan_relid > 0);
2040 rte = planner_rt_fetch(scan_relid, root);
2041 Assert(rte->rtekind == RTE_CTE);
2042 Assert(rte->self_reference);
2045 * We need to find the worktable param ID, which is in the plan level
2046 * that's processing the recursive UNION, which is one level *below* where
2047 * the CTE comes from.
2049 levelsup = rte->ctelevelsup;
2050 if (levelsup == 0) /* shouldn't happen */
2051 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2054 while (levelsup-- > 0)
2056 cteroot = cteroot->parent_root;
2057 if (!cteroot) /* shouldn't happen */
2058 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2060 if (cteroot->wt_param_id < 0) /* shouldn't happen */
2061 elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
2063 /* Sort clauses into best execution order */
2064 scan_clauses = order_qual_clauses(root, scan_clauses);
2066 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2067 scan_clauses = extract_actual_clauses(scan_clauses, false);
2069 /* Replace any outer-relation variables with nestloop params */
2070 if (best_path->param_info)
2072 scan_clauses = (List *)
2073 replace_nestloop_params(root, (Node *) scan_clauses);
2076 scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
2077 cteroot->wt_param_id);
2079 copy_path_costsize(&scan_plan->scan.plan, best_path);
2085 * create_foreignscan_plan
2086 * Returns a foreignscan plan for the relation scanned by 'best_path'
2087 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2089 static ForeignScan *
2090 create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
2091 List *tlist, List *scan_clauses)
2093 ForeignScan *scan_plan;
2094 RelOptInfo *rel = best_path->path.parent;
2095 Index scan_relid = rel->relid;
2096 Oid rel_oid = InvalidOid;
2097 Bitmapset *attrs_used = NULL;
2101 Assert(rel->fdwroutine != NULL);
2104 * If we're scanning a base relation, fetch its OID. (Irrelevant if
2105 * scanning a join relation.)
2111 Assert(rel->rtekind == RTE_RELATION);
2112 rte = planner_rt_fetch(scan_relid, root);
2113 Assert(rte->rtekind == RTE_RELATION);
2114 rel_oid = rte->relid;
2118 * Sort clauses into best execution order. We do this first since the FDW
2119 * might have more info than we do and wish to adjust the ordering.
2121 scan_clauses = order_qual_clauses(root, scan_clauses);
2124 * Let the FDW perform its processing on the restriction clauses and
2125 * generate the plan node. Note that the FDW might remove restriction
2126 * clauses that it intends to execute remotely, or even add more (if it
2127 * has selected some join clauses for remote use but also wants them
2128 * rechecked locally).
2130 scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
2132 tlist, scan_clauses);
2134 /* Copy cost data from Path to Plan; no need to make FDW do this */
2135 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
2137 /* Copy foreign server OID; likewise, no need to make FDW do this */
2138 scan_plan->fs_server = rel->serverid;
2140 /* Likewise, copy the relids that are represented by this foreign scan */
2141 scan_plan->fs_relids = best_path->path.parent->relids;
2144 * Replace any outer-relation variables with nestloop params in the qual
2145 * and fdw_exprs expressions. We do this last so that the FDW doesn't
2146 * have to be involved. (Note that parts of fdw_exprs could have come
2147 * from join clauses, so doing this beforehand on the scan_clauses
2148 * wouldn't work.) We assume fdw_scan_tlist contains no such variables.
2150 if (best_path->path.param_info)
2152 scan_plan->scan.plan.qual = (List *)
2153 replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
2154 scan_plan->fdw_exprs = (List *)
2155 replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
2159 * Detect whether any system columns are requested from rel. This is a
2160 * bit of a kluge and might go away someday, so we intentionally leave it
2161 * out of the API presented to FDWs.
2163 * First, examine all the attributes needed for joins or final output.
2164 * Note: we must look at reltargetlist, not the attr_needed data, because
2165 * attr_needed isn't computed for inheritance child rels.
2167 pull_varattnos((Node *) rel->reltargetlist, rel->relid, &attrs_used);
2169 /* Add all the attributes used by restriction clauses. */
2170 foreach(lc, rel->baserestrictinfo)
2172 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2174 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
2177 /* Now, are any system columns requested from rel? */
2178 scan_plan->fsSystemCol = false;
2179 for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
2181 if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
2183 scan_plan->fsSystemCol = true;
2188 bms_free(attrs_used);
2194 * create_custom_plan
2196 * Transform a CustomPath into a Plan.
2199 create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
2200 List *tlist, List *scan_clauses)
2203 RelOptInfo *rel = best_path->path.parent;
2204 List *custom_plans = NIL;
2207 /* Recursively transform child paths. */
2208 foreach(lc, best_path->custom_paths)
2210 Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc));
2212 custom_plans = lappend(custom_plans, plan);
2216 * Sort clauses into the best execution order, although custom-scan
2217 * provider can reorder them again.
2219 scan_clauses = order_qual_clauses(root, scan_clauses);
2222 * Invoke custom plan provider to create the Plan node represented by the
2225 cplan = (CustomScan *) best_path->methods->PlanCustomPath(root,
2231 Assert(IsA(cplan, CustomScan));
2234 * Copy cost data from Path to Plan; no need to make custom-plan providers
2237 copy_path_costsize(&cplan->scan.plan, &best_path->path);
2239 /* Likewise, copy the relids that are represented by this custom scan */
2240 cplan->custom_relids = best_path->path.parent->relids;
2243 * Replace any outer-relation variables with nestloop params in the qual
2244 * and custom_exprs expressions. We do this last so that the custom-plan
2245 * provider doesn't have to be involved. (Note that parts of custom_exprs
2246 * could have come from join clauses, so doing this beforehand on the
2247 * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
2250 if (best_path->path.param_info)
2252 cplan->scan.plan.qual = (List *)
2253 replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
2254 cplan->custom_exprs = (List *)
2255 replace_nestloop_params(root, (Node *) cplan->custom_exprs);
2262 /*****************************************************************************
2266 *****************************************************************************/
2269 create_nestloop_plan(PlannerInfo *root,
2270 NestPath *best_path,
2274 NestLoop *join_plan;
2275 List *tlist = build_path_tlist(root, &best_path->path);
2276 List *joinrestrictclauses = best_path->joinrestrictinfo;
2285 /* Sort join qual clauses into best execution order */
2286 joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
2288 /* Get the join qual clauses (in plain expression form) */
2289 /* Any pseudoconstant clauses are ignored here */
2290 if (IS_OUTER_JOIN(best_path->jointype))
2292 extract_actual_join_clauses(joinrestrictclauses,
2293 &joinclauses, &otherclauses);
2297 /* We can treat all clauses alike for an inner join */
2298 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
2302 /* Replace any outer-relation variables with nestloop params */
2303 if (best_path->path.param_info)
2305 joinclauses = (List *)
2306 replace_nestloop_params(root, (Node *) joinclauses);
2307 otherclauses = (List *)
2308 replace_nestloop_params(root, (Node *) otherclauses);
2312 * Identify any nestloop parameters that should be supplied by this join
2313 * node, and move them from root->curOuterParams to the nestParams list.
2315 outerrelids = best_path->outerjoinpath->parent->relids;
2318 for (cell = list_head(root->curOuterParams); cell; cell = next)
2320 NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
2323 if (IsA(nlp->paramval, Var) &&
2324 bms_is_member(nlp->paramval->varno, outerrelids))
2326 root->curOuterParams = list_delete_cell(root->curOuterParams,
2328 nestParams = lappend(nestParams, nlp);
2330 else if (IsA(nlp->paramval, PlaceHolderVar) &&
2331 bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
2333 bms_is_subset(find_placeholder_info(root,
2334 (PlaceHolderVar *) nlp->paramval,
2338 root->curOuterParams = list_delete_cell(root->curOuterParams,
2340 nestParams = lappend(nestParams, nlp);
2346 join_plan = make_nestloop(tlist,
2352 best_path->jointype);
2354 copy_path_costsize(&join_plan->join.plan, &best_path->path);
2360 create_mergejoin_plan(PlannerInfo *root,
2361 MergePath *best_path,
2365 List *tlist = build_path_tlist(root, &best_path->jpath.path);
2369 List *outerpathkeys;
2370 List *innerpathkeys;
2373 Oid *mergecollations;
2374 int *mergestrategies;
2375 bool *mergenullsfirst;
2376 MergeJoin *join_plan;
2382 /* Sort join qual clauses into best execution order */
2383 /* NB: do NOT reorder the mergeclauses */
2384 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2386 /* Get the join qual clauses (in plain expression form) */
2387 /* Any pseudoconstant clauses are ignored here */
2388 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2390 extract_actual_join_clauses(joinclauses,
2391 &joinclauses, &otherclauses);
2395 /* We can treat all clauses alike for an inner join */
2396 joinclauses = extract_actual_clauses(joinclauses, false);
2401 * Remove the mergeclauses from the list of join qual clauses, leaving the
2402 * list of quals that must be checked as qpquals.
2404 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
2405 joinclauses = list_difference(joinclauses, mergeclauses);
2408 * Replace any outer-relation variables with nestloop params. There
2409 * should not be any in the mergeclauses.
2411 if (best_path->jpath.path.param_info)
2413 joinclauses = (List *)
2414 replace_nestloop_params(root, (Node *) joinclauses);
2415 otherclauses = (List *)
2416 replace_nestloop_params(root, (Node *) otherclauses);
2420 * Rearrange mergeclauses, if needed, so that the outer variable is always
2421 * on the left; mark the mergeclause restrictinfos with correct
2422 * outer_is_left status.
2424 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
2425 best_path->jpath.outerjoinpath->parent->relids);
2428 * Create explicit sort nodes for the outer and inner paths if necessary.
2429 * Make sure there are no excess columns in the inputs if sorting.
2431 if (best_path->outersortkeys)
2433 disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath);
2434 outer_plan = (Plan *)
2435 make_sort_from_pathkeys(root,
2437 best_path->outersortkeys,
2439 outerpathkeys = best_path->outersortkeys;
2442 outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
2444 if (best_path->innersortkeys)
2446 disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath);
2447 inner_plan = (Plan *)
2448 make_sort_from_pathkeys(root,
2450 best_path->innersortkeys,
2452 innerpathkeys = best_path->innersortkeys;
2455 innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
2458 * If specified, add a materialize node to shield the inner plan from the
2459 * need to handle mark/restore.
2461 if (best_path->materialize_inner)
2463 Plan *matplan = (Plan *) make_material(inner_plan);
2466 * We assume the materialize will not spill to disk, and therefore
2467 * charge just cpu_operator_cost per tuple. (Keep this estimate in
2468 * sync with final_cost_mergejoin.)
2470 copy_plan_costsize(matplan, inner_plan);
2471 matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
2473 inner_plan = matplan;
2477 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
2478 * executor. The information is in the pathkeys for the two inputs, but
2479 * we need to be careful about the possibility of mergeclauses sharing a
2480 * pathkey (compare find_mergeclauses_for_pathkeys()).
2482 nClauses = list_length(mergeclauses);
2483 Assert(nClauses == list_length(best_path->path_mergeclauses));
2484 mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
2485 mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
2486 mergestrategies = (int *) palloc(nClauses * sizeof(int));
2487 mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
2489 lop = list_head(outerpathkeys);
2490 lip = list_head(innerpathkeys);
2492 foreach(lc, best_path->path_mergeclauses)
2494 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2495 EquivalenceClass *oeclass;
2496 EquivalenceClass *ieclass;
2499 EquivalenceClass *opeclass;
2500 EquivalenceClass *ipeclass;
2503 /* fetch outer/inner eclass from mergeclause */
2504 Assert(IsA(rinfo, RestrictInfo));
2505 if (rinfo->outer_is_left)
2507 oeclass = rinfo->left_ec;
2508 ieclass = rinfo->right_ec;
2512 oeclass = rinfo->right_ec;
2513 ieclass = rinfo->left_ec;
2515 Assert(oeclass != NULL);
2516 Assert(ieclass != NULL);
2519 * For debugging purposes, we check that the eclasses match the paths'
2520 * pathkeys. In typical cases the merge clauses are one-to-one with
2521 * the pathkeys, but when dealing with partially redundant query
2522 * conditions, we might have clauses that re-reference earlier path
2523 * keys. The case that we need to reject is where a pathkey is
2524 * entirely skipped over.
2526 * lop and lip reference the first as-yet-unused pathkey elements;
2527 * it's okay to match them, or any element before them. If they're
2528 * NULL then we have found all pathkey elements to be used.
2532 opathkey = (PathKey *) lfirst(lop);
2533 opeclass = opathkey->pk_eclass;
2534 if (oeclass == opeclass)
2536 /* fast path for typical case */
2541 /* redundant clauses ... must match something before lop */
2542 foreach(l2, outerpathkeys)
2546 opathkey = (PathKey *) lfirst(l2);
2547 opeclass = opathkey->pk_eclass;
2548 if (oeclass == opeclass)
2551 if (oeclass != opeclass)
2552 elog(ERROR, "outer pathkeys do not match mergeclauses");
2557 /* redundant clauses ... must match some already-used pathkey */
2560 foreach(l2, outerpathkeys)
2562 opathkey = (PathKey *) lfirst(l2);
2563 opeclass = opathkey->pk_eclass;
2564 if (oeclass == opeclass)
2568 elog(ERROR, "outer pathkeys do not match mergeclauses");
2573 ipathkey = (PathKey *) lfirst(lip);
2574 ipeclass = ipathkey->pk_eclass;
2575 if (ieclass == ipeclass)
2577 /* fast path for typical case */
2582 /* redundant clauses ... must match something before lip */
2583 foreach(l2, innerpathkeys)
2587 ipathkey = (PathKey *) lfirst(l2);
2588 ipeclass = ipathkey->pk_eclass;
2589 if (ieclass == ipeclass)
2592 if (ieclass != ipeclass)
2593 elog(ERROR, "inner pathkeys do not match mergeclauses");
2598 /* redundant clauses ... must match some already-used pathkey */
2601 foreach(l2, innerpathkeys)
2603 ipathkey = (PathKey *) lfirst(l2);
2604 ipeclass = ipathkey->pk_eclass;
2605 if (ieclass == ipeclass)
2609 elog(ERROR, "inner pathkeys do not match mergeclauses");
2612 /* pathkeys should match each other too (more debugging) */
2613 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2614 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2615 opathkey->pk_strategy != ipathkey->pk_strategy ||
2616 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2617 elog(ERROR, "left and right pathkeys do not match in mergejoin");
2619 /* OK, save info for executor */
2620 mergefamilies[i] = opathkey->pk_opfamily;
2621 mergecollations[i] = opathkey->pk_eclass->ec_collation;
2622 mergestrategies[i] = opathkey->pk_strategy;
2623 mergenullsfirst[i] = opathkey->pk_nulls_first;
2628 * Note: it is not an error if we have additional pathkey elements (i.e.,
2629 * lop or lip isn't NULL here). The input paths might be better-sorted
2630 * than we need for the current mergejoin.
2634 * Now we can build the mergejoin node.
2636 join_plan = make_mergejoin(tlist,
2646 best_path->jpath.jointype);
2648 /* Costs of sort and material steps are included in path cost already */
2649 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
2655 create_hashjoin_plan(PlannerInfo *root,
2656 HashPath *best_path,
2660 List *tlist = build_path_tlist(root, &best_path->jpath.path);
2664 Oid skewTable = InvalidOid;
2665 AttrNumber skewColumn = InvalidAttrNumber;
2666 bool skewInherit = false;
2667 Oid skewColType = InvalidOid;
2668 int32 skewColTypmod = -1;
2669 HashJoin *join_plan;
2672 /* Sort join qual clauses into best execution order */
2673 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2674 /* There's no point in sorting the hash clauses ... */
2676 /* Get the join qual clauses (in plain expression form) */
2677 /* Any pseudoconstant clauses are ignored here */
2678 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2680 extract_actual_join_clauses(joinclauses,
2681 &joinclauses, &otherclauses);
2685 /* We can treat all clauses alike for an inner join */
2686 joinclauses = extract_actual_clauses(joinclauses, false);
2691 * Remove the hashclauses from the list of join qual clauses, leaving the
2692 * list of quals that must be checked as qpquals.
2694 hashclauses = get_actual_clauses(best_path->path_hashclauses);
2695 joinclauses = list_difference(joinclauses, hashclauses);
2698 * Replace any outer-relation variables with nestloop params. There
2699 * should not be any in the hashclauses.
2701 if (best_path->jpath.path.param_info)
2703 joinclauses = (List *)
2704 replace_nestloop_params(root, (Node *) joinclauses);
2705 otherclauses = (List *)
2706 replace_nestloop_params(root, (Node *) otherclauses);
2710 * Rearrange hashclauses, if needed, so that the outer variable is always
2713 hashclauses = get_switched_clauses(best_path->path_hashclauses,
2714 best_path->jpath.outerjoinpath->parent->relids);
2716 /* We don't want any excess columns in the hashed tuples */
2717 disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath);
2719 /* If we expect batching, suppress excess columns in outer tuples too */
2720 if (best_path->num_batches > 1)
2721 disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath);
2724 * If there is a single join clause and we can identify the outer variable
2725 * as a simple column reference, supply its identity for possible use in
2726 * skew optimization. (Note: in principle we could do skew optimization
2727 * with multiple join clauses, but we'd have to be able to determine the
2728 * most common combinations of outer values, which we don't currently have
2729 * enough stats for.)
2731 if (list_length(hashclauses) == 1)
2733 OpExpr *clause = (OpExpr *) linitial(hashclauses);
2736 Assert(is_opclause(clause));
2737 node = (Node *) linitial(clause->args);
2738 if (IsA(node, RelabelType))
2739 node = (Node *) ((RelabelType *) node)->arg;
2742 Var *var = (Var *) node;
2745 rte = root->simple_rte_array[var->varno];
2746 if (rte->rtekind == RTE_RELATION)
2748 skewTable = rte->relid;
2749 skewColumn = var->varattno;
2750 skewInherit = rte->inh;
2751 skewColType = var->vartype;
2752 skewColTypmod = var->vartypmod;
2758 * Build the hash node and hash join node.
2760 hash_plan = make_hash(inner_plan,
2766 join_plan = make_hashjoin(tlist,
2772 best_path->jpath.jointype);
2774 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
2780 /*****************************************************************************
2782 * SUPPORTING ROUTINES
2784 *****************************************************************************/
2787 * replace_nestloop_params
2788 * Replace outer-relation Vars and PlaceHolderVars in the given expression
2789 * with nestloop Params
2791 * All Vars and PlaceHolderVars belonging to the relation(s) identified by
2792 * root->curOuterRels are replaced by Params, and entries are added to
2793 * root->curOuterParams if not already present.
2796 replace_nestloop_params(PlannerInfo *root, Node *expr)
2798 /* No setup needed for tree walk, so away we go */
2799 return replace_nestloop_params_mutator(expr, root);
2803 replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
2809 Var *var = (Var *) node;
2814 /* Upper-level Vars should be long gone at this point */
2815 Assert(var->varlevelsup == 0);
2816 /* If not to be replaced, we can just return the Var unmodified */
2817 if (!bms_is_member(var->varno, root->curOuterRels))
2819 /* Create a Param representing the Var */
2820 param = assign_nestloop_param_var(root, var);
2821 /* Is this param already listed in root->curOuterParams? */
2822 foreach(lc, root->curOuterParams)
2824 nlp = (NestLoopParam *) lfirst(lc);
2825 if (nlp->paramno == param->paramid)
2827 Assert(equal(var, nlp->paramval));
2828 /* Present, so we can just return the Param */
2829 return (Node *) param;
2833 nlp = makeNode(NestLoopParam);
2834 nlp->paramno = param->paramid;
2835 nlp->paramval = var;
2836 root->curOuterParams = lappend(root->curOuterParams, nlp);
2837 /* And return the replacement Param */
2838 return (Node *) param;
2840 if (IsA(node, PlaceHolderVar))
2842 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2847 /* Upper-level PlaceHolderVars should be long gone at this point */
2848 Assert(phv->phlevelsup == 0);
2851 * Check whether we need to replace the PHV. We use bms_overlap as a
2852 * cheap/quick test to see if the PHV might be evaluated in the outer
2853 * rels, and then grab its PlaceHolderInfo to tell for sure.
2855 if (!bms_overlap(phv->phrels, root->curOuterRels) ||
2856 !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2857 root->curOuterRels))
2860 * We can't replace the whole PHV, but we might still need to
2861 * replace Vars or PHVs within its expression, in case it ends up
2862 * actually getting evaluated here. (It might get evaluated in
2863 * this plan node, or some child node; in the latter case we don't
2864 * really need to process the expression here, but we haven't got
2865 * enough info to tell if that's the case.) Flat-copy the PHV
2866 * node and then recurse on its expression.
2868 * Note that after doing this, we might have different
2869 * representations of the contents of the same PHV in different
2870 * parts of the plan tree. This is OK because equal() will just
2871 * match on phid/phlevelsup, so setrefs.c will still recognize an
2872 * upper-level reference to a lower-level copy of the same PHV.
2874 PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
2876 memcpy(newphv, phv, sizeof(PlaceHolderVar));
2877 newphv->phexpr = (Expr *)
2878 replace_nestloop_params_mutator((Node *) phv->phexpr,
2880 return (Node *) newphv;
2882 /* Create a Param representing the PlaceHolderVar */
2883 param = assign_nestloop_param_placeholdervar(root, phv);
2884 /* Is this param already listed in root->curOuterParams? */
2885 foreach(lc, root->curOuterParams)
2887 nlp = (NestLoopParam *) lfirst(lc);
2888 if (nlp->paramno == param->paramid)
2890 Assert(equal(phv, nlp->paramval));
2891 /* Present, so we can just return the Param */
2892 return (Node *) param;
2896 nlp = makeNode(NestLoopParam);
2897 nlp->paramno = param->paramid;
2898 nlp->paramval = (Var *) phv;
2899 root->curOuterParams = lappend(root->curOuterParams, nlp);
2900 /* And return the replacement Param */
2901 return (Node *) param;
2903 return expression_tree_mutator(node,
2904 replace_nestloop_params_mutator,
2909 * process_subquery_nestloop_params
2910 * Handle params of a parameterized subquery that need to be fed
2911 * from an outer nestloop.
2913 * Currently, that would be *all* params that a subquery in FROM has demanded
2914 * from the current query level, since they must be LATERAL references.
2916 * The subplan's references to the outer variables are already represented
2917 * as PARAM_EXEC Params, so we need not modify the subplan here. What we
2918 * do need to do is add entries to root->curOuterParams to signal the parent
2919 * nestloop plan node that it must provide these values.
2922 process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
2926 foreach(ppl, subplan_params)
2928 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
2930 if (IsA(pitem->item, Var))
2932 Var *var = (Var *) pitem->item;
2936 /* If not from a nestloop outer rel, complain */
2937 if (!bms_is_member(var->varno, root->curOuterRels))
2938 elog(ERROR, "non-LATERAL parameter required by subquery");
2939 /* Is this param already listed in root->curOuterParams? */
2940 foreach(lc, root->curOuterParams)
2942 nlp = (NestLoopParam *) lfirst(lc);
2943 if (nlp->paramno == pitem->paramId)
2945 Assert(equal(var, nlp->paramval));
2946 /* Present, so nothing to do */
2953 nlp = makeNode(NestLoopParam);
2954 nlp->paramno = pitem->paramId;
2955 nlp->paramval = copyObject(var);
2956 root->curOuterParams = lappend(root->curOuterParams, nlp);
2959 else if (IsA(pitem->item, PlaceHolderVar))
2961 PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
2965 /* If not from a nestloop outer rel, complain */
2966 if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2967 root->curOuterRels))
2968 elog(ERROR, "non-LATERAL parameter required by subquery");
2969 /* Is this param already listed in root->curOuterParams? */
2970 foreach(lc, root->curOuterParams)
2972 nlp = (NestLoopParam *) lfirst(lc);
2973 if (nlp->paramno == pitem->paramId)
2975 Assert(equal(phv, nlp->paramval));
2976 /* Present, so nothing to do */
2983 nlp = makeNode(NestLoopParam);
2984 nlp->paramno = pitem->paramId;
2985 nlp->paramval = copyObject(phv);
2986 root->curOuterParams = lappend(root->curOuterParams, nlp);
2990 elog(ERROR, "unexpected type of subquery parameter");
2995 * fix_indexqual_references
2996 * Adjust indexqual clauses to the form the executor's indexqual
2999 * We have four tasks here:
3000 * * Remove RestrictInfo nodes from the input clauses.
3001 * * Replace any outer-relation Var or PHV nodes with nestloop Params.
3002 * (XXX eventually, that responsibility should go elsewhere?)
3003 * * Index keys must be represented by Var nodes with varattno set to the
3004 * index's attribute number, not the attribute number in the original rel.
3005 * * If the index key is on the right, commute the clause to put it on the
3008 * The result is a modified copy of the path's indexquals list --- the
3009 * original is not changed. Note also that the copy shares no substructure
3010 * with the original; this is needed in case there is a subplan in it (we need
3011 * two separate copies of the subplan tree, or things will go awry).
3014 fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
3016 IndexOptInfo *index = index_path->indexinfo;
3017 List *fixed_indexquals;
3021 fixed_indexquals = NIL;
3023 forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
3025 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
3026 int indexcol = lfirst_int(lci);
3029 Assert(IsA(rinfo, RestrictInfo));
3032 * Replace any outer-relation variables with nestloop params.
3034 * This also makes a copy of the clause, so it's safe to modify it
3037 clause = replace_nestloop_params(root, (Node *) rinfo->clause);
3039 if (IsA(clause, OpExpr))
3041 OpExpr *op = (OpExpr *) clause;
3043 if (list_length(op->args) != 2)
3044 elog(ERROR, "indexqual clause is not binary opclause");
3047 * Check to see if the indexkey is on the right; if so, commute
3048 * the clause. The indexkey should be the side that refers to
3049 * (only) the base relation.
3051 if (!bms_equal(rinfo->left_relids, index->rel->relids))
3055 * Now replace the indexkey expression with an index Var.
3057 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
3061 else if (IsA(clause, RowCompareExpr))
3063 RowCompareExpr *rc = (RowCompareExpr *) clause;
3071 * Re-discover which index columns are used in the rowcompare.
3073 newrc = adjust_rowcompare_for_index(rc,
3080 * Trouble if adjust_rowcompare_for_index thought the
3081 * RowCompareExpr didn't match the index as-is; the clause should
3082 * have gone through that routine already.
3084 if (newrc != (Expr *) rc)
3085 elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
3088 * Check to see if the indexkey is on the right; if so, commute
3092 CommuteRowCompareExpr(rc);
3095 * Now replace the indexkey expressions with index Vars.
3097 Assert(list_length(rc->largs) == list_length(indexcolnos));
3098 forboth(lca, rc->largs, lcai, indexcolnos)
3100 lfirst(lca) = fix_indexqual_operand(lfirst(lca),
3105 else if (IsA(clause, ScalarArrayOpExpr))
3107 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
3109 /* Never need to commute... */
3111 /* Replace the indexkey expression with an index Var. */
3112 linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
3116 else if (IsA(clause, NullTest))
3118 NullTest *nt = (NullTest *) clause;
3120 /* Replace the indexkey expression with an index Var. */
3121 nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
3126 elog(ERROR, "unsupported indexqual type: %d",
3127 (int) nodeTag(clause));
3129 fixed_indexquals = lappend(fixed_indexquals, clause);
3132 return fixed_indexquals;
3136 * fix_indexorderby_references
3137 * Adjust indexorderby clauses to the form the executor's index
3140 * This is a simplified version of fix_indexqual_references. The input does
3141 * not have RestrictInfo nodes, and we assume that indxpath.c already
3142 * commuted the clauses to put the index keys on the left. Also, we don't
3143 * bother to support any cases except simple OpExprs, since nothing else
3144 * is allowed for ordering operators.
3147 fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
3149 IndexOptInfo *index = index_path->indexinfo;
3150 List *fixed_indexorderbys;
3154 fixed_indexorderbys = NIL;
3156 forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
3158 Node *clause = (Node *) lfirst(lcc);
3159 int indexcol = lfirst_int(lci);
3162 * Replace any outer-relation variables with nestloop params.
3164 * This also makes a copy of the clause, so it's safe to modify it
3167 clause = replace_nestloop_params(root, clause);
3169 if (IsA(clause, OpExpr))
3171 OpExpr *op = (OpExpr *) clause;
3173 if (list_length(op->args) != 2)
3174 elog(ERROR, "indexorderby clause is not binary opclause");
3177 * Now replace the indexkey expression with an index Var.
3179 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
3184 elog(ERROR, "unsupported indexorderby type: %d",
3185 (int) nodeTag(clause));
3187 fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
3190 return fixed_indexorderbys;
3194 * fix_indexqual_operand
3195 * Convert an indexqual expression to a Var referencing the index column.
3197 * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
3198 * equal to the index's attribute number (index column position).
3200 * Most of the code here is just for sanity cross-checking that the given
3201 * expression actually matches the index column it's claimed to.
3204 fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
3208 ListCell *indexpr_item;
3211 * Remove any binary-compatible relabeling of the indexkey
3213 if (IsA(node, RelabelType))
3214 node = (Node *) ((RelabelType *) node)->arg;
3216 Assert(indexcol >= 0 && indexcol < index->ncolumns);
3218 if (index->indexkeys[indexcol] != 0)
3220 /* It's a simple index column */
3221 if (IsA(node, Var) &&
3222 ((Var *) node)->varno == index->rel->relid &&
3223 ((Var *) node)->varattno == index->indexkeys[indexcol])
3225 result = (Var *) copyObject(node);
3226 result->varno = INDEX_VAR;
3227 result->varattno = indexcol + 1;
3228 return (Node *) result;
3231 elog(ERROR, "index key does not match expected index column");
3234 /* It's an index expression, so find and cross-check the expression */
3235 indexpr_item = list_head(index->indexprs);
3236 for (pos = 0; pos < index->ncolumns; pos++)
3238 if (index->indexkeys[pos] == 0)
3240 if (indexpr_item == NULL)
3241 elog(ERROR, "too few entries in indexprs list");
3242 if (pos == indexcol)
3246 indexkey = (Node *) lfirst(indexpr_item);
3247 if (indexkey && IsA(indexkey, RelabelType))
3248 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3249 if (equal(node, indexkey))
3251 result = makeVar(INDEX_VAR, indexcol + 1,
3252 exprType(lfirst(indexpr_item)), -1,
3253 exprCollation(lfirst(indexpr_item)),
3255 return (Node *) result;
3258 elog(ERROR, "index key does not match expected index column");
3260 indexpr_item = lnext(indexpr_item);
3265 elog(ERROR, "index key does not match expected index column");
3266 return NULL; /* keep compiler quiet */
3270 * get_switched_clauses
3271 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
3272 * extract the bare clauses, and rearrange the elements within the
3273 * clauses, if needed, so the outer join variable is on the left and
3274 * the inner is on the right. The original clause data structure is not
3275 * touched; a modified list is returned. We do, however, set the transient
3276 * outer_is_left field in each RestrictInfo to show which side was which.
3279 get_switched_clauses(List *clauses, Relids outerrelids)
3286 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
3287 OpExpr *clause = (OpExpr *) restrictinfo->clause;
3289 Assert(is_opclause(clause));
3290 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
3293 * Duplicate just enough of the structure to allow commuting the
3294 * clause without changing the original list. Could use
3295 * copyObject, but a complete deep copy is overkill.
3297 OpExpr *temp = makeNode(OpExpr);
3299 temp->opno = clause->opno;
3300 temp->opfuncid = InvalidOid;
3301 temp->opresulttype = clause->opresulttype;
3302 temp->opretset = clause->opretset;
3303 temp->opcollid = clause->opcollid;
3304 temp->inputcollid = clause->inputcollid;
3305 temp->args = list_copy(clause->args);
3306 temp->location = clause->location;
3307 /* Commute it --- note this modifies the temp node in-place. */
3308 CommuteOpExpr(temp);
3309 t_list = lappend(t_list, temp);
3310 restrictinfo->outer_is_left = false;
3314 Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
3315 t_list = lappend(t_list, clause);
3316 restrictinfo->outer_is_left = true;
3323 * order_qual_clauses
3324 * Given a list of qual clauses that will all be evaluated at the same
3325 * plan node, sort the list into the order we want to check the quals
3328 * Ideally the order should be driven by a combination of execution cost and
3329 * selectivity, but it's not immediately clear how to account for both,
3330 * and given the uncertainty of the estimates the reliability of the decisions
3331 * would be doubtful anyway. So we just order by estimated per-tuple cost,
3332 * being careful not to change the order when (as is often the case) the
3333 * estimates are identical.
3335 * Although this will work on either bare clauses or RestrictInfos, it's
3336 * much faster to apply it to RestrictInfos, since it can re-use cost
3337 * information that is cached in RestrictInfos.
3339 * Note: some callers pass lists that contain entries that will later be
3340 * removed; this is the easiest way to let this routine see RestrictInfos
3341 * instead of bare clauses. It's OK because we only sort by cost, but
3342 * a cost/selectivity combination would likely do the wrong thing.
3345 order_qual_clauses(PlannerInfo *root, List *clauses)
3352 int nitems = list_length(clauses);
3358 /* No need to work hard for 0 or 1 clause */
3363 * Collect the items and costs into an array. This is to avoid repeated
3364 * cost_qual_eval work if the inputs aren't RestrictInfos.
3366 items = (QualItem *) palloc(nitems * sizeof(QualItem));
3368 foreach(lc, clauses)
3370 Node *clause = (Node *) lfirst(lc);
3373 cost_qual_eval_node(&qcost, clause, root);
3374 items[i].clause = clause;
3375 items[i].cost = qcost.per_tuple;
3380 * Sort. We don't use qsort() because it's not guaranteed stable for
3381 * equal keys. The expected number of entries is small enough that a
3382 * simple insertion sort should be good enough.
3384 for (i = 1; i < nitems; i++)
3386 QualItem newitem = items[i];
3389 /* insert newitem into the already-sorted subarray */
3390 for (j = i; j > 0; j--)
3392 if (newitem.cost >= items[j - 1].cost)
3394 items[j] = items[j - 1];
3399 /* Convert back to a list */
3401 for (i = 0; i < nitems; i++)
3402 result = lappend(result, items[i].clause);
3408 * Copy cost and size info from a Path node to the Plan node created from it.
3409 * The executor usually won't use this info, but it's needed by EXPLAIN.
3412 copy_path_costsize(Plan *dest, Path *src)
3416 dest->startup_cost = src->startup_cost;
3417 dest->total_cost = src->total_cost;
3418 dest->plan_rows = src->rows;
3419 dest->plan_width = src->parent->width;
3423 dest->startup_cost = 0;
3424 dest->total_cost = 0;
3425 dest->plan_rows = 0;
3426 dest->plan_width = 0;
3431 * Copy cost and size info from a lower plan node to an inserted node.
3432 * (Most callers alter the info after copying it.)
3435 copy_plan_costsize(Plan *dest, Plan *src)
3439 dest->startup_cost = src->startup_cost;
3440 dest->total_cost = src->total_cost;
3441 dest->plan_rows = src->plan_rows;
3442 dest->plan_width = src->plan_width;
3446 dest->startup_cost = 0;
3447 dest->total_cost = 0;
3448 dest->plan_rows = 0;
3449 dest->plan_width = 0;
3454 /*****************************************************************************
3456 * PLAN NODE BUILDING ROUTINES
3458 * Some of these are exported because they are called to build plan nodes
3459 * in contexts where we're not deriving the plan node from a path node.
3461 *****************************************************************************/
3464 make_seqscan(List *qptlist,
3468 SeqScan *node = makeNode(SeqScan);
3469 Plan *plan = &node->plan;
3471 /* cost should be inserted by caller */
3472 plan->targetlist = qptlist;
3473 plan->qual = qpqual;
3474 plan->lefttree = NULL;
3475 plan->righttree = NULL;
3476 node->scanrelid = scanrelid;
3482 make_samplescan(List *qptlist,
3485 TableSampleClause *tsc)
3487 SampleScan *node = makeNode(SampleScan);
3488 Plan *plan = &node->scan.plan;
3490 /* cost should be inserted by caller */
3491 plan->targetlist = qptlist;
3492 plan->qual = qpqual;
3493 plan->lefttree = NULL;
3494 plan->righttree = NULL;
3495 node->scan.scanrelid = scanrelid;
3496 node->tablesample = tsc;
3502 make_indexscan(List *qptlist,
3507 List *indexqualorig,
3509 List *indexorderbyorig,
3510 List *indexorderbyops,
3511 ScanDirection indexscandir)
3513 IndexScan *node = makeNode(IndexScan);
3514 Plan *plan = &node->scan.plan;
3516 /* cost should be inserted by caller */
3517 plan->targetlist = qptlist;
3518 plan->qual = qpqual;
3519 plan->lefttree = NULL;
3520 plan->righttree = NULL;
3521 node->scan.scanrelid = scanrelid;
3522 node->indexid = indexid;
3523 node->indexqual = indexqual;
3524 node->indexqualorig = indexqualorig;
3525 node->indexorderby = indexorderby;
3526 node->indexorderbyorig = indexorderbyorig;
3527 node->indexorderbyops = indexorderbyops;
3528 node->indexorderdir = indexscandir;
3533 static IndexOnlyScan *
3534 make_indexonlyscan(List *qptlist,
3541 ScanDirection indexscandir)
3543 IndexOnlyScan *node = makeNode(IndexOnlyScan);
3544 Plan *plan = &node->scan.plan;
3546 /* cost should be inserted by caller */
3547 plan->targetlist = qptlist;
3548 plan->qual = qpqual;
3549 plan->lefttree = NULL;
3550 plan->righttree = NULL;
3551 node->scan.scanrelid = scanrelid;
3552 node->indexid = indexid;
3553 node->indexqual = indexqual;
3554 node->indexorderby = indexorderby;
3555 node->indextlist = indextlist;
3556 node->indexorderdir = indexscandir;
3561 static BitmapIndexScan *
3562 make_bitmap_indexscan(Index scanrelid,
3565 List *indexqualorig)
3567 BitmapIndexScan *node = makeNode(BitmapIndexScan);
3568 Plan *plan = &node->scan.plan;
3570 /* cost should be inserted by caller */
3571 plan->targetlist = NIL; /* not used */
3572 plan->qual = NIL; /* not used */
3573 plan->lefttree = NULL;
3574 plan->righttree = NULL;
3575 node->scan.scanrelid = scanrelid;
3576 node->indexid = indexid;
3577 node->indexqual = indexqual;
3578 node->indexqualorig = indexqualorig;
3583 static BitmapHeapScan *
3584 make_bitmap_heapscan(List *qptlist,
3587 List *bitmapqualorig,
3590 BitmapHeapScan *node = makeNode(BitmapHeapScan);
3591 Plan *plan = &node->scan.plan;
3593 /* cost should be inserted by caller */
3594 plan->targetlist = qptlist;
3595 plan->qual = qpqual;
3596 plan->lefttree = lefttree;
3597 plan->righttree = NULL;
3598 node->scan.scanrelid = scanrelid;
3599 node->bitmapqualorig = bitmapqualorig;
3605 make_tidscan(List *qptlist,
3610 TidScan *node = makeNode(TidScan);
3611 Plan *plan = &node->scan.plan;
3613 /* cost should be inserted by caller */
3614 plan->targetlist = qptlist;
3615 plan->qual = qpqual;
3616 plan->lefttree = NULL;
3617 plan->righttree = NULL;
3618 node->scan.scanrelid = scanrelid;
3619 node->tidquals = tidquals;
3625 make_subqueryscan(List *qptlist,
3630 SubqueryScan *node = makeNode(SubqueryScan);
3631 Plan *plan = &node->scan.plan;
3634 * Cost is figured here for the convenience of prepunion.c. Note this is
3635 * only correct for the case where qpqual is empty; otherwise caller
3636 * should overwrite cost with a better estimate.
3638 copy_plan_costsize(plan, subplan);
3639 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
3641 plan->targetlist = qptlist;
3642 plan->qual = qpqual;
3643 plan->lefttree = NULL;
3644 plan->righttree = NULL;
3645 node->scan.scanrelid = scanrelid;
3646 node->subplan = subplan;
3651 static FunctionScan *
3652 make_functionscan(List *qptlist,
3656 bool funcordinality)
3658 FunctionScan *node = makeNode(FunctionScan);
3659 Plan *plan = &node->scan.plan;
3661 /* cost should be inserted by caller */
3662 plan->targetlist = qptlist;
3663 plan->qual = qpqual;
3664 plan->lefttree = NULL;
3665 plan->righttree = NULL;
3666 node->scan.scanrelid = scanrelid;
3667 node->functions = functions;
3668 node->funcordinality = funcordinality;
3674 make_valuesscan(List *qptlist,
3679 ValuesScan *node = makeNode(ValuesScan);
3680 Plan *plan = &node->scan.plan;
3682 /* cost should be inserted by caller */
3683 plan->targetlist = qptlist;
3684 plan->qual = qpqual;
3685 plan->lefttree = NULL;
3686 plan->righttree = NULL;
3687 node->scan.scanrelid = scanrelid;
3688 node->values_lists = values_lists;
3694 make_ctescan(List *qptlist,
3700 CteScan *node = makeNode(CteScan);
3701 Plan *plan = &node->scan.plan;
3703 /* cost should be inserted by caller */
3704 plan->targetlist = qptlist;
3705 plan->qual = qpqual;
3706 plan->lefttree = NULL;
3707 plan->righttree = NULL;
3708 node->scan.scanrelid = scanrelid;
3709 node->ctePlanId = ctePlanId;
3710 node->cteParam = cteParam;
3715 static WorkTableScan *
3716 make_worktablescan(List *qptlist,
3721 WorkTableScan *node = makeNode(WorkTableScan);
3722 Plan *plan = &node->scan.plan;
3724 /* cost should be inserted by caller */
3725 plan->targetlist = qptlist;
3726 plan->qual = qpqual;
3727 plan->lefttree = NULL;
3728 plan->righttree = NULL;
3729 node->scan.scanrelid = scanrelid;
3730 node->wtParam = wtParam;
3736 make_foreignscan(List *qptlist,
3741 List *fdw_scan_tlist)
3743 ForeignScan *node = makeNode(ForeignScan);
3744 Plan *plan = &node->scan.plan;
3746 /* cost will be filled in by create_foreignscan_plan */
3747 plan->targetlist = qptlist;
3748 plan->qual = qpqual;
3749 plan->lefttree = NULL;
3750 plan->righttree = NULL;
3751 node->scan.scanrelid = scanrelid;
3752 /* fs_server will be filled in by create_foreignscan_plan */
3753 node->fs_server = InvalidOid;
3754 node->fdw_exprs = fdw_exprs;
3755 node->fdw_private = fdw_private;
3756 node->fdw_scan_tlist = fdw_scan_tlist;
3757 /* fs_relids will be filled in by create_foreignscan_plan */
3758 node->fs_relids = NULL;
3759 /* fsSystemCol will be filled in by create_foreignscan_plan */
3760 node->fsSystemCol = false;
3766 make_append(List *appendplans, List *tlist)
3768 Append *node = makeNode(Append);
3769 Plan *plan = &node->plan;
3774 * Compute cost as sum of subplan costs. We charge nothing extra for the
3775 * Append itself, which perhaps is too optimistic, but since it doesn't do
3776 * any selection or projection, it is a pretty cheap node.
3778 * If you change this, see also create_append_path(). Also, the size
3779 * calculations should match set_append_rel_pathlist(). It'd be better
3780 * not to duplicate all this logic, but some callers of this function
3781 * aren't working from an appendrel or AppendPath, so there's noplace to
3782 * copy the data from.
3784 plan->startup_cost = 0;
3785 plan->total_cost = 0;
3786 plan->plan_rows = 0;
3788 foreach(subnode, appendplans)
3790 Plan *subplan = (Plan *) lfirst(subnode);
3792 if (subnode == list_head(appendplans)) /* first node? */
3793 plan->startup_cost = subplan->startup_cost;
3794 plan->total_cost += subplan->total_cost;
3795 plan->plan_rows += subplan->plan_rows;
3796 total_size += subplan->plan_width * subplan->plan_rows;
3798 if (plan->plan_rows > 0)
3799 plan->plan_width = rint(total_size / plan->plan_rows);
3801 plan->plan_width = 0;
3803 plan->targetlist = tlist;
3805 plan->lefttree = NULL;
3806 plan->righttree = NULL;
3807 node->appendplans = appendplans;
3813 make_recursive_union(List *tlist,
3820 RecursiveUnion *node = makeNode(RecursiveUnion);
3821 Plan *plan = &node->plan;
3822 int numCols = list_length(distinctList);
3824 cost_recursive_union(plan, lefttree, righttree);
3826 plan->targetlist = tlist;
3828 plan->lefttree = lefttree;
3829 plan->righttree = righttree;
3830 node->wtParam = wtParam;
3833 * convert SortGroupClause list into arrays of attr indexes and equality
3834 * operators, as wanted by executor
3836 node->numCols = numCols;
3840 AttrNumber *dupColIdx;
3844 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
3845 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
3847 foreach(slitem, distinctList)
3849 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
3850 TargetEntry *tle = get_sortgroupclause_tle(sortcl,
3853 dupColIdx[keyno] = tle->resno;
3854 dupOperators[keyno] = sortcl->eqop;
3855 Assert(OidIsValid(dupOperators[keyno]));
3858 node->dupColIdx = dupColIdx;
3859 node->dupOperators = dupOperators;
3861 node->numGroups = numGroups;
3867 make_bitmap_and(List *bitmapplans)
3869 BitmapAnd *node = makeNode(BitmapAnd);
3870 Plan *plan = &node->plan;
3872 /* cost should be inserted by caller */
3873 plan->targetlist = NIL;
3875 plan->lefttree = NULL;
3876 plan->righttree = NULL;
3877 node->bitmapplans = bitmapplans;
3883 make_bitmap_or(List *bitmapplans)
3885 BitmapOr *node = makeNode(BitmapOr);
3886 Plan *plan = &node->plan;
3888 /* cost should be inserted by caller */
3889 plan->targetlist = NIL;
3891 plan->lefttree = NULL;
3892 plan->righttree = NULL;
3893 node->bitmapplans = bitmapplans;
3899 make_nestloop(List *tlist,
3907 NestLoop *node = makeNode(NestLoop);
3908 Plan *plan = &node->join.plan;
3910 /* cost should be inserted by caller */
3911 plan->targetlist = tlist;
3912 plan->qual = otherclauses;
3913 plan->lefttree = lefttree;
3914 plan->righttree = righttree;
3915 node->join.jointype = jointype;
3916 node->join.joinqual = joinclauses;
3917 node->nestParams = nestParams;
3923 make_hashjoin(List *tlist,
3931 HashJoin *node = makeNode(HashJoin);
3932 Plan *plan = &node->join.plan;
3934 /* cost should be inserted by caller */
3935 plan->targetlist = tlist;
3936 plan->qual = otherclauses;
3937 plan->lefttree = lefttree;
3938 plan->righttree = righttree;
3939 node->hashclauses = hashclauses;
3940 node->join.jointype = jointype;
3941 node->join.joinqual = joinclauses;
3947 make_hash(Plan *lefttree,
3949 AttrNumber skewColumn,
3952 int32 skewColTypmod)
3954 Hash *node = makeNode(Hash);
3955 Plan *plan = &node->plan;
3957 copy_plan_costsize(plan, lefttree);
3960 * For plausibility, make startup & total costs equal total cost of input
3961 * plan; this only affects EXPLAIN display not decisions.
3963 plan->startup_cost = plan->total_cost;
3964 plan->targetlist = lefttree->targetlist;
3966 plan->lefttree = lefttree;
3967 plan->righttree = NULL;
3969 node->skewTable = skewTable;
3970 node->skewColumn = skewColumn;
3971 node->skewInherit = skewInherit;
3972 node->skewColType = skewColType;
3973 node->skewColTypmod = skewColTypmod;
3979 make_mergejoin(List *tlist,
3984 Oid *mergecollations,
3985 int *mergestrategies,
3986 bool *mergenullsfirst,
3991 MergeJoin *node = makeNode(MergeJoin);
3992 Plan *plan = &node->join.plan;
3994 /* cost should be inserted by caller */
3995 plan->targetlist = tlist;
3996 plan->qual = otherclauses;
3997 plan->lefttree = lefttree;
3998 plan->righttree = righttree;
3999 node->mergeclauses = mergeclauses;
4000 node->mergeFamilies = mergefamilies;
4001 node->mergeCollations = mergecollations;
4002 node->mergeStrategies = mergestrategies;
4003 node->mergeNullsFirst = mergenullsfirst;
4004 node->join.jointype = jointype;
4005 node->join.joinqual = joinclauses;
4011 * make_sort --- basic routine to build a Sort plan node
4013 * Caller must have built the sortColIdx, sortOperators, collations, and
4014 * nullsFirst arrays already.
4015 * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
4018 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
4019 AttrNumber *sortColIdx, Oid *sortOperators,
4020 Oid *collations, bool *nullsFirst,
4021 double limit_tuples)
4023 Sort *node = makeNode(Sort);
4024 Plan *plan = &node->plan;
4025 Path sort_path; /* dummy for result of cost_sort */
4027 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4028 cost_sort(&sort_path, root, NIL,
4029 lefttree->total_cost,
4030 lefttree->plan_rows,
4031 lefttree->plan_width,
4035 plan->startup_cost = sort_path.startup_cost;
4036 plan->total_cost = sort_path.total_cost;
4037 plan->targetlist = lefttree->targetlist;
4039 plan->lefttree = lefttree;
4040 plan->righttree = NULL;
4041 node->numCols = numCols;
4042 node->sortColIdx = sortColIdx;
4043 node->sortOperators = sortOperators;
4044 node->collations = collations;
4045 node->nullsFirst = nullsFirst;
4051 * prepare_sort_from_pathkeys
4052 * Prepare to sort according to given pathkeys
4054 * This is used to set up for both Sort and MergeAppend nodes. It calculates
4055 * the executor's representation of the sort key information, and adjusts the
4056 * plan targetlist if needed to add resjunk sort columns.
4059 * 'lefttree' is the plan node which yields input tuples
4060 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4061 * 'relids' identifies the child relation being sorted, if any
4062 * 'reqColIdx' is NULL or an array of required sort key column numbers
4063 * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
4065 * We must convert the pathkey information into arrays of sort key column
4066 * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
4067 * which is the representation the executor wants. These are returned into
4068 * the output parameters *p_numsortkeys etc.
4070 * When looking for matches to an EquivalenceClass's members, we will only
4071 * consider child EC members if they match 'relids'. This protects against
4072 * possible incorrect matches to child expressions that contain no Vars.
4074 * If reqColIdx isn't NULL then it contains sort key column numbers that
4075 * we should match. This is used when making child plans for a MergeAppend;
4076 * it's an error if we can't match the columns.
4078 * If the pathkeys include expressions that aren't simple Vars, we will
4079 * usually need to add resjunk items to the input plan's targetlist to
4080 * compute these expressions, since the Sort/MergeAppend node itself won't
4081 * do any such calculations. If the input plan type isn't one that can do
4082 * projections, this means adding a Result node just to do the projection.
4083 * However, the caller can pass adjust_tlist_in_place = TRUE to force the
4084 * lefttree tlist to be modified in-place regardless of whether the node type
4085 * can project --- we use this for fixing the tlist of MergeAppend itself.
4087 * Returns the node which is to be the input to the Sort (either lefttree,
4088 * or a Result stacked atop lefttree).
4091 prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4093 const AttrNumber *reqColIdx,
4094 bool adjust_tlist_in_place,
4096 AttrNumber **p_sortColIdx,
4097 Oid **p_sortOperators,
4099 bool **p_nullsFirst)
4101 List *tlist = lefttree->targetlist;
4104 AttrNumber *sortColIdx;
4110 * We will need at most list_length(pathkeys) sort columns; possibly less
4112 numsortkeys = list_length(pathkeys);
4113 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4114 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4115 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4116 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4120 foreach(i, pathkeys)
4122 PathKey *pathkey = (PathKey *) lfirst(i);
4123 EquivalenceClass *ec = pathkey->pk_eclass;
4124 EquivalenceMember *em;
4125 TargetEntry *tle = NULL;
4126 Oid pk_datatype = InvalidOid;
4130 if (ec->ec_has_volatile)
4133 * If the pathkey's EquivalenceClass is volatile, then it must
4134 * have come from an ORDER BY clause, and we have to match it to
4135 * that same targetlist entry.
4137 if (ec->ec_sortref == 0) /* can't happen */
4138 elog(ERROR, "volatile EquivalenceClass has no sortref");
4139 tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
4141 Assert(list_length(ec->ec_members) == 1);
4142 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
4144 else if (reqColIdx != NULL)
4147 * If we are given a sort column number to match, only consider
4148 * the single TLE at that position. It's possible that there is
4149 * no such TLE, in which case fall through and generate a resjunk
4150 * targetentry (we assume this must have happened in the parent
4151 * plan as well). If there is a TLE but it doesn't match the
4152 * pathkey's EC, we do the same, which is probably the wrong thing
4153 * but we'll leave it to caller to complain about the mismatch.
4155 tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
4158 em = find_ec_member_for_tle(ec, tle, relids);
4161 /* found expr at right place in tlist */
4162 pk_datatype = em->em_datatype;
4171 * Otherwise, we can sort by any non-constant expression listed in
4172 * the pathkey's EquivalenceClass. For now, we take the first
4173 * tlist item found in the EC. If there's no match, we'll generate
4174 * a resjunk entry using the first EC member that is an expression
4175 * in the input's vars. (The non-const restriction only matters
4176 * if the EC is below_outer_join; but if it isn't, it won't
4177 * contain consts anyway, else we'd have discarded the pathkey as
4180 * XXX if we have a choice, is there any way of figuring out which
4181 * might be cheapest to execute? (For example, int4lt is likely
4182 * much cheaper to execute than numericlt, but both might appear
4183 * in the same equivalence class...) Not clear that we ever will
4184 * have an interesting choice in practice, so it may not matter.
4188 tle = (TargetEntry *) lfirst(j);
4189 em = find_ec_member_for_tle(ec, tle, relids);
4192 /* found expr already in tlist */
4193 pk_datatype = em->em_datatype;
4203 * No matching tlist item; look for a computable expression. Note
4204 * that we treat Aggrefs as if they were variables; this is
4205 * necessary when attempting to sort the output from an Agg node
4206 * for use in a WindowFunc (since grouping_planner will have
4207 * treated the Aggrefs as variables, too).
4209 Expr *sortexpr = NULL;
4211 foreach(j, ec->ec_members)
4213 EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
4218 * We shouldn't be trying to sort by an equivalence class that
4219 * contains a constant, so no need to consider such cases any
4222 if (em->em_is_const)
4226 * Ignore child members unless they match the rel being
4229 if (em->em_is_child &&
4230 !bms_equal(em->em_relids, relids))
4233 sortexpr = em->em_expr;
4234 exprvars = pull_var_clause((Node *) sortexpr,
4235 PVC_INCLUDE_AGGREGATES,
4236 PVC_INCLUDE_PLACEHOLDERS);
4237 foreach(k, exprvars)
4239 if (!tlist_member_ignore_relabel(lfirst(k), tlist))
4242 list_free(exprvars);
4245 pk_datatype = em->em_datatype;
4246 break; /* found usable expression */
4250 elog(ERROR, "could not find pathkey item to sort");
4253 * Do we need to insert a Result node?
4255 if (!adjust_tlist_in_place &&
4256 !is_projection_capable_plan(lefttree))
4258 /* copy needed so we don't modify input's tlist below */
4259 tlist = copyObject(tlist);
4260 lefttree = (Plan *) make_result(root, tlist, NULL,
4264 /* Don't bother testing is_projection_capable_plan again */
4265 adjust_tlist_in_place = true;
4268 * Add resjunk entry to input's tlist
4270 tle = makeTargetEntry(sortexpr,
4271 list_length(tlist) + 1,
4274 tlist = lappend(tlist, tle);
4275 lefttree->targetlist = tlist; /* just in case NIL before */
4279 * Look up the correct sort operator from the PathKey's slightly
4280 * abstracted representation.
4282 sortop = get_opfamily_member(pathkey->pk_opfamily,
4285 pathkey->pk_strategy);
4286 if (!OidIsValid(sortop)) /* should not happen */
4287 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
4288 pathkey->pk_strategy, pk_datatype, pk_datatype,
4289 pathkey->pk_opfamily);
4291 /* Add the column to the sort arrays */
4292 sortColIdx[numsortkeys] = tle->resno;
4293 sortOperators[numsortkeys] = sortop;
4294 collations[numsortkeys] = ec->ec_collation;
4295 nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
4299 /* Return results */
4300 *p_numsortkeys = numsortkeys;
4301 *p_sortColIdx = sortColIdx;
4302 *p_sortOperators = sortOperators;
4303 *p_collations = collations;
4304 *p_nullsFirst = nullsFirst;
4310 * find_ec_member_for_tle
4311 * Locate an EquivalenceClass member matching the given TLE, if any
4313 * Child EC members are ignored unless they match 'relids'.
4315 static EquivalenceMember *
4316 find_ec_member_for_tle(EquivalenceClass *ec,
4323 /* We ignore binary-compatible relabeling on both ends */
4325 while (tlexpr && IsA(tlexpr, RelabelType))
4326 tlexpr = ((RelabelType *) tlexpr)->arg;
4328 foreach(lc, ec->ec_members)
4330 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
4334 * We shouldn't be trying to sort by an equivalence class that
4335 * contains a constant, so no need to consider such cases any further.
4337 if (em->em_is_const)
4341 * Ignore child members unless they match the rel being sorted.
4343 if (em->em_is_child &&
4344 !bms_equal(em->em_relids, relids))
4347 /* Match if same expression (after stripping relabel) */
4348 emexpr = em->em_expr;
4349 while (emexpr && IsA(emexpr, RelabelType))
4350 emexpr = ((RelabelType *) emexpr)->arg;
4352 if (equal(emexpr, tlexpr))
4360 * make_sort_from_pathkeys
4361 * Create sort plan to sort according to given pathkeys
4363 * 'lefttree' is the node which yields input tuples
4364 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4365 * 'limit_tuples' is the bound on the number of output tuples;
4369 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4370 double limit_tuples)
4373 AttrNumber *sortColIdx;
4378 /* Compute sort column info, and adjust lefttree as needed */
4379 lefttree = prepare_sort_from_pathkeys(root, lefttree, pathkeys,
4389 /* Now build the Sort node */
4390 return make_sort(root, lefttree, numsortkeys,
4391 sortColIdx, sortOperators, collations,
4392 nullsFirst, limit_tuples);
4396 * make_sort_from_sortclauses
4397 * Create sort plan to sort according to given sortclauses
4399 * 'sortcls' is a list of SortGroupClauses
4400 * 'lefttree' is the node which yields input tuples
4403 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
4405 List *sub_tlist = lefttree->targetlist;
4408 AttrNumber *sortColIdx;
4413 /* Convert list-ish representation to arrays wanted by executor */
4414 numsortkeys = list_length(sortcls);
4415 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4416 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4417 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4418 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4423 SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
4424 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
4426 sortColIdx[numsortkeys] = tle->resno;
4427 sortOperators[numsortkeys] = sortcl->sortop;
4428 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4429 nullsFirst[numsortkeys] = sortcl->nulls_first;
4433 return make_sort(root, lefttree, numsortkeys,
4434 sortColIdx, sortOperators, collations,
4439 * make_sort_from_groupcols
4440 * Create sort plan to sort based on grouping columns
4442 * 'groupcls' is the list of SortGroupClauses
4443 * 'grpColIdx' gives the column numbers to use
4445 * This might look like it could be merged with make_sort_from_sortclauses,
4446 * but presently we *must* use the grpColIdx[] array to locate sort columns,
4447 * because the child plan's tlist is not marked with ressortgroupref info
4448 * appropriate to the grouping node. So, only the sort ordering info
4449 * is used from the SortGroupClause entries.
4452 make_sort_from_groupcols(PlannerInfo *root,
4454 AttrNumber *grpColIdx,
4457 List *sub_tlist = lefttree->targetlist;
4460 AttrNumber *sortColIdx;
4465 /* Convert list-ish representation to arrays wanted by executor */
4466 numsortkeys = list_length(groupcls);
4467 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4468 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4469 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4470 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4473 foreach(l, groupcls)
4475 SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
4476 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
4479 elog(ERROR, "could not retrieve tle for sort-from-groupcols");
4481 sortColIdx[numsortkeys] = tle->resno;
4482 sortOperators[numsortkeys] = grpcl->sortop;
4483 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4484 nullsFirst[numsortkeys] = grpcl->nulls_first;
4488 return make_sort(root, lefttree, numsortkeys,
4489 sortColIdx, sortOperators, collations,
4494 make_material(Plan *lefttree)
4496 Material *node = makeNode(Material);
4497 Plan *plan = &node->plan;
4499 /* cost should be inserted by caller */
4500 plan->targetlist = lefttree->targetlist;
4502 plan->lefttree = lefttree;
4503 plan->righttree = NULL;
4509 * materialize_finished_plan: stick a Material node atop a completed plan
4511 * There are a couple of places where we want to attach a Material node
4512 * after completion of subquery_planner(), without any MaterialPath path.
4515 materialize_finished_plan(Plan *subplan)
4518 Path matpath; /* dummy for result of cost_material */
4520 matplan = (Plan *) make_material(subplan);
4523 cost_material(&matpath,
4524 subplan->startup_cost,
4525 subplan->total_cost,
4527 subplan->plan_width);
4528 matplan->startup_cost = matpath.startup_cost;
4529 matplan->total_cost = matpath.total_cost;
4530 matplan->plan_rows = subplan->plan_rows;
4531 matplan->plan_width = subplan->plan_width;
4537 make_agg(PlannerInfo *root, List *tlist, List *qual,
4538 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
4539 int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
4544 Agg *node = makeNode(Agg);
4545 Plan *plan = &node->plan;
4546 Path agg_path; /* dummy for result of cost_agg */
4549 node->aggstrategy = aggstrategy;
4550 node->numCols = numGroupCols;
4551 node->grpColIdx = grpColIdx;
4552 node->grpOperators = grpOperators;
4553 node->numGroups = numGroups;
4555 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4556 cost_agg(&agg_path, root,
4557 aggstrategy, aggcosts,
4558 numGroupCols, numGroups,
4559 lefttree->startup_cost,
4560 lefttree->total_cost,
4561 lefttree->plan_rows);
4562 plan->startup_cost = agg_path.startup_cost;
4563 plan->total_cost = agg_path.total_cost;
4566 * We will produce a single output tuple if not grouping, and a tuple per
4569 if (aggstrategy == AGG_PLAIN)
4570 plan->plan_rows = groupingSets ? list_length(groupingSets) : 1;
4572 plan->plan_rows = numGroups;
4574 node->groupingSets = groupingSets;
4577 * We also need to account for the cost of evaluation of the qual (ie, the
4578 * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge
4579 * anything for Aggref nodes; this is okay since they are really
4580 * comparable to Vars.
4582 * See notes in add_tlist_costs_to_plan about why only make_agg,
4583 * make_windowagg and make_group worry about tlist eval cost.
4587 cost_qual_eval(&qual_cost, qual, root);
4588 plan->startup_cost += qual_cost.startup;
4589 plan->total_cost += qual_cost.startup;
4590 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4592 add_tlist_costs_to_plan(root, plan, tlist);
4595 plan->targetlist = tlist;
4597 plan->lefttree = lefttree;
4598 plan->righttree = NULL;
4604 make_windowagg(PlannerInfo *root, List *tlist,
4605 List *windowFuncs, Index winref,
4606 int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
4607 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
4608 int frameOptions, Node *startOffset, Node *endOffset,
4611 WindowAgg *node = makeNode(WindowAgg);
4612 Plan *plan = &node->plan;
4613 Path windowagg_path; /* dummy for result of cost_windowagg */
4615 node->winref = winref;
4616 node->partNumCols = partNumCols;
4617 node->partColIdx = partColIdx;
4618 node->partOperators = partOperators;
4619 node->ordNumCols = ordNumCols;
4620 node->ordColIdx = ordColIdx;
4621 node->ordOperators = ordOperators;
4622 node->frameOptions = frameOptions;
4623 node->startOffset = startOffset;
4624 node->endOffset = endOffset;
4626 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4627 cost_windowagg(&windowagg_path, root,
4628 windowFuncs, partNumCols, ordNumCols,
4629 lefttree->startup_cost,
4630 lefttree->total_cost,
4631 lefttree->plan_rows);
4632 plan->startup_cost = windowagg_path.startup_cost;
4633 plan->total_cost = windowagg_path.total_cost;
4636 * We also need to account for the cost of evaluation of the tlist.
4638 * See notes in add_tlist_costs_to_plan about why only make_agg,
4639 * make_windowagg and make_group worry about tlist eval cost.
4641 add_tlist_costs_to_plan(root, plan, tlist);
4643 plan->targetlist = tlist;
4644 plan->lefttree = lefttree;
4645 plan->righttree = NULL;
4646 /* WindowAgg nodes never have a qual clause */
4653 make_group(PlannerInfo *root,
4657 AttrNumber *grpColIdx,
4662 Group *node = makeNode(Group);
4663 Plan *plan = &node->plan;
4664 Path group_path; /* dummy for result of cost_group */
4667 node->numCols = numGroupCols;
4668 node->grpColIdx = grpColIdx;
4669 node->grpOperators = grpOperators;
4671 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4672 cost_group(&group_path, root,
4673 numGroupCols, numGroups,
4674 lefttree->startup_cost,
4675 lefttree->total_cost,
4676 lefttree->plan_rows);
4677 plan->startup_cost = group_path.startup_cost;
4678 plan->total_cost = group_path.total_cost;
4680 /* One output tuple per estimated result group */
4681 plan->plan_rows = numGroups;
4684 * We also need to account for the cost of evaluation of the qual (ie, the
4685 * HAVING clause) and the tlist.
4687 * XXX this double-counts the cost of evaluation of any expressions used
4688 * for grouping, since in reality those will have been evaluated at a
4689 * lower plan level and will only be copied by the Group node. Worth
4692 * See notes in add_tlist_costs_to_plan about why only make_agg,
4693 * make_windowagg and make_group worry about tlist eval cost.
4697 cost_qual_eval(&qual_cost, qual, root);
4698 plan->startup_cost += qual_cost.startup;
4699 plan->total_cost += qual_cost.startup;
4700 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4702 add_tlist_costs_to_plan(root, plan, tlist);
4705 plan->targetlist = tlist;
4706 plan->lefttree = lefttree;
4707 plan->righttree = NULL;
4713 * distinctList is a list of SortGroupClauses, identifying the targetlist items
4714 * that should be considered by the Unique filter. The input path must
4715 * already be sorted accordingly.
4718 make_unique(Plan *lefttree, List *distinctList)
4720 Unique *node = makeNode(Unique);
4721 Plan *plan = &node->plan;
4722 int numCols = list_length(distinctList);
4724 AttrNumber *uniqColIdx;
4728 copy_plan_costsize(plan, lefttree);
4731 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4732 * all columns get compared at most of the tuples. (XXX probably this is
4735 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
4738 * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie,
4739 * we assume the filter removes nothing. The caller must alter this if he
4740 * has a better idea.
4743 plan->targetlist = lefttree->targetlist;
4745 plan->lefttree = lefttree;
4746 plan->righttree = NULL;
4749 * convert SortGroupClause list into arrays of attr indexes and equality
4750 * operators, as wanted by executor
4752 Assert(numCols > 0);
4753 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4754 uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4756 foreach(slitem, distinctList)
4758 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4759 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4761 uniqColIdx[keyno] = tle->resno;
4762 uniqOperators[keyno] = sortcl->eqop;
4763 Assert(OidIsValid(uniqOperators[keyno]));
4767 node->numCols = numCols;
4768 node->uniqColIdx = uniqColIdx;
4769 node->uniqOperators = uniqOperators;
4775 make_gather(List *qptlist,
4781 Gather *node = makeNode(Gather);
4782 Plan *plan = &node->plan;
4784 /* cost should be inserted by caller */
4785 plan->targetlist = qptlist;
4786 plan->qual = qpqual;
4787 plan->lefttree = subplan;
4788 plan->righttree = NULL;
4789 node->num_workers = nworkers;
4790 node->single_copy = single_copy;
4796 * distinctList is a list of SortGroupClauses, identifying the targetlist
4797 * items that should be considered by the SetOp filter. The input path must
4798 * already be sorted accordingly.
4801 make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
4802 List *distinctList, AttrNumber flagColIdx, int firstFlag,
4803 long numGroups, double outputRows)
4805 SetOp *node = makeNode(SetOp);
4806 Plan *plan = &node->plan;
4807 int numCols = list_length(distinctList);
4809 AttrNumber *dupColIdx;
4813 copy_plan_costsize(plan, lefttree);
4814 plan->plan_rows = outputRows;
4817 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4818 * all columns get compared at most of the tuples.
4820 plan->total_cost += cpu_operator_cost * lefttree->plan_rows * numCols;
4822 plan->targetlist = lefttree->targetlist;
4824 plan->lefttree = lefttree;
4825 plan->righttree = NULL;
4828 * convert SortGroupClause list into arrays of attr indexes and equality
4829 * operators, as wanted by executor
4831 Assert(numCols > 0);
4832 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4833 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4835 foreach(slitem, distinctList)
4837 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4838 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4840 dupColIdx[keyno] = tle->resno;
4841 dupOperators[keyno] = sortcl->eqop;
4842 Assert(OidIsValid(dupOperators[keyno]));
4847 node->strategy = strategy;
4848 node->numCols = numCols;
4849 node->dupColIdx = dupColIdx;
4850 node->dupOperators = dupOperators;
4851 node->flagColIdx = flagColIdx;
4852 node->firstFlag = firstFlag;
4853 node->numGroups = numGroups;
4860 * Build a LockRows plan node
4863 make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
4865 LockRows *node = makeNode(LockRows);
4866 Plan *plan = &node->plan;
4868 copy_plan_costsize(plan, lefttree);
4870 /* charge cpu_tuple_cost to reflect locking costs (underestimate?) */
4871 plan->total_cost += cpu_tuple_cost * plan->plan_rows;
4873 plan->targetlist = lefttree->targetlist;
4875 plan->lefttree = lefttree;
4876 plan->righttree = NULL;
4878 node->rowMarks = rowMarks;
4879 node->epqParam = epqParam;
4885 * Note: offset_est and count_est are passed in to save having to repeat
4886 * work already done to estimate the values of the limitOffset and limitCount
4887 * expressions. Their values are as returned by preprocess_limit (0 means
4888 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
4889 * with that function!
4892 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
4893 int64 offset_est, int64 count_est)
4895 Limit *node = makeNode(Limit);
4896 Plan *plan = &node->plan;
4898 copy_plan_costsize(plan, lefttree);
4901 * Adjust the output rows count and costs according to the offset/limit.
4902 * This is only a cosmetic issue if we are at top level, but if we are
4903 * building a subquery then it's important to report correct info to the
4906 * When the offset or count couldn't be estimated, use 10% of the
4907 * estimated number of rows emitted from the subplan.
4909 if (offset_est != 0)
4914 offset_rows = (double) offset_est;
4916 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4917 if (offset_rows > plan->plan_rows)
4918 offset_rows = plan->plan_rows;
4919 if (plan->plan_rows > 0)
4920 plan->startup_cost +=
4921 (plan->total_cost - plan->startup_cost)
4922 * offset_rows / plan->plan_rows;
4923 plan->plan_rows -= offset_rows;
4924 if (plan->plan_rows < 1)
4925 plan->plan_rows = 1;
4933 count_rows = (double) count_est;
4935 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4936 if (count_rows > plan->plan_rows)
4937 count_rows = plan->plan_rows;
4938 if (plan->plan_rows > 0)
4939 plan->total_cost = plan->startup_cost +
4940 (plan->total_cost - plan->startup_cost)
4941 * count_rows / plan->plan_rows;
4942 plan->plan_rows = count_rows;
4943 if (plan->plan_rows < 1)
4944 plan->plan_rows = 1;
4947 plan->targetlist = lefttree->targetlist;
4949 plan->lefttree = lefttree;
4950 plan->righttree = NULL;
4952 node->limitOffset = limitOffset;
4953 node->limitCount = limitCount;
4960 * Build a Result plan node
4962 * If we have a subplan, assume that any evaluation costs for the gating qual
4963 * were already factored into the subplan's startup cost, and just copy the
4964 * subplan cost. If there's no subplan, we should include the qual eval
4965 * cost. In either case, tlist eval cost is not to be included here.
4968 make_result(PlannerInfo *root,
4970 Node *resconstantqual,
4973 Result *node = makeNode(Result);
4974 Plan *plan = &node->plan;
4977 copy_plan_costsize(plan, subplan);
4980 plan->startup_cost = 0;
4981 plan->total_cost = cpu_tuple_cost;
4982 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
4983 plan->plan_width = 0; /* XXX is it worth being smarter? */
4984 if (resconstantqual)
4988 cost_qual_eval(&qual_cost, (List *) resconstantqual, root);
4989 /* resconstantqual is evaluated once at startup */
4990 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
4991 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
4995 plan->targetlist = tlist;
4997 plan->lefttree = subplan;
4998 plan->righttree = NULL;
4999 node->resconstantqual = resconstantqual;
5006 * Build a ModifyTable plan node
5008 * Currently, we don't charge anything extra for the actual table modification
5009 * work, nor for the WITH CHECK OPTIONS or RETURNING expressions if any. It
5010 * would only be window dressing, since these are always top-level nodes and
5011 * there is no way for the costs to change any higher-level planning choices.
5012 * But we might want to make it look better sometime.
5015 make_modifytable(PlannerInfo *root,
5016 CmdType operation, bool canSetTag,
5017 Index nominalRelation,
5018 List *resultRelations, List *subplans,
5019 List *withCheckOptionLists, List *returningLists,
5020 List *rowMarks, OnConflictExpr *onconflict, int epqParam)
5022 ModifyTable *node = makeNode(ModifyTable);
5023 Plan *plan = &node->plan;
5025 List *fdw_private_list;
5030 Assert(list_length(resultRelations) == list_length(subplans));
5031 Assert(withCheckOptionLists == NIL ||
5032 list_length(resultRelations) == list_length(withCheckOptionLists));
5033 Assert(returningLists == NIL ||
5034 list_length(resultRelations) == list_length(returningLists));
5037 * Compute cost as sum of subplan costs.
5039 plan->startup_cost = 0;
5040 plan->total_cost = 0;
5041 plan->plan_rows = 0;
5043 foreach(subnode, subplans)
5045 Plan *subplan = (Plan *) lfirst(subnode);
5047 if (subnode == list_head(subplans)) /* first node? */
5048 plan->startup_cost = subplan->startup_cost;
5049 plan->total_cost += subplan->total_cost;
5050 plan->plan_rows += subplan->plan_rows;
5051 total_size += subplan->plan_width * subplan->plan_rows;
5053 if (plan->plan_rows > 0)
5054 plan->plan_width = rint(total_size / plan->plan_rows);
5056 plan->plan_width = 0;
5058 node->plan.lefttree = NULL;
5059 node->plan.righttree = NULL;
5060 node->plan.qual = NIL;
5061 /* setrefs.c will fill in the targetlist, if needed */
5062 node->plan.targetlist = NIL;
5064 node->operation = operation;
5065 node->canSetTag = canSetTag;
5066 node->nominalRelation = nominalRelation;
5067 node->resultRelations = resultRelations;
5068 node->resultRelIndex = -1; /* will be set correctly in setrefs.c */
5069 node->plans = subplans;
5072 node->onConflictAction = ONCONFLICT_NONE;
5073 node->onConflictSet = NIL;
5074 node->onConflictWhere = NULL;
5075 node->arbiterIndexes = NIL;
5076 node->exclRelRTI = 0;
5077 node->exclRelTlist = NIL;
5081 node->onConflictAction = onconflict->action;
5082 node->onConflictSet = onconflict->onConflictSet;
5083 node->onConflictWhere = onconflict->onConflictWhere;
5086 * If a set of unique index inference elements was provided (an
5087 * INSERT...ON CONFLICT "inference specification"), then infer
5088 * appropriate unique indexes (or throw an error if none are
5091 node->arbiterIndexes = infer_arbiter_indexes(root);
5093 node->exclRelRTI = onconflict->exclRelIndex;
5094 node->exclRelTlist = onconflict->exclRelTlist;
5096 node->withCheckOptionLists = withCheckOptionLists;
5097 node->returningLists = returningLists;
5098 node->rowMarks = rowMarks;
5099 node->epqParam = epqParam;
5102 * For each result relation that is a foreign table, allow the FDW to
5103 * construct private plan data, and accumulate it all into a list.
5105 fdw_private_list = NIL;
5107 foreach(lc, resultRelations)
5109 Index rti = lfirst_int(lc);
5110 FdwRoutine *fdwroutine;
5114 * If possible, we want to get the FdwRoutine from our RelOptInfo for
5115 * the table. But sometimes we don't have a RelOptInfo and must get
5116 * it the hard way. (In INSERT, the target relation is not scanned,
5117 * so it's not a baserel; and there are also corner cases for
5118 * updatable views where the target rel isn't a baserel.)
5120 if (rti < root->simple_rel_array_size &&
5121 root->simple_rel_array[rti] != NULL)
5123 RelOptInfo *resultRel = root->simple_rel_array[rti];
5125 fdwroutine = resultRel->fdwroutine;
5129 RangeTblEntry *rte = planner_rt_fetch(rti, root);
5131 Assert(rte->rtekind == RTE_RELATION);
5132 if (rte->relkind == RELKIND_FOREIGN_TABLE)
5133 fdwroutine = GetFdwRoutineByRelId(rte->relid);
5138 if (fdwroutine != NULL &&
5139 fdwroutine->PlanForeignModify != NULL)
5140 fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
5143 fdw_private_list = lappend(fdw_private_list, fdw_private);
5146 node->fdwPrivLists = fdw_private_list;
5152 * is_projection_capable_plan
5153 * Check whether a given Plan node is able to do projection.
5156 is_projection_capable_plan(Plan *plan)
5158 /* Most plan types can project, so just list the ones that can't */
5159 switch (nodeTag(plan))
5171 case T_RecursiveUnion: