PostgreSQL Source Code git master
Loading...
Searching...
No Matches
createplan.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * createplan.c
4 * Routines to create the desired plan for processing a query.
5 * Planning is complete, we just need to convert the selected
6 * Path into a Plan.
7 *
8 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
10 *
11 *
12 * IDENTIFICATION
13 * src/backend/optimizer/plan/createplan.c
14 *
15 *-------------------------------------------------------------------------
16 */
17#include "postgres.h"
18
19#include "access/sysattr.h"
20#include "catalog/pg_class.h"
21#include "foreign/fdwapi.h"
22#include "miscadmin.h"
23#include "nodes/extensible.h"
24#include "nodes/makefuncs.h"
25#include "nodes/nodeFuncs.h"
26#include "optimizer/clauses.h"
27#include "optimizer/cost.h"
28#include "optimizer/optimizer.h"
30#include "optimizer/pathnode.h"
31#include "optimizer/paths.h"
33#include "optimizer/plancat.h"
34#include "optimizer/planmain.h"
35#include "optimizer/prep.h"
37#include "optimizer/subselect.h"
38#include "optimizer/tlist.h"
39#include "parser/parse_clause.h"
40#include "parser/parsetree.h"
42#include "tcop/tcopprot.h"
43#include "utils/lsyscache.h"
44
45
46/*
47 * Flag bits that can appear in the flags argument of create_plan_recurse().
48 * These can be OR-ed together.
49 *
50 * CP_EXACT_TLIST specifies that the generated plan node must return exactly
51 * the tlist specified by the path's pathtarget (this overrides both
52 * CP_SMALL_TLIST and CP_LABEL_TLIST, if those are set). Otherwise, the
53 * plan node is allowed to return just the Vars and PlaceHolderVars needed
54 * to evaluate the pathtarget.
55 *
56 * CP_SMALL_TLIST specifies that a narrower tlist is preferred. This is
57 * passed down by parent nodes such as Sort and Hash, which will have to
58 * store the returned tuples.
59 *
60 * CP_LABEL_TLIST specifies that the plan node must return columns matching
61 * any sortgrouprefs specified in its pathtarget, with appropriate
62 * ressortgroupref labels. This is passed down by parent nodes such as Sort
63 * and Group, which need these values to be available in their inputs.
64 *
65 * CP_IGNORE_TLIST specifies that the caller plans to replace the targetlist,
66 * and therefore it doesn't matter a bit what target list gets generated.
67 */
68#define CP_EXACT_TLIST 0x0001 /* Plan must return specified tlist */
69#define CP_SMALL_TLIST 0x0002 /* Prefer narrower tlists */
70#define CP_LABEL_TLIST 0x0004 /* tlist must contain sortgrouprefs */
71#define CP_IGNORE_TLIST 0x0008 /* caller will replace tlist */
72
73
75 int flags);
77 int flags);
79static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
80static List *get_gating_quals(PlannerInfo *root, List *quals);
84static bool mark_async_capable_plan(Plan *plan, Path *path);
86 int flags);
88 int flags);
93 int flags);
95 int flags);
99 int flags);
100static Plan *inject_projection_plan(Plan *subplan, List *tlist,
101 bool parallel_safe);
104 IncrementalSortPath *best_path, int flags);
112 int flags);
115 int flags);
118 int flags);
120 List *tlist, List *scan_clauses);
122 List *tlist, List *scan_clauses);
124 List *tlist, List *scan_clauses, bool indexonly);
127 List *tlist, List *scan_clauses);
128static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
129 List **qual, List **indexqual, List **indexECs);
132 List *tlist, List *scan_clauses);
135 List *tlist,
139 List *tlist, List *scan_clauses);
141 List *tlist, List *scan_clauses);
143 List *tlist, List *scan_clauses);
145 List *tlist, List *scan_clauses);
147 List *tlist, List *scan_clauses);
149 Path *best_path, List *tlist, List *scan_clauses);
151 List *tlist, List *scan_clauses);
153 List *tlist, List *scan_clauses);
155 List *tlist, List *scan_clauses);
158 List *tlist, List *scan_clauses);
169 IndexOptInfo *index, int indexcol,
170 Node *clause, List *indexcolnos);
171static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
172static List *get_switched_clauses(List *clauses, Relids outerrelids);
173static List *order_qual_clauses(PlannerInfo *root, List *clauses);
174static void copy_generic_path_info(Plan *dest, Path *src);
175static void copy_plan_costsize(Plan *dest, Plan *src);
177 double limit_tuples);
179 List *pathkeys, double limit_tuples);
180static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
183static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
184 Oid indexid, List *indexqual, List *indexqualorig,
185 List *indexorderby, List *indexorderbyorig,
186 List *indexorderbyops,
187 ScanDirection indexscandir);
189 Index scanrelid, Oid indexid,
190 List *indexqual, List *recheckqual,
191 List *indexorderby,
192 List *indextlist,
193 ScanDirection indexscandir);
194static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
195 List *indexqual,
196 List *indexqualorig);
198 List *qpqual,
199 Plan *lefttree,
200 List *bitmapqualorig,
201 Index scanrelid);
202static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
203 List *tidquals);
205 Index scanrelid, List *tidrangequals);
207 List *qpqual,
208 Index scanrelid,
209 Plan *subplan);
211 Index scanrelid, List *functions, bool funcordinality);
213 Index scanrelid, List *values_lists);
215 Index scanrelid, TableFunc *tablefunc);
217 Index scanrelid, int ctePlanId, int cteParam);
219 Index scanrelid, char *enrname);
221 Index scanrelid, int wtParam);
223 Plan *lefttree,
224 Plan *righttree,
225 int wtParam,
226 List *distinctList,
227 Cardinality numGroups);
228static BitmapAnd *make_bitmap_and(List *bitmapplans);
229static BitmapOr *make_bitmap_or(List *bitmapplans);
230static NestLoop *make_nestloop(List *tlist,
231 List *joinclauses, List *otherclauses, List *nestParams,
232 Plan *lefttree, Plan *righttree,
233 JoinType jointype, bool inner_unique);
234static HashJoin *make_hashjoin(List *tlist,
235 List *joinclauses, List *otherclauses,
236 List *hashclauses,
237 List *hashoperators, List *hashcollations,
238 List *hashkeys,
239 Plan *lefttree, Plan *righttree,
240 JoinType jointype, bool inner_unique);
241static Hash *make_hash(Plan *lefttree,
242 List *hashkeys,
243 Oid skewTable,
244 AttrNumber skewColumn,
245 bool skewInherit);
246static MergeJoin *make_mergejoin(List *tlist,
247 List *joinclauses, List *otherclauses,
248 List *mergeclauses,
251 bool *mergereversals,
252 bool *mergenullsfirst,
253 Plan *lefttree, Plan *righttree,
254 JoinType jointype, bool inner_unique,
255 bool skip_mark_restore);
256static Sort *make_sort(Plan *lefttree, int numCols,
257 AttrNumber *sortColIdx, Oid *sortOperators,
258 Oid *collations, bool *nullsFirst);
260 int numCols, int nPresortedCols,
261 AttrNumber *sortColIdx, Oid *sortOperators,
262 Oid *collations, bool *nullsFirst);
263static Plan *prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
264 Relids relids,
265 const AttrNumber *reqColIdx,
267 int *p_numsortkeys,
271 bool **p_nullsFirst);
272static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
273 Relids relids);
275 List *pathkeys, Relids relids, int nPresortedCols);
278 Plan *lefttree);
279static Material *make_material(Plan *lefttree);
280static Memoize *make_memoize(Plan *lefttree, Oid *hashoperators,
281 Oid *collations, List *param_exprs,
282 bool singlerow, bool binary_mode,
283 uint32 est_entries, Bitmapset *keyparamids,
284 Cardinality est_calls,
285 Cardinality est_unique_keys,
286 double est_hit_ratio);
287static WindowAgg *make_windowagg(List *tlist, WindowClause *wc,
290 List *runCondition, List *qual, bool topWindow,
291 Plan *lefttree);
292static Group *make_group(List *tlist, List *qual, int numGroupCols,
294 Plan *lefttree);
295static Unique *make_unique_from_pathkeys(Plan *lefttree,
296 List *pathkeys, int numCols,
297 Relids relids);
299 int nworkers, int rescan_param, bool single_copy, Plan *subplan);
300static SetOp *make_setop(SetOpCmd cmd, SetOpStrategy strategy,
301 List *tlist, Plan *lefttree, Plan *righttree,
302 List *groupList, Cardinality numGroups);
303static LockRows *make_lockrows(Plan *lefttree, List *rowMarks, int epqParam);
304static Result *make_gating_result(List *tlist, Node *resconstantqual,
305 Plan *subplan);
306static Result *make_one_row_result(List *tlist, Node *resconstantqual,
307 RelOptInfo *rel);
308static ProjectSet *make_project_set(List *tlist, Plan *subplan);
310 CmdType operation, bool canSetTag,
311 Index nominalRelation, Index rootRelation,
312 List *resultRelations,
313 List *updateColnosLists,
314 List *withCheckOptionLists, List *returningLists,
315 List *rowMarks, OnConflictExpr *onconflict,
316 List *mergeActionLists, List *mergeJoinConditions,
317 int epqParam);
320
321
322/*
323 * create_plan
324 * Creates the access plan for a query by recursively processing the
325 * desired tree of pathnodes, starting at the node 'best_path'. For
326 * every pathnode found, we create a corresponding plan node containing
327 * appropriate id, target list, and qualification information.
328 *
329 * The tlists and quals in the plan tree are still in planner format,
330 * ie, Vars still correspond to the parser's numbering. This will be
331 * fixed later by setrefs.c.
332 *
333 * best_path is the best access path
334 *
335 * Returns a Plan tree.
336 */
337Plan *
339{
340 Plan *plan;
341
342 /* plan_params should not be in use in current query level */
343 Assert(root->plan_params == NIL);
344
345 /* Initialize this module's workspace in PlannerInfo */
346 root->curOuterRels = NULL;
347 root->curOuterParams = NIL;
348
349 /* Recursively process the path tree, demanding the correct tlist result */
351
352 /*
353 * Make sure the topmost plan node's targetlist exposes the original
354 * column names and other decorative info. Targetlists generated within
355 * the planner don't bother with that stuff, but we must have it on the
356 * top-level tlist seen at execution time. However, ModifyTable plan
357 * nodes don't have a tlist matching the querytree targetlist.
358 */
359 if (!IsA(plan, ModifyTable))
360 apply_tlist_labeling(plan->targetlist, root->processed_tlist);
361
362 /*
363 * Attach any initPlans created in this query level to the topmost plan
364 * node. (In principle the initplans could go in any plan node at or
365 * above where they're referenced, but there seems no reason to put them
366 * any lower than the topmost node for the query level. Also, see
367 * comments for SS_finalize_plan before you try to change this.)
368 */
370
371 /* Check we successfully assigned all NestLoopParams to plan nodes */
372 if (root->curOuterParams != NIL)
373 elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
374
375 /*
376 * Reset plan_params to ensure param IDs used for nestloop params are not
377 * re-used later
378 */
379 root->plan_params = NIL;
380
381 return plan;
382}
383
384/*
385 * create_plan_recurse
386 * Recursive guts of create_plan().
387 */
388static Plan *
390{
391 Plan *plan;
392
393 /* Guard against stack overflow due to overly complex plans */
395
396 switch (best_path->pathtype)
397 {
398 case T_SeqScan:
399 case T_SampleScan:
400 case T_IndexScan:
401 case T_IndexOnlyScan:
402 case T_BitmapHeapScan:
403 case T_TidScan:
404 case T_TidRangeScan:
405 case T_SubqueryScan:
406 case T_FunctionScan:
407 case T_TableFuncScan:
408 case T_ValuesScan:
409 case T_CteScan:
410 case T_WorkTableScan:
412 case T_ForeignScan:
413 case T_CustomScan:
415 break;
416 case T_HashJoin:
417 case T_MergeJoin:
418 case T_NestLoop:
420 (JoinPath *) best_path);
421 break;
422 case T_Append:
425 flags);
426 break;
427 case T_MergeAppend:
430 flags);
431 break;
432 case T_Result:
434 {
437 flags);
438 }
439 else if (IsA(best_path, MinMaxAggPath))
440 {
443 }
444 else if (IsA(best_path, GroupResultPath))
445 {
448 }
449 else
450 {
451 /* Simple RTE_RESULT base relation */
454 }
455 break;
456 case T_ProjectSet:
459 break;
460 case T_Material:
463 flags);
464 break;
465 case T_Memoize:
468 flags);
469 break;
470 case T_Unique:
473 flags);
474 break;
475 case T_Gather:
478 break;
479 case T_Sort:
482 flags);
483 break;
487 flags);
488 break;
489 case T_Group:
491 (GroupPath *) best_path);
492 break;
493 case T_Agg:
497 else
498 {
501 (AggPath *) best_path);
502 }
503 break;
504 case T_WindowAgg:
507 break;
508 case T_SetOp:
511 flags);
512 break;
513 case T_RecursiveUnion:
516 break;
517 case T_LockRows:
520 flags);
521 break;
522 case T_ModifyTable:
525 break;
526 case T_Limit:
529 flags);
530 break;
531 case T_GatherMerge:
534 break;
535 default:
536 elog(ERROR, "unrecognized node type: %d",
537 (int) best_path->pathtype);
538 plan = NULL; /* keep compiler quiet */
539 break;
540 }
541
542 return plan;
543}
544
545/*
546 * create_scan_plan
547 * Create a scan plan for the parent relation of 'best_path'.
548 */
549static Plan *
551{
552 RelOptInfo *rel = best_path->parent;
555 List *tlist;
556 Plan *plan;
557
558 /*
559 * Extract the relevant restriction clauses from the parent relation. The
560 * executor must apply all these restrictions during the scan, except for
561 * pseudoconstants which we'll take care of below.
562 *
563 * If this is a plain indexscan or index-only scan, we need not consider
564 * restriction clauses that are implied by the index's predicate, so use
565 * indrestrictinfo not baserestrictinfo. Note that we can't do that for
566 * bitmap indexscans, since there's not necessarily a single index
567 * involved; but it doesn't matter since create_bitmap_scan_plan() will be
568 * able to get rid of such clauses anyway via predicate proof.
569 */
570 switch (best_path->pathtype)
571 {
572 case T_IndexScan:
573 case T_IndexOnlyScan:
574 scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
575 break;
576 default:
578 break;
579 }
580
581 /*
582 * If this is a parameterized scan, we also need to enforce all the join
583 * clauses available from the outer relation(s).
584 *
585 * For paranoia's sake, don't modify the stored baserestrictinfo list.
586 */
587 if (best_path->param_info)
589 best_path->param_info->ppi_clauses);
590
591 /*
592 * Detect whether we have any pseudoconstant quals to deal with. Then, if
593 * we'll need a gating Result node, it will be able to project, so there
594 * are no requirements on the child's tlist.
595 *
596 * If this replaces a join, it must be a foreign scan or a custom scan,
597 * and the FDW or the custom scan provider would have stored in the best
598 * path the list of RestrictInfo nodes to apply to the join; check against
599 * that list in that case.
600 */
601 if (IS_JOIN_REL(rel))
602 {
604
605 Assert(best_path->pathtype == T_ForeignScan ||
606 best_path->pathtype == T_CustomScan);
607 if (best_path->pathtype == T_ForeignScan)
608 join_clauses = ((ForeignPath *) best_path)->fdw_restrictinfo;
609 else
610 join_clauses = ((CustomPath *) best_path)->custom_restrictinfo;
611
613 }
614 else
616 if (gating_clauses)
617 flags = 0;
618
619 /*
620 * For table scans, rather than using the relation targetlist (which is
621 * only those Vars actually needed by the query), we prefer to generate a
622 * tlist containing all Vars in order. This will allow the executor to
623 * optimize away projection of the table tuples, if possible.
624 *
625 * But if the caller is going to ignore our tlist anyway, then don't
626 * bother generating one at all. We use an exact equality test here, so
627 * that this only applies when CP_IGNORE_TLIST is the only flag set.
628 */
629 if (flags == CP_IGNORE_TLIST)
630 {
631 tlist = NULL;
632 }
633 else if (use_physical_tlist(root, best_path, flags))
634 {
635 if (best_path->pathtype == T_IndexOnlyScan)
636 {
637 /* For index-only scan, the preferred tlist is the index's */
638 tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
639
640 /*
641 * Transfer sortgroupref data to the replacement tlist, if
642 * requested (use_physical_tlist checked that this will work).
643 */
644 if (flags & CP_LABEL_TLIST)
646 }
647 else
648 {
649 tlist = build_physical_tlist(root, rel);
650 if (tlist == NIL)
651 {
652 /* Failed because of dropped cols, so use regular method */
654 }
655 else
656 {
657 /* As above, transfer sortgroupref data to replacement tlist */
658 if (flags & CP_LABEL_TLIST)
660 }
661 }
662 }
663 else
664 {
666 }
667
668 switch (best_path->pathtype)
669 {
670 case T_SeqScan:
672 best_path,
673 tlist,
675 break;
676
677 case T_SampleScan:
679 best_path,
680 tlist,
682 break;
683
684 case T_IndexScan:
687 tlist,
689 false);
690 break;
691
692 case T_IndexOnlyScan:
695 tlist,
697 true);
698 break;
699
700 case T_BitmapHeapScan:
703 tlist,
705 break;
706
707 case T_TidScan:
709 (TidPath *) best_path,
710 tlist,
712 break;
713
714 case T_TidRangeScan:
717 tlist,
719 break;
720
721 case T_SubqueryScan:
724 tlist,
726 break;
727
728 case T_FunctionScan:
730 best_path,
731 tlist,
733 break;
734
735 case T_TableFuncScan:
737 best_path,
738 tlist,
740 break;
741
742 case T_ValuesScan:
744 best_path,
745 tlist,
747 break;
748
749 case T_CteScan:
751 best_path,
752 tlist,
754 break;
755
758 best_path,
759 tlist,
761 break;
762
763 case T_Result:
765 best_path,
766 tlist,
768 break;
769
770 case T_WorkTableScan:
772 best_path,
773 tlist,
775 break;
776
777 case T_ForeignScan:
780 tlist,
782 break;
783
784 case T_CustomScan:
787 tlist,
789 break;
790
791 default:
792 elog(ERROR, "unrecognized node type: %d",
793 (int) best_path->pathtype);
794 plan = NULL; /* keep compiler quiet */
795 break;
796 }
797
798 /*
799 * If there are any pseudoconstant clauses attached to this node, insert a
800 * gating Result node that evaluates the pseudoconstants as one-time
801 * quals.
802 */
803 if (gating_clauses)
805
806 return plan;
807}
808
809/*
810 * Build a target list (ie, a list of TargetEntry) for the Path's output.
811 *
812 * This is almost just make_tlist_from_pathtarget(), but we also have to
813 * deal with replacing nestloop params.
814 */
815static List *
817{
818 List *tlist = NIL;
819 Index *sortgrouprefs = path->pathtarget->sortgrouprefs;
820 int resno = 1;
821 ListCell *v;
822
823 foreach(v, path->pathtarget->exprs)
824 {
825 Node *node = (Node *) lfirst(v);
827
828 /*
829 * If it's a parameterized path, there might be lateral references in
830 * the tlist, which need to be replaced with Params. There's no need
831 * to remake the TargetEntry nodes, so apply this to each list item
832 * separately.
833 */
834 if (path->param_info)
835 node = replace_nestloop_params(root, node);
836
837 tle = makeTargetEntry((Expr *) node,
838 resno,
839 NULL,
840 false);
841 if (sortgrouprefs)
842 tle->ressortgroupref = sortgrouprefs[resno - 1];
843
844 tlist = lappend(tlist, tle);
845 resno++;
846 }
847 return tlist;
848}
849
850/*
851 * use_physical_tlist
852 * Decide whether to use a tlist matching relation structure,
853 * rather than only those Vars actually referenced.
854 */
855static bool
857{
858 RelOptInfo *rel = path->parent;
859 int i;
860 ListCell *lc;
861
862 /*
863 * Forget it if either exact tlist or small tlist is demanded.
864 */
865 if (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST))
866 return false;
867
868 /*
869 * We can do this for real relation scans, subquery scans, function scans,
870 * tablefunc scans, values scans, and CTE scans (but not for, eg, joins).
871 */
872 if (rel->rtekind != RTE_RELATION &&
873 rel->rtekind != RTE_SUBQUERY &&
874 rel->rtekind != RTE_FUNCTION &&
875 rel->rtekind != RTE_TABLEFUNC &&
876 rel->rtekind != RTE_VALUES &&
877 rel->rtekind != RTE_CTE)
878 return false;
879
880 /*
881 * Can't do it with inheritance cases either (mainly because Append
882 * doesn't project; this test may be unnecessary now that
883 * create_append_plan instructs its children to return an exact tlist).
884 */
885 if (rel->reloptkind != RELOPT_BASEREL)
886 return false;
887
888 /*
889 * Also, don't do it to a CustomPath; the premise that we're extracting
890 * columns from a simple physical tuple is unlikely to hold for those.
891 * (When it does make sense, the custom path creator can set up the path's
892 * pathtarget that way.)
893 */
894 if (IsA(path, CustomPath))
895 return false;
896
897 /*
898 * If a bitmap scan's tlist is empty, keep it as-is. This may allow the
899 * executor to skip heap page fetches, and in any case, the benefit of
900 * using a physical tlist instead would be minimal.
901 */
902 if (IsA(path, BitmapHeapPath) &&
903 path->pathtarget->exprs == NIL)
904 return false;
905
906 /*
907 * Can't do it if any system columns or whole-row Vars are requested.
908 * (This could possibly be fixed but would take some fragile assumptions
909 * in setrefs.c, I think.)
910 */
911 for (i = rel->min_attr; i <= 0; i++)
912 {
913 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
914 return false;
915 }
916
917 /*
918 * Can't do it if the rel is required to emit any placeholder expressions,
919 * either.
920 */
921 foreach(lc, root->placeholder_list)
922 {
924
925 if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
926 bms_is_subset(phinfo->ph_eval_at, rel->relids))
927 return false;
928 }
929
930 /*
931 * For an index-only scan, the "physical tlist" is the index's indextlist.
932 * We can only return that without a projection if all the index's columns
933 * are returnable.
934 */
935 if (path->pathtype == T_IndexOnlyScan)
936 {
937 IndexOptInfo *indexinfo = ((IndexPath *) path)->indexinfo;
938
939 for (i = 0; i < indexinfo->ncolumns; i++)
940 {
941 if (!indexinfo->canreturn[i])
942 return false;
943 }
944 }
945
946 /*
947 * Also, can't do it if CP_LABEL_TLIST is specified and path is requested
948 * to emit any sort/group columns that are not simple Vars. (If they are
949 * simple Vars, they should appear in the physical tlist, and
950 * apply_pathtarget_labeling_to_tlist will take care of getting them
951 * labeled again.) We also have to check that no two sort/group columns
952 * are the same Var, else that element of the physical tlist would need
953 * conflicting ressortgroupref labels.
954 */
955 if ((flags & CP_LABEL_TLIST) && path->pathtarget->sortgrouprefs)
956 {
958
959 i = 0;
960 foreach(lc, path->pathtarget->exprs)
961 {
962 Expr *expr = (Expr *) lfirst(lc);
963
964 if (path->pathtarget->sortgrouprefs[i])
965 {
966 if (expr && IsA(expr, Var))
967 {
968 int attno = ((Var *) expr)->varattno;
969
971 if (bms_is_member(attno, sortgroupatts))
972 return false;
974 }
975 else
976 return false;
977 }
978 i++;
979 }
980 }
981
982 return true;
983}
984
985/*
986 * get_gating_quals
987 * See if there are pseudoconstant quals in a node's quals list
988 *
989 * If the node's quals list includes any pseudoconstant quals,
990 * return just those quals.
991 */
992static List *
994{
995 /* No need to look if we know there are no pseudoconstants */
996 if (!root->hasPseudoConstantQuals)
997 return NIL;
998
999 /* Sort into desirable execution order while still in RestrictInfo form */
1000 quals = order_qual_clauses(root, quals);
1001
1002 /* Pull out any pseudoconstant quals from the RestrictInfo list */
1003 return extract_actual_clauses(quals, true);
1004}
1005
1006/*
1007 * create_gating_plan
1008 * Deal with pseudoconstant qual clauses
1009 *
1010 * Add a gating Result node atop the already-built plan.
1011 */
1012static Plan *
1015{
1016 Result *gplan;
1017
1019
1020 /*
1021 * Since we need a Result node anyway, always return the path's requested
1022 * tlist; that's never a wrong choice, even if the parent node didn't ask
1023 * for CP_EXACT_TLIST.
1024 */
1026 (Node *) gating_quals, plan);
1027
1028 /*
1029 * We might have had a trivial Result plan already. Stacking one Result
1030 * atop another is silly, so if that applies, just discard the input plan.
1031 * (We're assuming its targetlist is uninteresting; it should be either
1032 * the same as the result of build_path_tlist, or a simplified version.
1033 * However, we preserve the set of relids that it purports to scan and
1034 * attribute that to our replacement Result instead, and likewise for the
1035 * result_type.)
1036 */
1037 if (IsA(plan, Result))
1038 {
1039 Result *rplan = (Result *) plan;
1040
1041 gplan->plan.lefttree = NULL;
1042 gplan->relids = rplan->relids;
1043 gplan->result_type = rplan->result_type;
1044 }
1045
1046 /*
1047 * Notice that we don't change cost or size estimates when doing gating.
1048 * The costs of qual eval were already included in the subplan's cost.
1049 * Leaving the size alone amounts to assuming that the gating qual will
1050 * succeed, which is the conservative estimate for planning upper queries.
1051 * We certainly don't want to assume the output size is zero (unless the
1052 * gating qual is actually constant FALSE, and that case is dealt with in
1053 * clausesel.c). Interpolating between the two cases is silly, because it
1054 * doesn't reflect what will really happen at runtime, and besides which
1055 * in most cases we have only a very bad idea of the probability of the
1056 * gating qual being true.
1057 */
1058 copy_plan_costsize(&gplan->plan, plan);
1059
1060 /* Gating quals could be unsafe, so better use the Path's safety flag */
1061 gplan->plan.parallel_safe = path->parallel_safe;
1062
1063 return &gplan->plan;
1064}
1065
1066/*
1067 * create_join_plan
1068 * Create a join plan for 'best_path' and (recursively) plans for its
1069 * inner and outer paths.
1070 */
1071static Plan *
1073{
1074 Plan *plan;
1076
1077 switch (best_path->path.pathtype)
1078 {
1079 case T_MergeJoin:
1081 (MergePath *) best_path);
1082 break;
1083 case T_HashJoin:
1085 (HashPath *) best_path);
1086 break;
1087 case T_NestLoop:
1089 (NestPath *) best_path);
1090 break;
1091 default:
1092 elog(ERROR, "unrecognized node type: %d",
1093 (int) best_path->path.pathtype);
1094 plan = NULL; /* keep compiler quiet */
1095 break;
1096 }
1097
1098 /*
1099 * If there are any pseudoconstant clauses attached to this node, insert a
1100 * gating Result node that evaluates the pseudoconstants as one-time
1101 * quals.
1102 */
1103 gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
1104 if (gating_clauses)
1107
1108#ifdef NOT_USED
1109
1110 /*
1111 * * Expensive function pullups may have pulled local predicates * into
1112 * this path node. Put them in the qpqual of the plan node. * JMH,
1113 * 6/15/92
1114 */
1119#endif
1120
1121 return plan;
1122}
1123
1124/*
1125 * mark_async_capable_plan
1126 * Check whether the Plan node created from a Path node is async-capable,
1127 * and if so, mark the Plan node as such and return true, otherwise
1128 * return false.
1129 */
1130static bool
1132{
1133 switch (nodeTag(path))
1134 {
1135 case T_SubqueryScanPath:
1136 {
1138
1139 /*
1140 * If the generated plan node includes a gating Result node,
1141 * we can't execute it asynchronously.
1142 */
1143 if (IsA(plan, Result))
1144 return false;
1145
1146 /*
1147 * If a SubqueryScan node atop of an async-capable plan node
1148 * is deletable, consider it as async-capable.
1149 */
1152 ((SubqueryScanPath *) path)->subpath))
1153 break;
1154 return false;
1155 }
1156 case T_ForeignPath:
1157 {
1158 FdwRoutine *fdwroutine = path->parent->fdwroutine;
1159
1160 /*
1161 * If the generated plan node includes a gating Result node,
1162 * we can't execute it asynchronously.
1163 */
1164 if (IsA(plan, Result))
1165 return false;
1166
1167 Assert(fdwroutine != NULL);
1168 if (fdwroutine->IsForeignPathAsyncCapable != NULL &&
1169 fdwroutine->IsForeignPathAsyncCapable((ForeignPath *) path))
1170 break;
1171 return false;
1172 }
1173 case T_ProjectionPath:
1174
1175 /*
1176 * If the generated plan node includes a Result node for the
1177 * projection, we can't execute it asynchronously.
1178 */
1179 if (IsA(plan, Result))
1180 return false;
1181
1182 /*
1183 * create_projection_plan() would have pulled up the subplan, so
1184 * check the capability using the subpath.
1185 */
1187 ((ProjectionPath *) path)->subpath))
1188 return true;
1189 return false;
1190 default:
1191 return false;
1192 }
1193
1194 plan->async_capable = true;
1195
1196 return true;
1197}
1198
1199/*
1200 * create_append_plan
1201 * Create an Append plan for 'best_path' and (recursively) plans
1202 * for its subpaths.
1203 *
1204 * Returns a Plan node.
1205 */
1206static Plan *
1208{
1209 Append *plan;
1210 List *tlist = build_path_tlist(root, &best_path->path);
1211 int orig_tlist_length = list_length(tlist);
1212 bool tlist_was_changed = false;
1213 List *pathkeys = best_path->path.pathkeys;
1214 List *subplans = NIL;
1215 ListCell *subpaths;
1216 int nasyncplans = 0;
1217 RelOptInfo *rel = best_path->path.parent;
1218 int nodenumsortkeys = 0;
1222 bool *nodeNullsFirst = NULL;
1223 bool consider_async = false;
1224
1225 /*
1226 * The subpaths list could be empty, if every child was proven empty by
1227 * constraint exclusion. In that case generate a dummy plan that returns
1228 * no rows.
1229 *
1230 * Note that an AppendPath with no members is also generated in certain
1231 * cases where there was no appending construct at all, but we know the
1232 * relation is empty (see set_dummy_rel_pathlist and mark_dummy_rel).
1233 */
1234 if (best_path->subpaths == NIL)
1235 {
1236 /* Generate a Result plan with constant-FALSE gating qual */
1237 Plan *plan;
1238
1239 plan = (Plan *) make_one_row_result(tlist,
1240 (Node *) list_make1(makeBoolConst(false,
1241 false)),
1242 best_path->path.parent);
1243
1245
1246 return plan;
1247 }
1248
1249 /*
1250 * Otherwise build an Append plan. Note that if there's just one child,
1251 * the Append is pretty useless; but we wait till setrefs.c to get rid of
1252 * it. Doing so here doesn't work because the varno of the child scan
1253 * plan won't match the parent-rel Vars it'll be asked to emit.
1254 *
1255 * We don't have the actual creation of the Append node split out into a
1256 * separate make_xxx function. This is because we want to run
1257 * prepare_sort_from_pathkeys on it before we do so on the individual
1258 * child plans, to make cross-checking the sort info easier.
1259 */
1260 plan = makeNode(Append);
1261 plan->plan.targetlist = tlist;
1262 plan->plan.qual = NIL;
1263 plan->plan.lefttree = NULL;
1264 plan->plan.righttree = NULL;
1265 plan->apprelids = rel->relids;
1266
1267 if (pathkeys != NIL)
1268 {
1269 /*
1270 * Compute sort column info, and adjust the Append's tlist as needed.
1271 * Because we pass adjust_tlist_in_place = true, we may ignore the
1272 * function result; it must be the same plan node. However, we then
1273 * need to detect whether any tlist entries were added.
1274 */
1275 (void) prepare_sort_from_pathkeys((Plan *) plan, pathkeys,
1276 best_path->path.parent->relids,
1277 NULL,
1278 true,
1284 tlist_was_changed = (orig_tlist_length != list_length(plan->plan.targetlist));
1285 }
1286
1287 /* If appropriate, consider async append */
1288 consider_async = (enable_async_append && pathkeys == NIL &&
1289 !best_path->path.parallel_safe &&
1290 list_length(best_path->subpaths) > 1);
1291
1292 /* Build the plan for each child */
1293 foreach(subpaths, best_path->subpaths)
1294 {
1295 Path *subpath = (Path *) lfirst(subpaths);
1296 Plan *subplan;
1297
1298 /* Must insist that all children return the same tlist */
1300
1301 /*
1302 * For ordered Appends, we must insert a Sort node if subplan isn't
1303 * sufficiently ordered.
1304 */
1305 if (pathkeys != NIL)
1306 {
1307 int numsortkeys;
1308 AttrNumber *sortColIdx;
1309 Oid *sortOperators;
1310 Oid *collations;
1311 bool *nullsFirst;
1312 int presorted_keys;
1313
1314 /*
1315 * Compute sort column info, and adjust subplan's tlist as needed.
1316 * We must apply prepare_sort_from_pathkeys even to subplans that
1317 * don't need an explicit sort, to make sure they are returning
1318 * the same sort key columns the Append expects.
1319 */
1320 subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1321 subpath->parent->relids,
1323 false,
1324 &numsortkeys,
1325 &sortColIdx,
1326 &sortOperators,
1327 &collations,
1328 &nullsFirst);
1329
1330 /*
1331 * Check that we got the same sort key information. We just
1332 * Assert that the sortops match, since those depend only on the
1333 * pathkeys; but it seems like a good idea to check the sort
1334 * column numbers explicitly, to ensure the tlists match up.
1335 */
1337 if (memcmp(sortColIdx, nodeSortColIdx,
1338 numsortkeys * sizeof(AttrNumber)) != 0)
1339 elog(ERROR, "Append child's targetlist doesn't match Append");
1340 Assert(memcmp(sortOperators, nodeSortOperators,
1341 numsortkeys * sizeof(Oid)) == 0);
1342 Assert(memcmp(collations, nodeCollations,
1343 numsortkeys * sizeof(Oid)) == 0);
1345 numsortkeys * sizeof(bool)) == 0);
1346
1347 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1348 if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
1349 &presorted_keys))
1350 {
1351 Plan *sort_plan;
1352
1353 /*
1354 * We choose to use incremental sort if it is enabled and
1355 * there are presorted keys; otherwise we use full sort.
1356 */
1357 if (enable_incremental_sort && presorted_keys > 0)
1358 {
1359 sort_plan = (Plan *)
1360 make_incrementalsort(subplan, numsortkeys, presorted_keys,
1361 sortColIdx, sortOperators,
1362 collations, nullsFirst);
1363
1366 pathkeys,
1367 best_path->limit_tuples);
1368 }
1369 else
1370 {
1371 sort_plan = (Plan *) make_sort(subplan, numsortkeys,
1372 sortColIdx, sortOperators,
1373 collations, nullsFirst);
1374
1376 best_path->limit_tuples);
1377 }
1378
1379 subplan = sort_plan;
1380 }
1381 }
1382
1383 /* If needed, check to see if subplan can be executed asynchronously */
1385 {
1386 Assert(subplan->async_capable);
1387 ++nasyncplans;
1388 }
1389
1390 subplans = lappend(subplans, subplan);
1391 }
1392
1393 /* Set below if we find quals that we can use to run-time prune */
1394 plan->part_prune_index = -1;
1395
1396 /*
1397 * If any quals exist, they may be useful to perform further partition
1398 * pruning during execution. Gather information needed by the executor to
1399 * do partition pruning.
1400 */
1402 {
1403 List *prunequal;
1404
1406
1407 if (best_path->path.param_info)
1408 {
1409 List *prmquals = best_path->path.param_info->ppi_clauses;
1410
1413 (Node *) prmquals);
1414
1416 }
1417
1418 if (prunequal != NIL)
1419 plan->part_prune_index = make_partition_pruneinfo(root, rel,
1420 best_path->subpaths,
1421 prunequal);
1422 }
1423
1424 plan->appendplans = subplans;
1425 plan->nasyncplans = nasyncplans;
1426 plan->first_partial_plan = best_path->first_partial_path;
1427
1429
1430 /*
1431 * If prepare_sort_from_pathkeys added sort columns, but we were told to
1432 * produce either the exact tlist or a narrow tlist, we should get rid of
1433 * the sort columns again. We must inject a projection node to do so.
1434 */
1435 if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
1436 {
1437 tlist = list_copy_head(plan->plan.targetlist, orig_tlist_length);
1438 return inject_projection_plan((Plan *) plan, tlist,
1439 plan->plan.parallel_safe);
1440 }
1441 else
1442 return (Plan *) plan;
1443}
1444
1445/*
1446 * create_merge_append_plan
1447 * Create a MergeAppend plan for 'best_path' and (recursively) plans
1448 * for its subpaths.
1449 *
1450 * Returns a Plan node.
1451 */
1452static Plan *
1454 int flags)
1455{
1457 Plan *plan = &node->plan;
1458 List *tlist = build_path_tlist(root, &best_path->path);
1459 int orig_tlist_length = list_length(tlist);
1460 bool tlist_was_changed;
1461 List *pathkeys = best_path->path.pathkeys;
1462 List *subplans = NIL;
1463 ListCell *subpaths;
1464 RelOptInfo *rel = best_path->path.parent;
1465
1466 /*
1467 * We don't have the actual creation of the MergeAppend node split out
1468 * into a separate make_xxx function. This is because we want to run
1469 * prepare_sort_from_pathkeys on it before we do so on the individual
1470 * child plans, to make cross-checking the sort info easier.
1471 */
1473 plan->targetlist = tlist;
1474 plan->qual = NIL;
1475 plan->lefttree = NULL;
1476 plan->righttree = NULL;
1477 node->apprelids = rel->relids;
1478
1479 /*
1480 * Compute sort column info, and adjust MergeAppend's tlist as needed.
1481 * Because we pass adjust_tlist_in_place = true, we may ignore the
1482 * function result; it must be the same plan node. However, we then need
1483 * to detect whether any tlist entries were added.
1484 */
1486 best_path->path.parent->relids,
1487 NULL,
1488 true,
1489 &node->numCols,
1490 &node->sortColIdx,
1491 &node->sortOperators,
1492 &node->collations,
1493 &node->nullsFirst);
1495
1496 /*
1497 * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
1498 * even to subplans that don't need an explicit sort, to make sure they
1499 * are returning the same sort key columns the MergeAppend expects.
1500 */
1501 foreach(subpaths, best_path->subpaths)
1502 {
1503 Path *subpath = (Path *) lfirst(subpaths);
1504 Plan *subplan;
1505 int numsortkeys;
1506 AttrNumber *sortColIdx;
1507 Oid *sortOperators;
1508 Oid *collations;
1509 bool *nullsFirst;
1510 int presorted_keys;
1511
1512 /* Build the child plan */
1513 /* Must insist that all children return the same tlist */
1515
1516 /* Compute sort column info, and adjust subplan's tlist as needed */
1517 subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1518 subpath->parent->relids,
1519 node->sortColIdx,
1520 false,
1521 &numsortkeys,
1522 &sortColIdx,
1523 &sortOperators,
1524 &collations,
1525 &nullsFirst);
1526
1527 /*
1528 * Check that we got the same sort key information. We just Assert
1529 * that the sortops match, since those depend only on the pathkeys;
1530 * but it seems like a good idea to check the sort column numbers
1531 * explicitly, to ensure the tlists really do match up.
1532 */
1533 Assert(numsortkeys == node->numCols);
1534 if (memcmp(sortColIdx, node->sortColIdx,
1535 numsortkeys * sizeof(AttrNumber)) != 0)
1536 elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
1537 Assert(memcmp(sortOperators, node->sortOperators,
1538 numsortkeys * sizeof(Oid)) == 0);
1539 Assert(memcmp(collations, node->collations,
1540 numsortkeys * sizeof(Oid)) == 0);
1541 Assert(memcmp(nullsFirst, node->nullsFirst,
1542 numsortkeys * sizeof(bool)) == 0);
1543
1544 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1545 if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
1546 &presorted_keys))
1547 {
1548 Plan *sort_plan;
1549
1550 /*
1551 * We choose to use incremental sort if it is enabled and there
1552 * are presorted keys; otherwise we use full sort.
1553 */
1554 if (enable_incremental_sort && presorted_keys > 0)
1555 {
1556 sort_plan = (Plan *)
1557 make_incrementalsort(subplan, numsortkeys, presorted_keys,
1558 sortColIdx, sortOperators,
1559 collations, nullsFirst);
1560
1563 pathkeys,
1564 best_path->limit_tuples);
1565 }
1566 else
1567 {
1568 sort_plan = (Plan *) make_sort(subplan, numsortkeys,
1569 sortColIdx, sortOperators,
1570 collations, nullsFirst);
1571
1573 best_path->limit_tuples);
1574 }
1575
1576 subplan = sort_plan;
1577 }
1578
1579 subplans = lappend(subplans, subplan);
1580 }
1581
1582 /* Set below if we find quals that we can use to run-time prune */
1583 node->part_prune_index = -1;
1584
1585 /*
1586 * If any quals exist, they may be useful to perform further partition
1587 * pruning during execution. Gather information needed by the executor to
1588 * do partition pruning.
1589 */
1591 {
1592 List *prunequal;
1593
1595
1596 /* We don't currently generate any parameterized MergeAppend paths */
1597 Assert(best_path->path.param_info == NULL);
1598
1599 if (prunequal != NIL)
1601 best_path->subpaths,
1602 prunequal);
1603 }
1604
1605 node->mergeplans = subplans;
1606
1607 /*
1608 * If prepare_sort_from_pathkeys added sort columns, but we were told to
1609 * produce either the exact tlist or a narrow tlist, we should get rid of
1610 * the sort columns again. We must inject a projection node to do so.
1611 */
1612 if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
1613 {
1614 tlist = list_copy_head(plan->targetlist, orig_tlist_length);
1615 return inject_projection_plan(plan, tlist, plan->parallel_safe);
1616 }
1617 else
1618 return plan;
1619}
1620
1621/*
1622 * create_group_result_plan
1623 * Create a Result plan for 'best_path'.
1624 * This is only used for degenerate grouping cases.
1625 *
1626 * Returns a Plan node.
1627 */
1628static Result *
1630{
1631 Result *plan;
1632 List *tlist;
1633 List *quals;
1634
1635 tlist = build_path_tlist(root, &best_path->path);
1636
1637 /* best_path->quals is just bare clauses */
1638 quals = order_qual_clauses(root, best_path->quals);
1639
1640 plan = make_one_row_result(tlist, (Node *) quals, best_path->path.parent);
1641
1643
1644 return plan;
1645}
1646
1647/*
1648 * create_project_set_plan
1649 * Create a ProjectSet plan for 'best_path'.
1650 *
1651 * Returns a Plan node.
1652 */
1653static ProjectSet *
1655{
1657 Plan *subplan;
1658 List *tlist;
1659
1660 /* Since we intend to project, we don't need to constrain child tlist */
1661 subplan = create_plan_recurse(root, best_path->subpath, 0);
1662
1663 tlist = build_path_tlist(root, &best_path->path);
1664
1665 plan = make_project_set(tlist, subplan);
1666
1668
1669 return plan;
1670}
1671
1672/*
1673 * create_material_plan
1674 * Create a Material plan for 'best_path' and (recursively) plans
1675 * for its subpaths.
1676 *
1677 * Returns a Plan node.
1678 */
1679static Material *
1681{
1682 Material *plan;
1683 Plan *subplan;
1684
1685 /*
1686 * We don't want any excess columns in the materialized tuples, so request
1687 * a smaller tlist. Otherwise, since Material doesn't project, tlist
1688 * requirements pass through.
1689 */
1690 subplan = create_plan_recurse(root, best_path->subpath,
1691 flags | CP_SMALL_TLIST);
1692
1693 plan = make_material(subplan);
1694
1696
1697 return plan;
1698}
1699
1700/*
1701 * create_memoize_plan
1702 * Create a Memoize plan for 'best_path' and (recursively) plans for its
1703 * subpaths.
1704 *
1705 * Returns a Plan node.
1706 */
1707static Memoize *
1709{
1710 Memoize *plan;
1711 Bitmapset *keyparamids;
1712 Plan *subplan;
1713 Oid *operators;
1714 Oid *collations;
1715 List *param_exprs = NIL;
1716 ListCell *lc;
1717 ListCell *lc2;
1718 int nkeys;
1719 int i;
1720
1721 subplan = create_plan_recurse(root, best_path->subpath,
1722 flags | CP_SMALL_TLIST);
1723
1724 param_exprs = (List *) replace_nestloop_params(root, (Node *)
1725 best_path->param_exprs);
1726
1727 nkeys = list_length(param_exprs);
1728 Assert(nkeys > 0);
1729 operators = palloc(nkeys * sizeof(Oid));
1730 collations = palloc(nkeys * sizeof(Oid));
1731
1732 i = 0;
1733 forboth(lc, param_exprs, lc2, best_path->hash_operators)
1734 {
1735 Expr *param_expr = (Expr *) lfirst(lc);
1736 Oid opno = lfirst_oid(lc2);
1737
1738 operators[i] = opno;
1739 collations[i] = exprCollation((Node *) param_expr);
1740 i++;
1741 }
1742
1743 keyparamids = pull_paramids((Expr *) param_exprs);
1744
1745 plan = make_memoize(subplan, operators, collations, param_exprs,
1746 best_path->singlerow, best_path->binary_mode,
1747 best_path->est_entries, keyparamids, best_path->est_calls,
1748 best_path->est_unique_keys, best_path->est_hit_ratio);
1749
1751
1752 return plan;
1753}
1754
1755/*
1756 * create_gather_plan
1757 *
1758 * Create a Gather plan for 'best_path' and (recursively) plans
1759 * for its subpaths.
1760 */
1761static Gather *
1763{
1765 Plan *subplan;
1766 List *tlist;
1767
1768 /*
1769 * Push projection down to the child node. That way, the projection work
1770 * is parallelized, and there can be no system columns in the result (they
1771 * can't travel through a tuple queue because it uses MinimalTuple
1772 * representation).
1773 */
1774 subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1775
1776 tlist = build_path_tlist(root, &best_path->path);
1777
1778 gather_plan = make_gather(tlist,
1779 NIL,
1780 best_path->num_workers,
1782 best_path->single_copy,
1783 subplan);
1784
1786
1787 /* use parallel mode for parallel plans. */
1788 root->glob->parallelModeNeeded = true;
1789
1790 return gather_plan;
1791}
1792
1793/*
1794 * create_gather_merge_plan
1795 *
1796 * Create a Gather Merge plan for 'best_path' and (recursively)
1797 * plans for its subpaths.
1798 */
1799static GatherMerge *
1801{
1803 Plan *subplan;
1804 List *pathkeys = best_path->path.pathkeys;
1805 List *tlist = build_path_tlist(root, &best_path->path);
1806
1807 /* As with Gather, project away columns in the workers. */
1808 subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1809
1810 /* Create a shell for a GatherMerge plan. */
1812 gm_plan->plan.targetlist = tlist;
1813 gm_plan->num_workers = best_path->num_workers;
1815
1816 /* Assign the rescan Param. */
1817 gm_plan->rescan_param = assign_special_exec_param(root);
1818
1819 /* Gather Merge is pointless with no pathkeys; use Gather instead. */
1820 Assert(pathkeys != NIL);
1821
1822 /* Compute sort column info, and adjust subplan's tlist as needed */
1823 subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1824 best_path->subpath->parent->relids,
1825 gm_plan->sortColIdx,
1826 false,
1827 &gm_plan->numCols,
1828 &gm_plan->sortColIdx,
1829 &gm_plan->sortOperators,
1830 &gm_plan->collations,
1831 &gm_plan->nullsFirst);
1832
1833 /*
1834 * All gather merge paths should have already guaranteed the necessary
1835 * sort order. See create_gather_merge_path.
1836 */
1837 Assert(pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys));
1838
1839 /* Now insert the subplan under GatherMerge. */
1840 gm_plan->plan.lefttree = subplan;
1841
1842 /* use parallel mode for parallel plans. */
1843 root->glob->parallelModeNeeded = true;
1844
1845 return gm_plan;
1846}
1847
1848/*
1849 * create_projection_plan
1850 *
1851 * Create a plan tree to do a projection step and (recursively) plans
1852 * for its subpaths. We may need a Result node for the projection,
1853 * but sometimes we can just let the subplan do the work.
1854 */
1855static Plan *
1857{
1858 Plan *plan;
1859 Plan *subplan;
1860 List *tlist;
1861 bool needs_result_node = false;
1862
1863 /*
1864 * Convert our subpath to a Plan and determine whether we need a Result
1865 * node.
1866 *
1867 * In most cases where we don't need to project, create_projection_path
1868 * will have set dummypp, but not always. First, some createplan.c
1869 * routines change the tlists of their nodes. (An example is that
1870 * create_merge_append_plan might add resjunk sort columns to a
1871 * MergeAppend.) Second, create_projection_path has no way of knowing
1872 * what path node will be placed on top of the projection path and
1873 * therefore can't predict whether it will require an exact tlist. For
1874 * both of these reasons, we have to recheck here.
1875 */
1876 if (use_physical_tlist(root, &best_path->path, flags))
1877 {
1878 /*
1879 * Our caller doesn't really care what tlist we return, so we don't
1880 * actually need to project. However, we may still need to ensure
1881 * proper sortgroupref labels, if the caller cares about those.
1882 */
1883 subplan = create_plan_recurse(root, best_path->subpath, 0);
1884 tlist = subplan->targetlist;
1885 if (flags & CP_LABEL_TLIST)
1887 best_path->path.pathtarget);
1888 }
1889 else if (is_projection_capable_path(best_path->subpath))
1890 {
1891 /*
1892 * Our caller requires that we return the exact tlist, but no separate
1893 * result node is needed because the subpath is projection-capable.
1894 * Tell create_plan_recurse that we're going to ignore the tlist it
1895 * produces.
1896 */
1897 subplan = create_plan_recurse(root, best_path->subpath,
1900 tlist = build_path_tlist(root, &best_path->path);
1901 }
1902 else
1903 {
1904 /*
1905 * It looks like we need a result node, unless by good fortune the
1906 * requested tlist is exactly the one the child wants to produce.
1907 */
1908 subplan = create_plan_recurse(root, best_path->subpath, 0);
1909 tlist = build_path_tlist(root, &best_path->path);
1910 needs_result_node = !tlist_same_exprs(tlist, subplan->targetlist);
1911 }
1912
1913 /*
1914 * If we make a different decision about whether to include a Result node
1915 * than create_projection_path did, we'll have made slightly wrong cost
1916 * estimates; but label the plan with the cost estimates we actually used,
1917 * not "corrected" ones. (XXX this could be cleaned up if we moved more
1918 * of the sortcolumn setup logic into Path creation, but that would add
1919 * expense to creating Paths we might end up not using.)
1920 */
1921 if (!needs_result_node)
1922 {
1923 /* Don't need a separate Result, just assign tlist to subplan */
1924 plan = subplan;
1925 plan->targetlist = tlist;
1926
1927 /* Label plan with the estimated costs we actually used */
1928 plan->startup_cost = best_path->path.startup_cost;
1929 plan->total_cost = best_path->path.total_cost;
1930 plan->plan_rows = best_path->path.rows;
1931 plan->plan_width = best_path->path.pathtarget->width;
1932 plan->parallel_safe = best_path->path.parallel_safe;
1933 /* ... but don't change subplan's parallel_aware flag */
1934 }
1935 else
1936 {
1937 plan = (Plan *) make_gating_result(tlist, NULL, subplan);
1938
1940 }
1941
1942 return plan;
1943}
1944
1945/*
1946 * inject_projection_plan
1947 * Insert a Result node to do a projection step.
1948 *
1949 * This is used in a few places where we decide on-the-fly that we need a
1950 * projection step as part of the tree generated for some Path node.
1951 * We should try to get rid of this in favor of doing it more honestly.
1952 *
1953 * One reason it's ugly is we have to be told the right parallel_safe marking
1954 * to apply (since the tlist might be unsafe even if the child plan is safe).
1955 */
1956static Plan *
1957inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
1958{
1959 Plan *plan;
1960
1961 plan = (Plan *) make_gating_result(tlist, NULL, subplan);
1962
1963 /*
1964 * In principle, we should charge tlist eval cost plus cpu_per_tuple per
1965 * row for the Result node. But the former has probably been factored in
1966 * already and the latter was not accounted for during Path construction,
1967 * so being formally correct might just make the EXPLAIN output look less
1968 * consistent not more so. Hence, just copy the subplan's cost.
1969 */
1970 copy_plan_costsize(plan, subplan);
1971 plan->parallel_safe = parallel_safe;
1972
1973 return plan;
1974}
1975
1976/*
1977 * change_plan_targetlist
1978 * Externally available wrapper for inject_projection_plan.
1979 *
1980 * This is meant for use by FDW plan-generation functions, which might
1981 * want to adjust the tlist computed by some subplan tree. In general,
1982 * a Result node is needed to compute the new tlist, but we can optimize
1983 * some cases.
1984 *
1985 * In most cases, tlist_parallel_safe can just be passed as the parallel_safe
1986 * flag of the FDW's own Path node.
1987 */
1988Plan *
1990{
1991 /*
1992 * If the top plan node can't do projections and its existing target list
1993 * isn't already what we need, we need to add a Result node to help it
1994 * along.
1995 */
1996 if (!is_projection_capable_plan(subplan) &&
1997 !tlist_same_exprs(tlist, subplan->targetlist))
1998 subplan = inject_projection_plan(subplan, tlist,
1999 subplan->parallel_safe &&
2001 else
2002 {
2003 /* Else we can just replace the plan node's tlist */
2004 subplan->targetlist = tlist;
2006 }
2007 return subplan;
2008}
2009
2010/*
2011 * create_sort_plan
2012 *
2013 * Create a Sort plan for 'best_path' and (recursively) plans
2014 * for its subpaths.
2015 */
2016static Sort *
2018{
2019 Sort *plan;
2020 Plan *subplan;
2021
2022 /*
2023 * We don't want any excess columns in the sorted tuples, so request a
2024 * smaller tlist. Otherwise, since Sort doesn't project, tlist
2025 * requirements pass through.
2026 */
2027 subplan = create_plan_recurse(root, best_path->subpath,
2028 flags | CP_SMALL_TLIST);
2029
2030 /*
2031 * make_sort_from_pathkeys indirectly calls find_ec_member_matching_expr,
2032 * which will ignore any child EC members that don't belong to the given
2033 * relids. Thus, if this sort path is based on a child relation, we must
2034 * pass its relids.
2035 */
2036 plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys,
2037 IS_OTHER_REL(best_path->subpath->parent) ?
2038 best_path->path.parent->relids : NULL);
2039
2041
2042 return plan;
2043}
2044
2045/*
2046 * create_incrementalsort_plan
2047 *
2048 * Do the same as create_sort_plan, but create IncrementalSort plan.
2049 */
2050static IncrementalSort *
2052 int flags)
2053{
2055 Plan *subplan;
2056
2057 /* See comments in create_sort_plan() above */
2058 subplan = create_plan_recurse(root, best_path->spath.subpath,
2059 flags | CP_SMALL_TLIST);
2061 best_path->spath.path.pathkeys,
2062 IS_OTHER_REL(best_path->spath.subpath->parent) ?
2063 best_path->spath.path.parent->relids : NULL,
2064 best_path->nPresortedCols);
2065
2066 copy_generic_path_info(&plan->sort.plan, (Path *) best_path);
2067
2068 return plan;
2069}
2070
2071/*
2072 * create_group_plan
2073 *
2074 * Create a Group plan for 'best_path' and (recursively) plans
2075 * for its subpaths.
2076 */
2077static Group *
2079{
2080 Group *plan;
2081 Plan *subplan;
2082 List *tlist;
2083 List *quals;
2084
2085 /*
2086 * Group can project, so no need to be terribly picky about child tlist,
2087 * but we do need grouping columns to be available
2088 */
2089 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2090
2091 tlist = build_path_tlist(root, &best_path->path);
2092
2093 quals = order_qual_clauses(root, best_path->qual);
2094
2095 plan = make_group(tlist,
2096 quals,
2097 list_length(best_path->groupClause),
2098 extract_grouping_cols(best_path->groupClause,
2099 subplan->targetlist),
2100 extract_grouping_ops(best_path->groupClause),
2102 subplan->targetlist),
2103 subplan);
2104
2106
2107 return plan;
2108}
2109
2110/*
2111 * create_unique_plan
2112 *
2113 * Create a Unique plan for 'best_path' and (recursively) plans
2114 * for its subpaths.
2115 */
2116static Unique *
2118{
2119 Unique *plan;
2120 Plan *subplan;
2121
2122 /*
2123 * Unique doesn't project, so tlist requirements pass through; moreover we
2124 * need grouping columns to be labeled.
2125 */
2126 subplan = create_plan_recurse(root, best_path->subpath,
2127 flags | CP_LABEL_TLIST);
2128
2129 /*
2130 * make_unique_from_pathkeys calls find_ec_member_matching_expr, which
2131 * will ignore any child EC members that don't belong to the given relids.
2132 * Thus, if this unique path is based on a child relation, we must pass
2133 * its relids.
2134 */
2136 best_path->path.pathkeys,
2137 best_path->numkeys,
2138 IS_OTHER_REL(best_path->path.parent) ?
2139 best_path->path.parent->relids : NULL);
2140
2142
2143 return plan;
2144}
2145
2146/*
2147 * create_agg_plan
2148 *
2149 * Create an Agg plan for 'best_path' and (recursively) plans
2150 * for its subpaths.
2151 */
2152static Agg *
2154{
2155 Agg *plan;
2156 Plan *subplan;
2157 List *tlist;
2158 List *quals;
2159
2160 /*
2161 * Agg can project, so no need to be terribly picky about child tlist, but
2162 * we do need grouping columns to be available
2163 */
2164 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2165
2166 tlist = build_path_tlist(root, &best_path->path);
2167
2168 quals = order_qual_clauses(root, best_path->qual);
2169
2170 plan = make_agg(tlist, quals,
2171 best_path->aggstrategy,
2172 best_path->aggsplit,
2173 list_length(best_path->groupClause),
2174 extract_grouping_cols(best_path->groupClause,
2175 subplan->targetlist),
2176 extract_grouping_ops(best_path->groupClause),
2178 subplan->targetlist),
2179 NIL,
2180 NIL,
2181 best_path->numGroups,
2182 best_path->transitionSpace,
2183 subplan);
2184
2186
2187 return plan;
2188}
2189
2190/*
2191 * Given a groupclause for a collection of grouping sets, produce the
2192 * corresponding groupColIdx.
2193 *
2194 * root->grouping_map maps the tleSortGroupRef to the actual column position in
2195 * the input tuple. So we get the ref from the entries in the groupclause and
2196 * look them up there.
2197 */
2198static AttrNumber *
2200{
2201 AttrNumber *grouping_map = root->grouping_map;
2203 ListCell *lc;
2204 int i;
2205
2207
2209
2210 i = 0;
2211 foreach(lc, groupClause)
2212 {
2213 SortGroupClause *clause = lfirst(lc);
2214
2216 }
2217
2218 return new_grpColIdx;
2219}
2220
2221/*
2222 * create_groupingsets_plan
2223 * Create a plan for 'best_path' and (recursively) plans
2224 * for its subpaths.
2225 *
2226 * What we emit is an Agg plan with some vestigial Agg and Sort nodes
2227 * hanging off the side. The top Agg implements the last grouping set
2228 * specified in the GroupingSetsPath, and any additional grouping sets
2229 * each give rise to a subsidiary Agg and Sort node in the top Agg's
2230 * "chain" list. These nodes don't participate in the plan directly,
2231 * but they are a convenient way to represent the required data for
2232 * the extra steps.
2233 *
2234 * Returns a Plan node.
2235 */
2236static Plan *
2238{
2239 Agg *plan;
2240 Plan *subplan;
2241 List *rollups = best_path->rollups;
2243 int maxref;
2244 List *chain;
2245 ListCell *lc;
2246
2247 /* Shouldn't get here without grouping sets */
2248 Assert(root->parse->groupingSets);
2249 Assert(rollups != NIL);
2250
2251 /*
2252 * Agg can project, so no need to be terribly picky about child tlist, but
2253 * we do need grouping columns to be available
2254 */
2255 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2256
2257 /*
2258 * Compute the mapping from tleSortGroupRef to column index in the child's
2259 * tlist. First, identify max SortGroupRef in groupClause, for array
2260 * sizing.
2261 */
2262 maxref = 0;
2263 foreach(lc, root->processed_groupClause)
2264 {
2266
2267 if (gc->tleSortGroupRef > maxref)
2269 }
2270
2271 grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
2272
2273 /* Now look up the column numbers in the child's tlist */
2274 foreach(lc, root->processed_groupClause)
2275 {
2278
2279 grouping_map[gc->tleSortGroupRef] = tle->resno;
2280 }
2281
2282 /*
2283 * During setrefs.c, we'll need the grouping_map to fix up the cols lists
2284 * in GroupingFunc nodes. Save it for setrefs.c to use.
2285 */
2286 Assert(root->grouping_map == NULL);
2287 root->grouping_map = grouping_map;
2288
2289 /*
2290 * Generate the side nodes that describe the other sort and group
2291 * operations besides the top one. Note that we don't worry about putting
2292 * accurate cost estimates in the side nodes; only the topmost Agg node's
2293 * costs will be shown by EXPLAIN.
2294 */
2295 chain = NIL;
2296 if (list_length(rollups) > 1)
2297 {
2298 bool is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
2299
2300 for_each_from(lc, rollups, 1)
2301 {
2304 Plan *sort_plan = NULL;
2305 Plan *agg_plan;
2307
2308 new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
2309
2310 if (!rollup->is_hashed && !is_first_sort)
2311 {
2312 sort_plan = (Plan *)
2313 make_sort_from_groupcols(rollup->groupClause,
2315 subplan);
2316 }
2317
2318 if (!rollup->is_hashed)
2319 is_first_sort = false;
2320
2321 if (rollup->is_hashed)
2322 strat = AGG_HASHED;
2323 else if (linitial(rollup->gsets) == NIL)
2324 strat = AGG_PLAIN;
2325 else
2326 strat = AGG_SORTED;
2327
2328 agg_plan = (Plan *) make_agg(NIL,
2329 NIL,
2330 strat,
2332 list_length((List *) linitial(rollup->gsets)),
2334 extract_grouping_ops(rollup->groupClause),
2335 extract_grouping_collations(rollup->groupClause, subplan->targetlist),
2336 rollup->gsets,
2337 NIL,
2338 rollup->numGroups,
2339 best_path->transitionSpace,
2340 sort_plan);
2341
2342 /*
2343 * Remove stuff we don't need to avoid bloating debug output.
2344 */
2345 if (sort_plan)
2346 {
2347 sort_plan->targetlist = NIL;
2348 sort_plan->lefttree = NULL;
2349 }
2350
2351 chain = lappend(chain, agg_plan);
2352 }
2353 }
2354
2355 /*
2356 * Now make the real Agg node
2357 */
2358 {
2359 RollupData *rollup = linitial(rollups);
2361 int numGroupCols;
2362
2363 top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
2364
2366
2368 best_path->qual,
2369 best_path->aggstrategy,
2373 extract_grouping_ops(rollup->groupClause),
2374 extract_grouping_collations(rollup->groupClause, subplan->targetlist),
2375 rollup->gsets,
2376 chain,
2377 rollup->numGroups,
2378 best_path->transitionSpace,
2379 subplan);
2380
2381 /* Copy cost data from Path to Plan */
2382 copy_generic_path_info(&plan->plan, &best_path->path);
2383 }
2384
2385 return (Plan *) plan;
2386}
2387
2388/*
2389 * create_minmaxagg_plan
2390 *
2391 * Create a Result plan for 'best_path' and (recursively) plans
2392 * for its subpaths.
2393 */
2394static Result *
2396{
2397 Result *plan;
2398 List *tlist;
2399 ListCell *lc;
2400
2401 /* Prepare an InitPlan for each aggregate's subquery. */
2402 foreach(lc, best_path->mmaggregates)
2403 {
2405 PlannerInfo *subroot = mminfo->subroot;
2406 Query *subparse = subroot->parse;
2407 Plan *plan;
2408
2409 /*
2410 * Generate the plan for the subquery. We already have a Path, but we
2411 * have to convert it to a Plan and attach a LIMIT node above it.
2412 * Since we are entering a different planner context (subroot),
2413 * recurse to create_plan not create_plan_recurse.
2414 */
2415 plan = create_plan(subroot, mminfo->path);
2416
2417 plan = (Plan *) make_limit(plan,
2418 subparse->limitOffset,
2419 subparse->limitCount,
2420 subparse->limitOption,
2421 0, NULL, NULL, NULL);
2422
2423 /* Must apply correct cost/width data to Limit node */
2424 plan->disabled_nodes = mminfo->path->disabled_nodes;
2425 plan->startup_cost = mminfo->path->startup_cost;
2426 plan->total_cost = mminfo->pathcost;
2427 plan->plan_rows = 1;
2428 plan->plan_width = mminfo->path->pathtarget->width;
2429 plan->parallel_aware = false;
2430 plan->parallel_safe = mminfo->path->parallel_safe;
2431
2432 /* Convert the plan into an InitPlan in the outer query. */
2433 SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
2434 }
2435
2436 /* Generate the output plan --- basically just a Result */
2437 tlist = build_path_tlist(root, &best_path->path);
2438
2439 plan = make_one_row_result(tlist, (Node *) best_path->quals,
2440 best_path->path.parent);
2441 plan->result_type = RESULT_TYPE_MINMAX;
2442
2444
2445 /*
2446 * During setrefs.c, we'll need to replace references to the Agg nodes
2447 * with InitPlan output params. (We can't just do that locally in the
2448 * MinMaxAgg node, because path nodes above here may have Agg references
2449 * as well.) Save the mmaggregates list to tell setrefs.c to do that.
2450 */
2451 Assert(root->minmax_aggs == NIL);
2452 root->minmax_aggs = best_path->mmaggregates;
2453
2454 return plan;
2455}
2456
2457/*
2458 * create_windowagg_plan
2459 *
2460 * Create a WindowAgg plan for 'best_path' and (recursively) plans
2461 * for its subpaths.
2462 */
2463static WindowAgg *
2465{
2466 WindowAgg *plan;
2467 WindowClause *wc = best_path->winclause;
2469 int numOrder = list_length(wc->orderClause);
2470 Plan *subplan;
2471 List *tlist;
2472 int partNumCols;
2476 int ordNumCols;
2480 ListCell *lc;
2481
2482 /*
2483 * Choice of tlist here is motivated by the fact that WindowAgg will be
2484 * storing the input rows of window frames in a tuplestore; it therefore
2485 * behooves us to request a small tlist to avoid wasting space. We do of
2486 * course need grouping columns to be available.
2487 */
2488 subplan = create_plan_recurse(root, best_path->subpath,
2490
2491 tlist = build_path_tlist(root, &best_path->path);
2492
2493 /*
2494 * Convert SortGroupClause lists into arrays of attr indexes and equality
2495 * operators, as wanted by executor.
2496 */
2500
2501 partNumCols = 0;
2502 foreach(lc, wc->partitionClause)
2503 {
2506
2507 Assert(OidIsValid(sgc->eqop));
2508 partColIdx[partNumCols] = tle->resno;
2509 partOperators[partNumCols] = sgc->eqop;
2510 partCollations[partNumCols] = exprCollation((Node *) tle->expr);
2511 partNumCols++;
2512 }
2513
2517
2518 ordNumCols = 0;
2519 foreach(lc, wc->orderClause)
2520 {
2523
2524 Assert(OidIsValid(sgc->eqop));
2525 ordColIdx[ordNumCols] = tle->resno;
2526 ordOperators[ordNumCols] = sgc->eqop;
2527 ordCollations[ordNumCols] = exprCollation((Node *) tle->expr);
2528 ordNumCols++;
2529 }
2530
2531 /* And finally we can make the WindowAgg node */
2532 plan = make_windowagg(tlist,
2533 wc,
2534 partNumCols,
2535 partColIdx,
2538 ordNumCols,
2539 ordColIdx,
2542 best_path->runCondition,
2543 best_path->qual,
2544 best_path->topwindow,
2545 subplan);
2546
2548
2549 return plan;
2550}
2551
2552/*
2553 * create_setop_plan
2554 *
2555 * Create a SetOp plan for 'best_path' and (recursively) plans
2556 * for its subpaths.
2557 */
2558static SetOp *
2560{
2561 SetOp *plan;
2562 List *tlist = build_path_tlist(root, &best_path->path);
2563 Plan *leftplan;
2564 Plan *rightplan;
2565
2566 /*
2567 * SetOp doesn't project, so tlist requirements pass through; moreover we
2568 * need grouping columns to be labeled.
2569 */
2571 flags | CP_LABEL_TLIST);
2573 flags | CP_LABEL_TLIST);
2574
2575 plan = make_setop(best_path->cmd,
2576 best_path->strategy,
2577 tlist,
2578 leftplan,
2579 rightplan,
2580 best_path->groupList,
2581 best_path->numGroups);
2582
2584
2585 return plan;
2586}
2587
2588/*
2589 * create_recursiveunion_plan
2590 *
2591 * Create a RecursiveUnion plan for 'best_path' and (recursively) plans
2592 * for its subpaths.
2593 */
2594static RecursiveUnion *
2596{
2598 Plan *leftplan;
2599 Plan *rightplan;
2600 List *tlist;
2601
2602 /* Need both children to produce same tlist, so force it */
2605
2606 tlist = build_path_tlist(root, &best_path->path);
2607
2608 plan = make_recursive_union(tlist,
2609 leftplan,
2610 rightplan,
2611 best_path->wtParam,
2612 best_path->distinctList,
2613 best_path->numGroups);
2614
2616
2617 return plan;
2618}
2619
2620/*
2621 * create_lockrows_plan
2622 *
2623 * Create a LockRows plan for 'best_path' and (recursively) plans
2624 * for its subpaths.
2625 */
2626static LockRows *
2628 int flags)
2629{
2630 LockRows *plan;
2631 Plan *subplan;
2632
2633 /* LockRows doesn't project, so tlist requirements pass through */
2634 subplan = create_plan_recurse(root, best_path->subpath, flags);
2635
2636 plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
2637
2639
2640 return plan;
2641}
2642
2643/*
2644 * create_modifytable_plan
2645 * Create a ModifyTable plan for 'best_path'.
2646 *
2647 * Returns a Plan node.
2648 */
2649static ModifyTable *
2651{
2653 Path *subpath = best_path->subpath;
2654 Plan *subplan;
2655
2656 /* Subplan must produce exactly the specified tlist */
2658
2659 /* Transfer resname/resjunk labeling, too, to keep executor happy */
2660 apply_tlist_labeling(subplan->targetlist, root->processed_tlist);
2661
2663 subplan,
2664 best_path->operation,
2665 best_path->canSetTag,
2666 best_path->nominalRelation,
2667 best_path->rootRelation,
2668 best_path->resultRelations,
2669 best_path->updateColnosLists,
2670 best_path->withCheckOptionLists,
2671 best_path->returningLists,
2672 best_path->rowMarks,
2673 best_path->onconflict,
2674 best_path->mergeActionLists,
2675 best_path->mergeJoinConditions,
2676 best_path->epqParam);
2677
2678 copy_generic_path_info(&plan->plan, &best_path->path);
2679
2680 return plan;
2681}
2682
2683/*
2684 * create_limit_plan
2685 *
2686 * Create a Limit plan for 'best_path' and (recursively) plans
2687 * for its subpaths.
2688 */
2689static Limit *
2691{
2692 Limit *plan;
2693 Plan *subplan;
2694 int numUniqkeys = 0;
2698
2699 /* Limit doesn't project, so tlist requirements pass through */
2700 subplan = create_plan_recurse(root, best_path->subpath, flags);
2701
2702 /* Extract information necessary for comparing rows for WITH TIES. */
2703 if (best_path->limitOption == LIMIT_OPTION_WITH_TIES)
2704 {
2705 Query *parse = root->parse;
2706 ListCell *l;
2707
2708 numUniqkeys = list_length(parse->sortClause);
2710 uniqOperators = (Oid *) palloc(numUniqkeys * sizeof(Oid));
2711 uniqCollations = (Oid *) palloc(numUniqkeys * sizeof(Oid));
2712
2713 numUniqkeys = 0;
2714 foreach(l, parse->sortClause)
2715 {
2718
2719 uniqColIdx[numUniqkeys] = tle->resno;
2722 numUniqkeys++;
2723 }
2724 }
2725
2726 plan = make_limit(subplan,
2727 best_path->limitOffset,
2728 best_path->limitCount,
2729 best_path->limitOption,
2731
2733
2734 return plan;
2735}
2736
2737
2738/*****************************************************************************
2739 *
2740 * BASE-RELATION SCAN METHODS
2741 *
2742 *****************************************************************************/
2743
2744
2745/*
2746 * create_seqscan_plan
2747 * Returns a seqscan plan for the base relation scanned by 'best_path'
2748 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2749 */
2750static SeqScan *
2752 List *tlist, List *scan_clauses)
2753{
2755 Index scan_relid = best_path->parent->relid;
2756
2757 /* it should be a base rel... */
2758 Assert(scan_relid > 0);
2759 Assert(best_path->parent->rtekind == RTE_RELATION);
2760
2761 /* Sort clauses into best execution order */
2763
2764 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2766
2767 /* Replace any outer-relation variables with nestloop params */
2768 if (best_path->param_info)
2769 {
2770 scan_clauses = (List *)
2772 }
2773
2774 scan_plan = make_seqscan(tlist,
2776 scan_relid);
2777
2779
2780 return scan_plan;
2781}
2782
2783/*
2784 * create_samplescan_plan
2785 * Returns a samplescan plan for the base relation scanned by 'best_path'
2786 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2787 */
2788static SampleScan *
2790 List *tlist, List *scan_clauses)
2791{
2793 Index scan_relid = best_path->parent->relid;
2796
2797 /* it should be a base rel with a tablesample clause... */
2798 Assert(scan_relid > 0);
2800 Assert(rte->rtekind == RTE_RELATION);
2801 tsc = rte->tablesample;
2802 Assert(tsc != NULL);
2803
2804 /* Sort clauses into best execution order */
2806
2807 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2809
2810 /* Replace any outer-relation variables with nestloop params */
2811 if (best_path->param_info)
2812 {
2813 scan_clauses = (List *)
2817 }
2818
2819 scan_plan = make_samplescan(tlist,
2821 scan_relid,
2822 tsc);
2823
2825
2826 return scan_plan;
2827}
2828
2829/*
2830 * create_indexscan_plan
2831 * Returns an indexscan plan for the base relation scanned by 'best_path'
2832 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2833 *
2834 * We use this for both plain IndexScans and IndexOnlyScans, because the
2835 * qual preprocessing work is the same for both. Note that the caller tells
2836 * us which to build --- we don't look at best_path->path.pathtype, because
2837 * create_bitmap_subplan needs to be able to override the prior decision.
2838 */
2839static Scan *
2842 List *tlist,
2844 bool indexonly)
2845{
2846 Scan *scan_plan;
2847 List *indexclauses = best_path->indexclauses;
2848 List *indexorderbys = best_path->indexorderbys;
2849 Index baserelid = best_path->path.parent->relid;
2850 IndexOptInfo *indexinfo = best_path->indexinfo;
2851 Oid indexoid = indexinfo->indexoid;
2852 List *qpqual;
2856 List *indexorderbyops = NIL;
2857 ListCell *l;
2858
2859 /* it should be a base rel... */
2860 Assert(baserelid > 0);
2861 Assert(best_path->path.parent->rtekind == RTE_RELATION);
2862 /* check the scan direction is valid */
2863 Assert(best_path->indexscandir == ForwardScanDirection ||
2864 best_path->indexscandir == BackwardScanDirection);
2865
2866 /*
2867 * Extract the index qual expressions (stripped of RestrictInfos) from the
2868 * IndexClauses list, and prepare a copy with index Vars substituted for
2869 * table Vars. (This step also does replace_nestloop_params on the
2870 * fixed_indexquals.)
2871 */
2875
2876 /*
2877 * Likewise fix up index attr references in the ORDER BY expressions.
2878 */
2880
2881 /*
2882 * The qpqual list must contain all restrictions not automatically handled
2883 * by the index, other than pseudoconstant clauses which will be handled
2884 * by a separate gating plan node. All the predicates in the indexquals
2885 * will be checked (either by the index itself, or by nodeIndexscan.c),
2886 * but if there are any "special" operators involved then they must be
2887 * included in qpqual. The upshot is that qpqual must contain
2888 * scan_clauses minus whatever appears in indexquals.
2889 *
2890 * is_redundant_with_indexclauses() detects cases where a scan clause is
2891 * present in the indexclauses list or is generated from the same
2892 * EquivalenceClass as some indexclause, and is therefore redundant with
2893 * it, though not equal. (The latter happens when indxpath.c prefers a
2894 * different derived equality than what generate_join_implied_equalities
2895 * picked for a parameterized scan's ppi_clauses.) Note that it will not
2896 * match to lossy index clauses, which is critical because we have to
2897 * include the original clause in qpqual in that case.
2898 *
2899 * In some situations (particularly with OR'd index conditions) we may
2900 * have scan_clauses that are not equal to, but are logically implied by,
2901 * the index quals; so we also try a predicate_implied_by() check to see
2902 * if we can discard quals that way. (predicate_implied_by assumes its
2903 * first input contains only immutable functions, so we have to check
2904 * that.)
2905 *
2906 * Note: if you change this bit of code you should also look at
2907 * extract_nonindex_conditions() in costsize.c.
2908 */
2909 qpqual = NIL;
2910 foreach(l, scan_clauses)
2911 {
2913
2914 if (rinfo->pseudoconstant)
2915 continue; /* we may drop pseudoconstants here */
2916 if (is_redundant_with_indexclauses(rinfo, indexclauses))
2917 continue; /* dup or derived from same EquivalenceClass */
2918 if (!contain_mutable_functions((Node *) rinfo->clause) &&
2920 false))
2921 continue; /* provably implied by indexquals */
2922 qpqual = lappend(qpqual, rinfo);
2923 }
2924
2925 /* Sort clauses into best execution order */
2927
2928 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2930
2931 /*
2932 * We have to replace any outer-relation variables with nestloop params in
2933 * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
2934 * annoying to have to do this separately from the processing in
2935 * fix_indexqual_references --- rethink this when generalizing the inner
2936 * indexscan support. But note we can't really do this earlier because
2937 * it'd break the comparisons to predicates above ... (or would it? Those
2938 * wouldn't have outer refs)
2939 */
2940 if (best_path->path.param_info)
2941 {
2944 qpqual = (List *)
2946 indexorderbys = (List *)
2947 replace_nestloop_params(root, (Node *) indexorderbys);
2948 }
2949
2950 /*
2951 * If there are ORDER BY expressions, look up the sort operators for their
2952 * result datatypes.
2953 */
2954 if (indexorderbys)
2955 {
2957 *exprCell;
2958
2959 /*
2960 * PathKey contains OID of the btree opfamily we're sorting by, but
2961 * that's not quite enough because we need the expression's datatype
2962 * to look up the sort operator in the operator family.
2963 */
2964 Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
2965 forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
2966 {
2968 Node *expr = (Node *) lfirst(exprCell);
2969 Oid exprtype = exprType(expr);
2970 Oid sortop;
2971
2972 /* Get sort operator from opfamily */
2973 sortop = get_opfamily_member_for_cmptype(pathkey->pk_opfamily,
2974 exprtype,
2975 exprtype,
2976 pathkey->pk_cmptype);
2977 if (!OidIsValid(sortop))
2978 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2979 pathkey->pk_cmptype, exprtype, exprtype, pathkey->pk_opfamily);
2980 indexorderbyops = lappend_oid(indexorderbyops, sortop);
2981 }
2982 }
2983
2984 /*
2985 * For an index-only scan, we must mark indextlist entries as resjunk if
2986 * they are columns that the index AM can't return; this cues setrefs.c to
2987 * not generate references to those columns.
2988 */
2989 if (indexonly)
2990 {
2991 int i = 0;
2992
2993 foreach(l, indexinfo->indextlist)
2994 {
2996
2997 indextle->resjunk = !indexinfo->canreturn[i];
2998 i++;
2999 }
3000 }
3001
3002 /* Finally ready to build the plan node */
3003 if (indexonly)
3004 scan_plan = (Scan *) make_indexonlyscan(tlist,
3005 qpqual,
3006 baserelid,
3007 indexoid,
3011 indexinfo->indextlist,
3012 best_path->indexscandir);
3013 else
3014 scan_plan = (Scan *) make_indexscan(tlist,
3015 qpqual,
3016 baserelid,
3017 indexoid,
3021 indexorderbys,
3022 indexorderbyops,
3023 best_path->indexscandir);
3024
3026
3027 return scan_plan;
3028}
3029
3030/*
3031 * create_bitmap_scan_plan
3032 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
3033 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3034 */
3035static BitmapHeapScan *
3038 List *tlist,
3040{
3041 Index baserelid = best_path->path.parent->relid;
3043 List *bitmapqualorig;
3044 List *indexquals;
3045 List *indexECs;
3046 List *qpqual;
3047 ListCell *l;
3049
3050 /* it should be a base rel... */
3051 Assert(baserelid > 0);
3052 Assert(best_path->path.parent->rtekind == RTE_RELATION);
3053
3054 /* Process the bitmapqual tree into a Plan tree and qual lists */
3056 &bitmapqualorig, &indexquals,
3057 &indexECs);
3058
3059 if (best_path->path.parallel_aware)
3061
3062 /*
3063 * The qpqual list must contain all restrictions not automatically handled
3064 * by the index, other than pseudoconstant clauses which will be handled
3065 * by a separate gating plan node. All the predicates in the indexquals
3066 * will be checked (either by the index itself, or by
3067 * nodeBitmapHeapscan.c), but if there are any "special" operators
3068 * involved then they must be added to qpqual. The upshot is that qpqual
3069 * must contain scan_clauses minus whatever appears in indexquals.
3070 *
3071 * This loop is similar to the comparable code in create_indexscan_plan(),
3072 * but with some differences because it has to compare the scan clauses to
3073 * stripped (no RestrictInfos) indexquals. See comments there for more
3074 * info.
3075 *
3076 * In normal cases simple equal() checks will be enough to spot duplicate
3077 * clauses, so we try that first. We next see if the scan clause is
3078 * redundant with any top-level indexqual by virtue of being generated
3079 * from the same EC. After that, try predicate_implied_by().
3080 *
3081 * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
3082 * useful for getting rid of qpquals that are implied by index predicates,
3083 * because the predicate conditions are included in the "indexquals"
3084 * returned by create_bitmap_subplan(). Bitmap scans have to do it that
3085 * way because predicate conditions need to be rechecked if the scan
3086 * becomes lossy, so they have to be included in bitmapqualorig.
3087 */
3088 qpqual = NIL;
3089 foreach(l, scan_clauses)
3090 {
3092 Node *clause = (Node *) rinfo->clause;
3093
3094 if (rinfo->pseudoconstant)
3095 continue; /* we may drop pseudoconstants here */
3096 if (list_member(indexquals, clause))
3097 continue; /* simple duplicate */
3098 if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
3099 continue; /* derived from same EquivalenceClass */
3100 if (!contain_mutable_functions(clause) &&
3101 predicate_implied_by(list_make1(clause), indexquals, false))
3102 continue; /* provably implied by indexquals */
3103 qpqual = lappend(qpqual, rinfo);
3104 }
3105
3106 /* Sort clauses into best execution order */
3108
3109 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3111
3112 /*
3113 * When dealing with special operators, we will at this point have
3114 * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
3115 * 'em from bitmapqualorig, since there's no point in making the tests
3116 * twice.
3117 */
3118 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
3119
3120 /*
3121 * We have to replace any outer-relation variables with nestloop params in
3122 * the qpqual and bitmapqualorig expressions. (This was already done for
3123 * expressions attached to plan nodes in the bitmapqualplan tree.)
3124 */
3125 if (best_path->path.param_info)
3126 {
3127 qpqual = (List *)
3129 bitmapqualorig = (List *)
3130 replace_nestloop_params(root, (Node *) bitmapqualorig);
3131 }
3132
3133 /* Finally ready to build the plan node */
3135 qpqual,
3137 bitmapqualorig,
3138 baserelid);
3139
3140 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3141
3142 return scan_plan;
3143}
3144
3145/*
3146 * Given a bitmapqual tree, generate the Plan tree that implements it
3147 *
3148 * As byproducts, we also return in *qual and *indexqual the qual lists
3149 * (in implicit-AND form, without RestrictInfos) describing the original index
3150 * conditions and the generated indexqual conditions. (These are the same in
3151 * simple cases, but when special index operators are involved, the former
3152 * list includes the special conditions while the latter includes the actual
3153 * indexable conditions derived from them.) Both lists include partial-index
3154 * predicates, because we have to recheck predicates as well as index
3155 * conditions if the bitmap scan becomes lossy.
3156 *
3157 * In addition, we return a list of EquivalenceClass pointers for all the
3158 * top-level indexquals that were possibly-redundantly derived from ECs.
3159 * This allows removal of scan_clauses that are redundant with such quals.
3160 * (We do not attempt to detect such redundancies for quals that are within
3161 * OR subtrees. This could be done in a less hacky way if we returned the
3162 * indexquals in RestrictInfo form, but that would be slower and still pretty
3163 * messy, since we'd have to build new RestrictInfos in many cases.)
3164 */
3165static Plan *
3167 List **qual, List **indexqual, List **indexECs)
3168{
3169 Plan *plan;
3170
3171 if (IsA(bitmapqual, BitmapAndPath))
3172 {
3173 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
3174 List *subplans = NIL;
3175 List *subquals = NIL;
3177 List *subindexECs = NIL;
3178 ListCell *l;
3179
3180 /*
3181 * There may well be redundant quals among the subplans, since a
3182 * top-level WHERE qual might have gotten used to form several
3183 * different index quals. We don't try exceedingly hard to eliminate
3184 * redundancies, but we do eliminate obvious duplicates by using
3185 * list_concat_unique.
3186 */
3187 foreach(l, apath->bitmapquals)
3188 {
3189 Plan *subplan;
3190 List *subqual;
3193
3194 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
3196 &subindexEC);
3197 subplans = lappend(subplans, subplan);
3200 /* Duplicates in indexECs aren't worth getting rid of */
3202 }
3203 plan = (Plan *) make_bitmap_and(subplans);
3204 plan->startup_cost = apath->path.startup_cost;
3205 plan->total_cost = apath->path.total_cost;
3206 plan->plan_rows =
3207 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
3208 plan->plan_width = 0; /* meaningless */
3209 plan->parallel_aware = false;
3210 plan->parallel_safe = apath->path.parallel_safe;
3211 *qual = subquals;
3212 *indexqual = subindexquals;
3214 }
3215 else if (IsA(bitmapqual, BitmapOrPath))
3216 {
3217 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
3218 List *subplans = NIL;
3219 List *subquals = NIL;
3221 bool const_true_subqual = false;
3222 bool const_true_subindexqual = false;
3223 ListCell *l;
3224
3225 /*
3226 * Here, we only detect qual-free subplans. A qual-free subplan would
3227 * cause us to generate "... OR true ..." which we may as well reduce
3228 * to just "true". We do not try to eliminate redundant subclauses
3229 * because (a) it's not as likely as in the AND case, and (b) we might
3230 * well be working with hundreds or even thousands of OR conditions,
3231 * perhaps from a long IN list. The performance of list_append_unique
3232 * would be unacceptable.
3233 */
3234 foreach(l, opath->bitmapquals)
3235 {
3236 Plan *subplan;
3237 List *subqual;
3240
3241 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
3243 &subindexEC);
3244 subplans = lappend(subplans, subplan);
3245 if (subqual == NIL)
3246 const_true_subqual = true;
3247 else if (!const_true_subqual)
3250 if (subindexqual == NIL)
3252 else if (!const_true_subindexqual)
3255 }
3256
3257 /*
3258 * In the presence of ScalarArrayOpExpr quals, we might have built
3259 * BitmapOrPaths with just one subpath; don't add an OR step.
3260 */
3261 if (list_length(subplans) == 1)
3262 {
3263 plan = (Plan *) linitial(subplans);
3264 }
3265 else
3266 {
3267 plan = (Plan *) make_bitmap_or(subplans);
3268 plan->startup_cost = opath->path.startup_cost;
3269 plan->total_cost = opath->path.total_cost;
3270 plan->plan_rows =
3271 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
3272 plan->plan_width = 0; /* meaningless */
3273 plan->parallel_aware = false;
3274 plan->parallel_safe = opath->path.parallel_safe;
3275 }
3276
3277 /*
3278 * If there were constant-TRUE subquals, the OR reduces to constant
3279 * TRUE. Also, avoid generating one-element ORs, which could happen
3280 * due to redundancy elimination or ScalarArrayOpExpr quals.
3281 */
3283 *qual = NIL;
3284 else if (list_length(subquals) <= 1)
3285 *qual = subquals;
3286 else
3289 *indexqual = NIL;
3290 else if (list_length(subindexquals) <= 1)
3291 *indexqual = subindexquals;
3292 else
3293 *indexqual = list_make1(make_orclause(subindexquals));
3294 *indexECs = NIL;
3295 }
3296 else if (IsA(bitmapqual, IndexPath))
3297 {
3298 IndexPath *ipath = (IndexPath *) bitmapqual;
3299 IndexScan *iscan;
3300 List *subquals;
3303 ListCell *l;
3304
3305 /* Use the regular indexscan plan build machinery... */
3306 iscan = castNode(IndexScan,
3308 NIL, NIL, false));
3309 /* then convert to a bitmap indexscan */
3311 iscan->indexid,
3312 iscan->indexqual,
3313 iscan->indexqualorig);
3314 /* and set its cost/width fields appropriately */
3315 plan->startup_cost = 0.0;
3316 plan->total_cost = ipath->indextotalcost;
3317 plan->plan_rows =
3318 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
3319 plan->plan_width = 0; /* meaningless */
3320 plan->parallel_aware = false;
3321 plan->parallel_safe = ipath->path.parallel_safe;
3322 /* Extract original index clauses, actual index quals, relevant ECs */
3323 subquals = NIL;
3325 subindexECs = NIL;
3326 foreach(l, ipath->indexclauses)
3327 {
3329 RestrictInfo *rinfo = iclause->rinfo;
3330
3331 Assert(!rinfo->pseudoconstant);
3332 subquals = lappend(subquals, rinfo->clause);
3334 get_actual_clauses(iclause->indexquals));
3335 if (rinfo->parent_ec)
3336 subindexECs = lappend(subindexECs, rinfo->parent_ec);
3337 }
3338 /* We can add any index predicate conditions, too */
3339 foreach(l, ipath->indexinfo->indpred)
3340 {
3341 Expr *pred = (Expr *) lfirst(l);
3342
3343 /*
3344 * We know that the index predicate must have been implied by the
3345 * query condition as a whole, but it may or may not be implied by
3346 * the conditions that got pushed into the bitmapqual. Avoid
3347 * generating redundant conditions.
3348 */
3349 if (!predicate_implied_by(list_make1(pred), subquals, false))
3350 {
3351 subquals = lappend(subquals, pred);
3353 }
3354 }
3355 *qual = subquals;
3356 *indexqual = subindexquals;
3358 }
3359 else
3360 {
3361 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
3362 plan = NULL; /* keep compiler quiet */
3363 }
3364
3365 return plan;
3366}
3367
3368/*
3369 * create_tidscan_plan
3370 * Returns a tidscan plan for the base relation scanned by 'best_path'
3371 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3372 */
3373static TidScan *
3375 List *tlist, List *scan_clauses)
3376{
3378 Index scan_relid = best_path->path.parent->relid;
3379 List *tidquals = best_path->tidquals;
3380
3381 /* it should be a base rel... */
3382 Assert(scan_relid > 0);
3383 Assert(best_path->path.parent->rtekind == RTE_RELATION);
3384
3385 /*
3386 * The qpqual list must contain all restrictions not enforced by the
3387 * tidquals list. Since tidquals has OR semantics, we have to be careful
3388 * about matching it up to scan_clauses. It's convenient to handle the
3389 * single-tidqual case separately from the multiple-tidqual case. In the
3390 * single-tidqual case, we look through the scan_clauses while they are
3391 * still in RestrictInfo form, and drop any that are redundant with the
3392 * tidqual.
3393 *
3394 * In normal cases simple pointer equality checks will be enough to spot
3395 * duplicate RestrictInfos, so we try that first.
3396 *
3397 * Another common case is that a scan_clauses entry is generated from the
3398 * same EquivalenceClass as some tidqual, and is therefore redundant with
3399 * it, though not equal.
3400 *
3401 * Unlike indexpaths, we don't bother with predicate_implied_by(); the
3402 * number of cases where it could win are pretty small.
3403 */
3404 if (list_length(tidquals) == 1)
3405 {
3406 List *qpqual = NIL;
3407 ListCell *l;
3408
3409 foreach(l, scan_clauses)
3410 {
3412
3413 if (rinfo->pseudoconstant)
3414 continue; /* we may drop pseudoconstants here */
3415 if (list_member_ptr(tidquals, rinfo))
3416 continue; /* simple duplicate */
3417 if (is_redundant_derived_clause(rinfo, tidquals))
3418 continue; /* derived from same EquivalenceClass */
3419 qpqual = lappend(qpqual, rinfo);
3420 }
3422 }
3423
3424 /* Sort clauses into best execution order */
3426
3427 /* Reduce RestrictInfo lists to bare expressions; ignore pseudoconstants */
3428 tidquals = extract_actual_clauses(tidquals, false);
3430
3431 /*
3432 * If we have multiple tidquals, it's more convenient to remove duplicate
3433 * scan_clauses after stripping the RestrictInfos. In this situation,
3434 * because the tidquals represent OR sub-clauses, they could not have come
3435 * from EquivalenceClasses so we don't have to worry about matching up
3436 * non-identical clauses. On the other hand, because tidpath.c will have
3437 * extracted those sub-clauses from some OR clause and built its own list,
3438 * we will certainly not have pointer equality to any scan clause. So
3439 * convert the tidquals list to an explicit OR clause and see if we can
3440 * match it via equal() to any scan clause.
3441 */
3442 if (list_length(tidquals) > 1)
3444 list_make1(make_orclause(tidquals)));
3445
3446 /* Replace any outer-relation variables with nestloop params */
3447 if (best_path->path.param_info)
3448 {
3449 tidquals = (List *)
3450 replace_nestloop_params(root, (Node *) tidquals);
3451 scan_clauses = (List *)
3453 }
3454
3455 scan_plan = make_tidscan(tlist,
3457 scan_relid,
3458 tidquals);
3459
3460 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3461
3462 return scan_plan;
3463}
3464
3465/*
3466 * create_tidrangescan_plan
3467 * Returns a tidrangescan plan for the base relation scanned by 'best_path'
3468 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3469 */
3470static TidRangeScan *
3472 List *tlist, List *scan_clauses)
3473{
3475 Index scan_relid = best_path->path.parent->relid;
3476 List *tidrangequals = best_path->tidrangequals;
3477
3478 /* it should be a base rel... */
3479 Assert(scan_relid > 0);
3480 Assert(best_path->path.parent->rtekind == RTE_RELATION);
3481
3482 /*
3483 * The qpqual list must contain all restrictions not enforced by the
3484 * tidrangequals list. tidrangequals has AND semantics, so we can simply
3485 * remove any qual that appears in it.
3486 */
3487 {
3488 List *qpqual = NIL;
3489 ListCell *l;
3490
3491 foreach(l, scan_clauses)
3492 {
3494
3495 if (rinfo->pseudoconstant)
3496 continue; /* we may drop pseudoconstants here */
3497 if (list_member_ptr(tidrangequals, rinfo))
3498 continue; /* simple duplicate */
3499 qpqual = lappend(qpqual, rinfo);
3500 }
3502 }
3503
3504 /* Sort clauses into best execution order */
3506
3507 /* Reduce RestrictInfo lists to bare expressions; ignore pseudoconstants */
3508 tidrangequals = extract_actual_clauses(tidrangequals, false);
3510
3511 /* Replace any outer-relation variables with nestloop params */
3512 if (best_path->path.param_info)
3513 {
3514 tidrangequals = (List *)
3515 replace_nestloop_params(root, (Node *) tidrangequals);
3516 scan_clauses = (List *)
3518 }
3519
3522 scan_relid,
3523 tidrangequals);
3524
3525 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3526
3527 return scan_plan;
3528}
3529
3530/*
3531 * create_subqueryscan_plan
3532 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
3533 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3534 */
3535static SubqueryScan *
3537 List *tlist, List *scan_clauses)
3538{
3540 RelOptInfo *rel = best_path->path.parent;
3541 Index scan_relid = rel->relid;
3542 Plan *subplan;
3543
3544 /* it should be a subquery base rel... */
3545 Assert(scan_relid > 0);
3546 Assert(rel->rtekind == RTE_SUBQUERY);
3547
3548 /*
3549 * Recursively create Plan from Path for subquery. Since we are entering
3550 * a different planner context (subroot), recurse to create_plan not
3551 * create_plan_recurse.
3552 */
3553 subplan = create_plan(rel->subroot, best_path->subpath);
3554
3555 /* Sort clauses into best execution order */
3557
3558 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3560
3561 /*
3562 * Replace any outer-relation variables with nestloop params.
3563 *
3564 * We must provide nestloop params for both lateral references of the
3565 * subquery and outer vars in the scan_clauses. It's better to assign the
3566 * former first, because that code path requires specific param IDs, while
3567 * replace_nestloop_params can adapt to the IDs assigned by
3568 * process_subquery_nestloop_params. This avoids possibly duplicating
3569 * nestloop params when the same Var is needed for both reasons.
3570 */
3571 if (best_path->path.param_info)
3572 {
3574 rel->subplan_params);
3575 scan_clauses = (List *)
3577 }
3578
3581 scan_relid,
3582 subplan);
3583
3584 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3585
3586 return scan_plan;
3587}
3588
3589/*
3590 * create_functionscan_plan
3591 * Returns a functionscan plan for the base relation scanned by 'best_path'
3592 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3593 */
3594static FunctionScan *
3596 List *tlist, List *scan_clauses)
3597{
3599 Index scan_relid = best_path->parent->relid;
3601 List *functions;
3602
3603 /* it should be a function base rel... */
3604 Assert(scan_relid > 0);
3606 Assert(rte->rtekind == RTE_FUNCTION);
3607 functions = rte->functions;
3608
3609 /* Sort clauses into best execution order */
3611
3612 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3614
3615 /* Replace any outer-relation variables with nestloop params */
3616 if (best_path->param_info)
3617 {
3618 scan_clauses = (List *)
3620 /* The function expressions could contain nestloop params, too */
3622 }
3623
3625 functions, rte->funcordinality);
3626
3628
3629 return scan_plan;
3630}
3631
3632/*
3633 * create_tablefuncscan_plan
3634 * Returns a tablefuncscan plan for the base relation scanned by 'best_path'
3635 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3636 */
3637static TableFuncScan *
3639 List *tlist, List *scan_clauses)
3640{
3642 Index scan_relid = best_path->parent->relid;
3644 TableFunc *tablefunc;
3645
3646 /* it should be a function base rel... */
3647 Assert(scan_relid > 0);
3649 Assert(rte->rtekind == RTE_TABLEFUNC);
3650 tablefunc = rte->tablefunc;
3651
3652 /* Sort clauses into best execution order */
3654
3655 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3657
3658 /* Replace any outer-relation variables with nestloop params */
3659 if (best_path->param_info)
3660 {
3661 scan_clauses = (List *)
3663 /* The function expressions could contain nestloop params, too */
3664 tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
3665 }
3666
3668 tablefunc);
3669
3671
3672 return scan_plan;
3673}
3674
3675/*
3676 * create_valuesscan_plan
3677 * Returns a valuesscan plan for the base relation scanned by 'best_path'
3678 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3679 */
3680static ValuesScan *
3682 List *tlist, List *scan_clauses)
3683{
3685 Index scan_relid = best_path->parent->relid;
3687 List *values_lists;
3688
3689 /* it should be a values base rel... */
3690 Assert(scan_relid > 0);
3692 Assert(rte->rtekind == RTE_VALUES);
3693 values_lists = rte->values_lists;
3694
3695 /* Sort clauses into best execution order */
3697
3698 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3700
3701 /* Replace any outer-relation variables with nestloop params */
3702 if (best_path->param_info)
3703 {
3704 scan_clauses = (List *)
3706 /* The values lists could contain nestloop params, too */
3707 values_lists = (List *)
3708 replace_nestloop_params(root, (Node *) values_lists);
3709 }
3710
3712 values_lists);
3713
3715
3716 return scan_plan;
3717}
3718
3719/*
3720 * create_ctescan_plan
3721 * Returns a ctescan plan for the base relation scanned by 'best_path'
3722 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3723 */
3724static CteScan *
3726 List *tlist, List *scan_clauses)
3727{
3729 Index scan_relid = best_path->parent->relid;
3732 int plan_id;
3733 int cte_param_id;
3735 Index levelsup;
3736 int ndx;
3737 ListCell *lc;
3738
3739 Assert(scan_relid > 0);
3741 Assert(rte->rtekind == RTE_CTE);
3742 Assert(!rte->self_reference);
3743
3744 /*
3745 * Find the referenced CTE, and locate the SubPlan previously made for it.
3746 */
3747 levelsup = rte->ctelevelsup;
3748 cteroot = root;
3749 while (levelsup-- > 0)
3750 {
3751 cteroot = cteroot->parent_root;
3752 if (!cteroot) /* shouldn't happen */
3753 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3754 }
3755
3756 /*
3757 * Note: cte_plan_ids can be shorter than cteList, if we are still working
3758 * on planning the CTEs (ie, this is a side-reference from another CTE).
3759 * So we mustn't use forboth here.
3760 */
3761 ndx = 0;
3762 foreach(lc, cteroot->parse->cteList)
3763 {
3765
3766 if (strcmp(cte->ctename, rte->ctename) == 0)
3767 break;
3768 ndx++;
3769 }
3770 if (lc == NULL) /* shouldn't happen */
3771 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3772 if (ndx >= list_length(cteroot->cte_plan_ids))
3773 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3774 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3775 if (plan_id <= 0)
3776 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
3777 foreach(lc, cteroot->init_plans)
3778 {
3779 ctesplan = (SubPlan *) lfirst(lc);
3780 if (ctesplan->plan_id == plan_id)
3781 break;
3782 }
3783 if (lc == NULL) /* shouldn't happen */
3784 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3785
3786 /*
3787 * We need the CTE param ID, which is the sole member of the SubPlan's
3788 * setParam list.
3789 */
3790 cte_param_id = linitial_int(ctesplan->setParam);
3791
3792 /* Sort clauses into best execution order */
3794
3795 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3797
3798 /* Replace any outer-relation variables with nestloop params */
3799 if (best_path->param_info)
3800 {
3801 scan_clauses = (List *)
3803 }
3804
3806 plan_id, cte_param_id);
3807
3809
3810 return scan_plan;
3811}
3812
3813/*
3814 * create_namedtuplestorescan_plan
3815 * Returns a tuplestorescan plan for the base relation scanned by
3816 * 'best_path' with restriction clauses 'scan_clauses' and targetlist
3817 * 'tlist'.
3818 */
3819static NamedTuplestoreScan *
3821 List *tlist, List *scan_clauses)
3822{
3824 Index scan_relid = best_path->parent->relid;
3826
3827 Assert(scan_relid > 0);
3829 Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
3830
3831 /* Sort clauses into best execution order */
3833
3834 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3836
3837 /* Replace any outer-relation variables with nestloop params */
3838 if (best_path->param_info)
3839 {
3840 scan_clauses = (List *)
3842 }
3843
3845 rte->enrname);
3846
3848
3849 return scan_plan;
3850}
3851
3852/*
3853 * create_resultscan_plan
3854 * Returns a Result plan for the RTE_RESULT base relation scanned by
3855 * 'best_path' with restriction clauses 'scan_clauses' and targetlist
3856 * 'tlist'.
3857 */
3858static Result *
3860 List *tlist, List *scan_clauses)
3861{
3863 Index scan_relid = best_path->parent->relid;
3865
3866 Assert(scan_relid > 0);
3868 Assert(rte->rtekind == RTE_RESULT);
3869
3870 /* Sort clauses into best execution order */
3872
3873 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3875
3876 /* Replace any outer-relation variables with nestloop params */
3877 if (best_path->param_info)
3878 {
3879 scan_clauses = (List *)
3881 }
3882
3884 best_path->parent);
3885
3887
3888 return scan_plan;
3889}
3890
3891/*
3892 * create_worktablescan_plan
3893 * Returns a worktablescan plan for the base relation scanned by 'best_path'
3894 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3895 */
3896static WorkTableScan *
3898 List *tlist, List *scan_clauses)
3899{
3901 Index scan_relid = best_path->parent->relid;
3903 Index levelsup;
3905
3906 Assert(scan_relid > 0);
3908 Assert(rte->rtekind == RTE_CTE);
3909 Assert(rte->self_reference);
3910
3911 /*
3912 * We need to find the worktable param ID, which is in the plan level
3913 * that's processing the recursive UNION, which is one level *below* where
3914 * the CTE comes from.
3915 */
3916 levelsup = rte->ctelevelsup;
3917 if (levelsup == 0) /* shouldn't happen */
3918 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3919 levelsup--;
3920 cteroot = root;
3921 while (levelsup-- > 0)
3922 {
3923 cteroot = cteroot->parent_root;
3924 if (!cteroot) /* shouldn't happen */
3925 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3926 }
3927 if (cteroot->wt_param_id < 0) /* shouldn't happen */
3928 elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
3929
3930 /* Sort clauses into best execution order */
3932
3933 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3935
3936 /* Replace any outer-relation variables with nestloop params */
3937 if (best_path->param_info)
3938 {
3939 scan_clauses = (List *)
3941 }
3942
3944 cteroot->wt_param_id);
3945
3947
3948 return scan_plan;
3949}
3950
3951/*
3952 * create_foreignscan_plan
3953 * Returns a foreignscan plan for the relation scanned by 'best_path'
3954 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3955 */
3956static ForeignScan *
3958 List *tlist, List *scan_clauses)
3959{
3961 RelOptInfo *rel = best_path->path.parent;
3962 Index scan_relid = rel->relid;
3964 Plan *outer_plan = NULL;
3965
3966 Assert(rel->fdwroutine != NULL);
3967
3968 /* transform the child path if any */
3969 if (best_path->fdw_outerpath)
3970 outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
3972
3973 /*
3974 * If we're scanning a base relation, fetch its OID. (Irrelevant if
3975 * scanning a join relation.)
3976 */
3977 if (scan_relid > 0)
3978 {
3980
3981 Assert(rel->rtekind == RTE_RELATION);
3983 Assert(rte->rtekind == RTE_RELATION);
3984 rel_oid = rte->relid;
3985 }
3986
3987 /*
3988 * Sort clauses into best execution order. We do this first since the FDW
3989 * might have more info than we do and wish to adjust the ordering.
3990 */
3992
3993 /*
3994 * Let the FDW perform its processing on the restriction clauses and
3995 * generate the plan node. Note that the FDW might remove restriction
3996 * clauses that it intends to execute remotely, or even add more (if it
3997 * has selected some join clauses for remote use but also wants them
3998 * rechecked locally).
3999 */
4000 scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
4001 best_path,
4002 tlist, scan_clauses,
4003 outer_plan);
4004
4005 /* Copy cost data from Path to Plan; no need to make FDW do this */
4006 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
4007
4008 /* Copy user OID to access as; likewise no need to make FDW do this */
4009 scan_plan->checkAsUser = rel->userid;
4010
4011 /* Copy foreign server OID; likewise, no need to make FDW do this */
4012 scan_plan->fs_server = rel->serverid;
4013
4014 /*
4015 * Likewise, copy the relids that are represented by this foreign scan. An
4016 * upper rel doesn't have relids set, but it covers all the relations
4017 * participating in the underlying scan/join, so use root->all_query_rels.
4018 */
4019 if (rel->reloptkind == RELOPT_UPPER_REL)
4020 scan_plan->fs_relids = root->all_query_rels;
4021 else
4022 scan_plan->fs_relids = best_path->path.parent->relids;
4023
4024 /*
4025 * Join relid sets include relevant outer joins, but FDWs may need to know
4026 * which are the included base rels. That's a bit tedious to get without
4027 * access to the plan-time data structures, so compute it here.
4028 */
4029 scan_plan->fs_base_relids = bms_difference(scan_plan->fs_relids,
4030 root->outer_join_rels);
4031
4032 /*
4033 * If this is a foreign join, and to make it valid to push down we had to
4034 * assume that the current user is the same as some user explicitly named
4035 * in the query, mark the finished plan as depending on the current user.
4036 */
4037 if (rel->useridiscurrent)
4038 root->glob->dependsOnRole = true;
4039
4040 /*
4041 * Replace any outer-relation variables with nestloop params in the qual,
4042 * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
4043 * the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
4044 * fdw_recheck_quals could have come from join clauses, so doing this
4045 * beforehand on the scan_clauses wouldn't work.) We assume
4046 * fdw_scan_tlist contains no such variables.
4047 */
4048 if (best_path->path.param_info)
4049 {
4050 scan_plan->scan.plan.qual = (List *)
4051 replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
4052 scan_plan->fdw_exprs = (List *)
4053 replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
4054 scan_plan->fdw_recheck_quals = (List *)
4056 (Node *) scan_plan->fdw_recheck_quals);
4057 }
4058
4059 /*
4060 * If rel is a base relation, detect whether any system columns are
4061 * requested from the rel. (If rel is a join relation, rel->relid will be
4062 * 0, but there can be no Var with relid 0 in the rel's targetlist or the
4063 * restriction clauses, so we skip this in that case. Note that any such
4064 * columns in base relations that were joined are assumed to be contained
4065 * in fdw_scan_tlist.) This is a bit of a kluge and might go away
4066 * someday, so we intentionally leave it out of the API presented to FDWs.
4067 */
4068 scan_plan->fsSystemCol = false;
4069 if (scan_relid > 0)
4070 {
4071 Bitmapset *attrs_used = NULL;
4072 ListCell *lc;
4073 int i;
4074
4075 /*
4076 * First, examine all the attributes needed for joins or final output.
4077 * Note: we must look at rel's targetlist, not the attr_needed data,
4078 * because attr_needed isn't computed for inheritance child rels.
4079 */
4080 pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
4081
4082 /* Add all the attributes used by restriction clauses. */
4083 foreach(lc, rel->baserestrictinfo)
4084 {
4085 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4086
4087 pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
4088 }
4089
4090 /* Now, are any system columns requested from rel? */
4091 for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
4092 {
4094 {
4095 scan_plan->fsSystemCol = true;
4096 break;
4097 }
4098 }
4099
4100 bms_free(attrs_used);
4101 }
4102
4103 return scan_plan;
4104}
4105
4106/*
4107 * create_customscan_plan
4108 *
4109 * Transform a CustomPath into a Plan.
4110 */
4111static CustomScan *
4113 List *tlist, List *scan_clauses)
4114{
4115 CustomScan *cplan;
4116 RelOptInfo *rel = best_path->path.parent;
4117 List *custom_plans = NIL;
4118 ListCell *lc;
4119
4120 /* Recursively transform child paths. */
4121 foreach(lc, best_path->custom_paths)
4122 {
4125
4126 custom_plans = lappend(custom_plans, plan);
4127 }
4128
4129 /*
4130 * Sort clauses into the best execution order, although custom-scan
4131 * provider can reorder them again.
4132 */
4134
4135 /*
4136 * Invoke custom plan provider to create the Plan node represented by the
4137 * CustomPath.
4138 */
4139 cplan = castNode(CustomScan,
4140 best_path->methods->PlanCustomPath(root,
4141 rel,
4142 best_path,
4143 tlist,
4145 custom_plans));
4146
4147 /*
4148 * Copy cost data from Path to Plan; no need to make custom-plan providers
4149 * do this
4150 */
4151 copy_generic_path_info(&cplan->scan.plan, &best_path->path);
4152
4153 /* Likewise, copy the relids that are represented by this custom scan */
4154 cplan->custom_relids = best_path->path.parent->relids;
4155
4156 /*
4157 * Replace any outer-relation variables with nestloop params in the qual
4158 * and custom_exprs expressions. We do this last so that the custom-plan
4159 * provider doesn't have to be involved. (Note that parts of custom_exprs
4160 * could have come from join clauses, so doing this beforehand on the
4161 * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
4162 * such variables.
4163 */
4164 if (best_path->path.param_info)
4165 {
4166 cplan->scan.plan.qual = (List *)
4167 replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
4168 cplan->custom_exprs = (List *)
4170 }
4171
4172 return cplan;
4173}
4174
4175
4176/*****************************************************************************
4177 *
4178 * JOIN METHODS
4179 *
4180 *****************************************************************************/
4181
4182static NestLoop *
4185{
4187 Plan *outer_plan;
4188 Plan *inner_plan;
4189 Relids outerrelids;
4190 List *tlist = build_path_tlist(root, &best_path->jpath.path);
4191 List *joinrestrictclauses = best_path->jpath.joinrestrictinfo;
4192 List *joinclauses;
4194 List *nestParams;
4195 List *outer_tlist;
4197 Relids saveOuterRels = root->curOuterRels;
4198 ListCell *lc;
4199
4200 /*
4201 * If the inner path is parameterized by the topmost parent of the outer
4202 * rel rather than the outer rel itself, fix that. (Nothing happens here
4203 * if it is not so parameterized.)
4204 */
4205 best_path->jpath.innerjoinpath =
4207 best_path->jpath.innerjoinpath,
4208 best_path->jpath.outerjoinpath->parent);
4209
4210 /*
4211 * Failure here probably means that reparameterize_path_by_child() is not
4212 * in sync with path_is_reparameterizable_by_child().
4213 */
4214 Assert(best_path->jpath.innerjoinpath != NULL);
4215
4216 /* NestLoop can project, so no need to be picky about child tlists */
4217 outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath, 0);
4218
4219 /* For a nestloop, include outer relids in curOuterRels for inner side */
4220 outerrelids = best_path->jpath.outerjoinpath->parent->relids;
4221 root->curOuterRels = bms_union(root->curOuterRels, outerrelids);
4222
4223 inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath, 0);
4224
4225 /* Restore curOuterRels */
4226 bms_free(root->curOuterRels);
4227 root->curOuterRels = saveOuterRels;
4228
4229 /* Sort join qual clauses into best execution order */
4231
4232 /* Get the join qual clauses (in plain expression form) */
4233 /* Any pseudoconstant clauses are ignored here */
4234 if (IS_OUTER_JOIN(best_path->jpath.jointype))
4235 {
4237 best_path->jpath.path.parent->relids,
4238 &joinclauses, &otherclauses);
4239 }
4240 else
4241 {
4242 /* We can treat all clauses alike for an inner join */
4243 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
4244 otherclauses = NIL;
4245 }
4246
4247 /* Replace any outer-relation variables with nestloop params */
4248 if (best_path->jpath.path.param_info)
4249 {
4250 joinclauses = (List *)
4251 replace_nestloop_params(root, (Node *) joinclauses);
4252 otherclauses = (List *)
4254 }
4255
4256 /*
4257 * Identify any nestloop parameters that should be supplied by this join
4258 * node, and remove them from root->curOuterParams.
4259 */
4261 outerrelids,
4263
4264 /*
4265 * While nestloop parameters that are Vars had better be available from
4266 * the outer_plan already, there are edge cases where nestloop parameters
4267 * that are PHVs won't be. In such cases we must add them to the
4268 * outer_plan's tlist, since the executor's NestLoopParam machinery
4269 * requires the params to be simple outer-Var references to that tlist.
4270 * (This is cheating a little bit, because the outer path's required-outer
4271 * relids might not be enough to allow evaluating such a PHV. But in
4272 * practice, if we could have evaluated the PHV at the nestloop node, we
4273 * can do so in the outer plan too.)
4274 */
4275 outer_tlist = outer_plan->targetlist;
4276 outer_parallel_safe = outer_plan->parallel_safe;
4277 foreach(lc, nestParams)
4278 {
4282
4283 if (IsA(nlp->paramval, Var))
4284 continue; /* nothing to do for simple Vars */
4285 /* Otherwise it must be a PHV */
4286 phv = castNode(PlaceHolderVar, nlp->paramval);
4287
4288 if (tlist_member((Expr *) phv, outer_tlist))
4289 continue; /* already available */
4290
4291 /*
4292 * It's possible that nestloop parameter PHVs selected to evaluate
4293 * here contain references to surviving root->curOuterParams items
4294 * (that is, they reference values that will be supplied by some
4295 * higher-level nestloop). Those need to be converted to Params now.
4296 * Note: it's safe to do this after the tlist_member() check, because
4297 * equal() won't pay attention to phv->phexpr.
4298 */
4299 phv->phexpr = (Expr *) replace_nestloop_params(root,
4300 (Node *) phv->phexpr);
4301
4302 /* Make a shallow copy of outer_tlist, if we didn't already */
4303 if (outer_tlist == outer_plan->targetlist)
4304 outer_tlist = list_copy(outer_tlist);
4305 /* ... and add the needed expression */
4307 list_length(outer_tlist) + 1,
4308 NULL,
4309 true);
4310 outer_tlist = lappend(outer_tlist, tle);
4311 /* ... and track whether tlist is (still) parallel-safe */
4314 }
4315 if (outer_tlist != outer_plan->targetlist)
4316 outer_plan = change_plan_targetlist(outer_plan, outer_tlist,
4318
4319 /* And finally, we can build the join plan node */
4320 join_plan = make_nestloop(tlist,
4321 joinclauses,
4323 nestParams,
4324 outer_plan,
4325 inner_plan,
4326 best_path->jpath.jointype,
4327 best_path->jpath.inner_unique);
4328
4329 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4330
4331 return join_plan;
4332}
4333
4334static MergeJoin *
4337{
4339 Plan *outer_plan;
4340 Plan *inner_plan;
4341 List *tlist = build_path_tlist(root, &best_path->jpath.path);
4342 List *joinclauses;
4344 List *mergeclauses;
4347 int nClauses;
4350 bool *mergereversals;
4351 bool *mergenullsfirst;
4354 int i;
4355 ListCell *lc;
4356 ListCell *lop;
4357 ListCell *lip;
4358 Path *outer_path = best_path->jpath.outerjoinpath;
4359 Path *inner_path = best_path->jpath.innerjoinpath;
4360
4361 /*
4362 * MergeJoin can project, so we don't have to demand exact tlists from the
4363 * inputs. However, if we're intending to sort an input's result, it's
4364 * best to request a small tlist so we aren't sorting more data than
4365 * necessary.
4366 */
4367 outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4368 (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
4369
4370 inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4371 (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
4372
4373 /* Sort join qual clauses into best execution order */
4374 /* NB: do NOT reorder the mergeclauses */
4375 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4376
4377 /* Get the join qual clauses (in plain expression form) */
4378 /* Any pseudoconstant clauses are ignored here */
4379 if (IS_OUTER_JOIN(best_path->jpath.jointype))
4380 {
4381 extract_actual_join_clauses(joinclauses,
4382 best_path->jpath.path.parent->relids,
4383 &joinclauses, &otherclauses);
4384 }
4385 else
4386 {
4387 /* We can treat all clauses alike for an inner join */
4388 joinclauses = extract_actual_clauses(joinclauses, false);
4389 otherclauses = NIL;
4390 }
4391
4392 /*
4393 * Remove the mergeclauses from the list of join qual clauses, leaving the
4394 * list of quals that must be checked as qpquals.
4395 */
4396 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
4397 joinclauses = list_difference(joinclauses, mergeclauses);
4398
4399 /*
4400 * Replace any outer-relation variables with nestloop params. There
4401 * should not be any in the mergeclauses.
4402 */
4403 if (best_path->jpath.path.param_info)
4404 {
4405 joinclauses = (List *)
4406 replace_nestloop_params(root, (Node *) joinclauses);
4407 otherclauses = (List *)
4409 }
4410
4411 /*
4412 * Rearrange mergeclauses, if needed, so that the outer variable is always
4413 * on the left; mark the mergeclause restrictinfos with correct
4414 * outer_is_left status.
4415 */
4416 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
4417 best_path->jpath.outerjoinpath->parent->relids);
4418
4419 /*
4420 * Create explicit sort nodes for the outer and inner paths if necessary.
4421 */
4422 if (best_path->outersortkeys)
4423 {
4424 Relids outer_relids = outer_path->parent->relids;
4425 Plan *sort_plan;
4426
4427 /*
4428 * We can assert that the outer path is not already ordered
4429 * appropriately for the mergejoin; otherwise, outersortkeys would
4430 * have been set to NIL.
4431 */
4432 Assert(!pathkeys_contained_in(best_path->outersortkeys,
4433 outer_path->pathkeys));
4434
4435 /*
4436 * We choose to use incremental sort if it is enabled and there are
4437 * presorted keys; otherwise we use full sort.
4438 */
4439 if (enable_incremental_sort && best_path->outer_presorted_keys > 0)
4440 {
4441 sort_plan = (Plan *)
4443 best_path->outersortkeys,
4444 outer_relids,
4445 best_path->outer_presorted_keys);
4446
4449 best_path->outersortkeys,
4450 -1.0);
4451 }
4452 else
4453 {
4454 sort_plan = (Plan *)
4455 make_sort_from_pathkeys(outer_plan,
4456 best_path->outersortkeys,
4457 outer_relids);
4458
4460 }
4461
4462 outer_plan = sort_plan;
4463 outerpathkeys = best_path->outersortkeys;
4464 }
4465 else
4466 outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
4467
4468 if (best_path->innersortkeys)
4469 {
4470 /*
4471 * We do not consider incremental sort for inner path, because
4472 * incremental sort does not support mark/restore.
4473 */
4474
4475 Relids inner_relids = inner_path->parent->relids;
4476 Sort *sort;
4477
4478 /*
4479 * We can assert that the inner path is not already ordered
4480 * appropriately for the mergejoin; otherwise, innersortkeys would
4481 * have been set to NIL.
4482 */
4483 Assert(!pathkeys_contained_in(best_path->innersortkeys,
4484 inner_path->pathkeys));
4485
4486 sort = make_sort_from_pathkeys(inner_plan,
4487 best_path->innersortkeys,
4488 inner_relids);
4489
4491 inner_plan = (Plan *) sort;
4492 innerpathkeys = best_path->innersortkeys;
4493 }
4494 else
4495 innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
4496
4497 /*
4498 * If specified, add a materialize node to shield the inner plan from the
4499 * need to handle mark/restore.
4500 */
4501 if (best_path->materialize_inner)
4502 {
4503 Plan *matplan = (Plan *) make_material(inner_plan);
4504
4505 /*
4506 * We assume the materialize will not spill to disk, and therefore
4507 * charge just cpu_operator_cost per tuple. (Keep this estimate in
4508 * sync with final_cost_mergejoin.)
4509 */
4510 copy_plan_costsize(matplan, inner_plan);
4511 matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
4512
4513 inner_plan = matplan;
4514 }
4515
4516 /*
4517 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
4518 * executor. The information is in the pathkeys for the two inputs, but
4519 * we need to be careful about the possibility of mergeclauses sharing a
4520 * pathkey, as well as the possibility that the inner pathkeys are not in
4521 * an order matching the mergeclauses.
4522 */
4523 nClauses = list_length(mergeclauses);
4524 Assert(nClauses == list_length(best_path->path_mergeclauses));
4525 mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
4526 mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
4527 mergereversals = (bool *) palloc(nClauses * sizeof(bool));
4528 mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
4529
4530 opathkey = NULL;
4531 opeclass = NULL;
4534 i = 0;
4535 foreach(lc, best_path->path_mergeclauses)
4536 {
4542 bool first_inner_match = false;
4543
4544 /* fetch outer/inner eclass from mergeclause */
4545 if (rinfo->outer_is_left)
4546 {
4547 oeclass = rinfo->left_ec;
4548 ieclass = rinfo->right_ec;
4549 }
4550 else
4551 {
4552 oeclass = rinfo->right_ec;
4553 ieclass = rinfo->left_ec;
4554 }
4555 Assert(oeclass != NULL);
4556 Assert(ieclass != NULL);
4557
4558 /*
4559 * We must identify the pathkey elements associated with this clause
4560 * by matching the eclasses (which should give a unique match, since
4561 * the pathkey lists should be canonical). In typical cases the merge
4562 * clauses are one-to-one with the pathkeys, but when dealing with
4563 * partially redundant query conditions, things are more complicated.
4564 *
4565 * lop and lip reference the first as-yet-unmatched pathkey elements.
4566 * If they're NULL then all pathkey elements have been matched.
4567 *
4568 * The ordering of the outer pathkeys should match the mergeclauses,
4569 * by construction (see find_mergeclauses_for_outer_pathkeys()). There
4570 * could be more than one mergeclause for the same outer pathkey, but
4571 * no pathkey may be entirely skipped over.
4572 */
4573 if (oeclass != opeclass) /* multiple matches are not interesting */
4574 {
4575 /* doesn't match the current opathkey, so must match the next */
4576 if (lop == NULL)
4577 elog(ERROR, "outer pathkeys do not match mergeclauses");
4578 opathkey = (PathKey *) lfirst(lop);
4579 opeclass = opathkey->pk_eclass;
4581 if (oeclass != opeclass)
4582 elog(ERROR, "outer pathkeys do not match mergeclauses");
4583 }
4584
4585 /*
4586 * The inner pathkeys likewise should not have skipped-over keys, but
4587 * it's possible for a mergeclause to reference some earlier inner
4588 * pathkey if we had redundant pathkeys. For example we might have
4589 * mergeclauses like "o.a = i.x AND o.b = i.y AND o.c = i.x". The
4590 * implied inner ordering is then "ORDER BY x, y, x", but the pathkey
4591 * mechanism drops the second sort by x as redundant, and this code
4592 * must cope.
4593 *
4594 * It's also possible for the implied inner-rel ordering to be like
4595 * "ORDER BY x, y, x DESC". We still drop the second instance of x as
4596 * redundant; but this means that the sort ordering of a redundant
4597 * inner pathkey should not be considered significant. So we must
4598 * detect whether this is the first clause matching an inner pathkey.
4599 */
4600 if (lip)
4601 {
4602 ipathkey = (PathKey *) lfirst(lip);
4603 ipeclass = ipathkey->pk_eclass;
4604 if (ieclass == ipeclass)
4605 {
4606 /* successful first match to this inner pathkey */
4608 first_inner_match = true;
4609 }
4610 }
4611 if (!first_inner_match)
4612 {
4613 /* redundant clause ... must match something before lip */
4614 ListCell *l2;
4615
4616 foreach(l2, innerpathkeys)
4617 {
4618 if (l2 == lip)
4619 break;
4620 ipathkey = (PathKey *) lfirst(l2);
4621 ipeclass = ipathkey->pk_eclass;
4622 if (ieclass == ipeclass)
4623 break;
4624 }
4625 if (ieclass != ipeclass)
4626 elog(ERROR, "inner pathkeys do not match mergeclauses");
4627 }
4628
4629 /*
4630 * The pathkeys should always match each other as to opfamily and
4631 * collation (which affect equality), but if we're considering a
4632 * redundant inner pathkey, its sort ordering might not match. In
4633 * such cases we may ignore the inner pathkey's sort ordering and use
4634 * the outer's. (In effect, we're lying to the executor about the
4635 * sort direction of this inner column, but it does not matter since
4636 * the run-time row comparisons would only reach this column when
4637 * there's equality for the earlier column containing the same eclass.
4638 * There could be only one value in this column for the range of inner
4639 * rows having a given value in the earlier column, so it does not
4640 * matter which way we imagine this column to be ordered.) But a
4641 * non-redundant inner pathkey had better match outer's ordering too.
4642 */
4643 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
4644 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation)
4645 elog(ERROR, "left and right pathkeys do not match in mergejoin");
4646 if (first_inner_match &&
4647 (opathkey->pk_cmptype != ipathkey->pk_cmptype ||
4648 opathkey->pk_nulls_first != ipathkey->pk_nulls_first))
4649 elog(ERROR, "left and right pathkeys do not match in mergejoin");
4650
4651 /* OK, save info for executor */
4652 mergefamilies[i] = opathkey->pk_opfamily;
4653 mergecollations[i] = opathkey->pk_eclass->ec_collation;
4654 mergereversals[i] = (opathkey->pk_cmptype == COMPARE_GT ? true : false);
4655 mergenullsfirst[i] = opathkey->pk_nulls_first;
4656 i++;
4657 }
4658
4659 /*
4660 * Note: it is not an error if we have additional pathkey elements (i.e.,
4661 * lop or lip isn't NULL here). The input paths might be better-sorted
4662 * than we need for the current mergejoin.
4663 */
4664
4665 /*
4666 * Now we can build the mergejoin node.
4667 */
4668 join_plan = make_mergejoin(tlist,
4669 joinclauses,
4671 mergeclauses,
4676 outer_plan,
4677 inner_plan,
4678 best_path->jpath.jointype,
4679 best_path->jpath.inner_unique,
4680 best_path->skip_mark_restore);
4681
4682 /* Costs of sort and material steps are included in path cost already */
4683 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4684
4685 return join_plan;
4686}
4687
4688static HashJoin *
4691{
4693 Hash *hash_plan;
4694 Plan *outer_plan;
4695 Plan *inner_plan;
4696 List *tlist = build_path_tlist(root, &best_path->jpath.path);
4697 List *joinclauses;
4699 List *hashclauses;
4700 List *hashoperators = NIL;
4701 List *hashcollations = NIL;
4704 Oid skewTable = InvalidOid;
4705 AttrNumber skewColumn = InvalidAttrNumber;
4706 bool skewInherit = false;
4707 ListCell *lc;
4708
4709 /*
4710 * HashJoin can project, so we don't have to demand exact tlists from the
4711 * inputs. However, it's best to request a small tlist from the inner
4712 * side, so that we aren't storing more data than necessary. Likewise, if
4713 * we anticipate batching, request a small tlist from the outer side so
4714 * that we don't put extra data in the outer batch files.
4715 */
4716 outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4717 (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
4718
4719 inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4721
4722 /* Sort join qual clauses into best execution order */
4723 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4724 /* There's no point in sorting the hash clauses ... */
4725
4726 /* Get the join qual clauses (in plain expression form) */
4727 /* Any pseudoconstant clauses are ignored here */
4728 if (IS_OUTER_JOIN(best_path->jpath.jointype))
4729 {
4730 extract_actual_join_clauses(joinclauses,
4731 best_path->jpath.path.parent->relids,
4732 &joinclauses, &otherclauses);
4733 }
4734 else
4735 {
4736 /* We can treat all clauses alike for an inner join */
4737 joinclauses = extract_actual_clauses(joinclauses, false);
4738 otherclauses = NIL;
4739 }
4740
4741 /*
4742 * Remove the hashclauses from the list of join qual clauses, leaving the
4743 * list of quals that must be checked as qpquals.
4744 */
4745 hashclauses = get_actual_clauses(best_path->path_hashclauses);
4746 joinclauses = list_difference(joinclauses, hashclauses);
4747
4748 /*
4749 * Replace any outer-relation variables with nestloop params. There
4750 * should not be any in the hashclauses.
4751 */
4752 if (best_path->jpath.path.param_info)
4753 {
4754 joinclauses = (List *)
4755 replace_nestloop_params(root, (Node *) joinclauses);
4756 otherclauses = (List *)
4758 }
4759
4760 /*
4761 * Rearrange hashclauses, if needed, so that the outer variable is always
4762 * on the left.
4763 */
4764 hashclauses = get_switched_clauses(best_path->path_hashclauses,
4765 best_path->jpath.outerjoinpath->parent->relids);
4766
4767 /*
4768 * If there is a single join clause and we can identify the outer variable
4769 * as a simple column reference, supply its identity for possible use in
4770 * skew optimization. (Note: in principle we could do skew optimization
4771 * with multiple join clauses, but we'd have to be able to determine the
4772 * most common combinations of outer values, which we don't currently have
4773 * enough stats for.)
4774 */
4775 if (list_length(hashclauses) == 1)
4776 {
4777 OpExpr *clause = (OpExpr *) linitial(hashclauses);
4778 Node *node;
4779
4780 Assert(is_opclause(clause));
4781 node = (Node *) linitial(clause->args);
4782 if (IsA(node, RelabelType))
4783 node = (Node *) ((RelabelType *) node)->arg;
4784 if (IsA(node, Var))
4785 {
4786 Var *var = (Var *) node;
4788
4789 rte = root->simple_rte_array[var->varno];
4790 if (rte->rtekind == RTE_RELATION)
4791 {
4792 skewTable = rte->relid;
4793 skewColumn = var->varattno;
4794 skewInherit = rte->inh;
4795 }
4796 }
4797 }
4798
4799 /*
4800 * Collect hash related information. The hashed expressions are
4801 * deconstructed into outer/inner expressions, so they can be computed
4802 * separately (inner expressions are used to build the hashtable via Hash,
4803 * outer expressions to perform lookups of tuples from HashJoin's outer
4804 * plan in the hashtable). Also collect operator information necessary to
4805 * build the hashtable.
4806 */
4807 foreach(lc, hashclauses)
4808 {
4810
4811 hashoperators = lappend_oid(hashoperators, hclause->opno);
4812 hashcollations = lappend_oid(hashcollations, hclause->inputcollid);
4815 }
4816
4817 /*
4818 * Build the hash node and hash join node.
4819 */
4820 hash_plan = make_hash(inner_plan,
4822 skewTable,
4823 skewColumn,
4824 skewInherit);
4825
4826 /*
4827 * Set Hash node's startup & total costs equal to total cost of input
4828 * plan; this only affects EXPLAIN display not decisions.
4829 */
4830 copy_plan_costsize(&hash_plan->plan, inner_plan);
4831 hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
4832
4833 /*
4834 * If parallel-aware, the executor will also need an estimate of the total
4835 * number of rows expected from all participants so that it can size the
4836 * shared hash table.
4837 */
4838 if (best_path->jpath.path.parallel_aware)
4839 {
4840 hash_plan->plan.parallel_aware = true;
4841 hash_plan->rows_total = best_path->inner_rows_total;
4842 }
4843
4844 join_plan = make_hashjoin(tlist,
4845 joinclauses,
4847 hashclauses,
4848 hashoperators,
4849 hashcollations,
4851 outer_plan,
4852 (Plan *) hash_plan,
4853 best_path->jpath.jointype,
4854 best_path->jpath.inner_unique);
4855
4856 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4857
4858 return join_plan;
4859}
4860
4861
4862/*****************************************************************************
4863 *
4864 * SUPPORTING ROUTINES
4865 *
4866 *****************************************************************************/
4867
4868/*
4869 * replace_nestloop_params
4870 * Replace outer-relation Vars and PlaceHolderVars in the given expression
4871 * with nestloop Params
4872 *
4873 * All Vars and PlaceHolderVars belonging to the relation(s) identified by
4874 * root->curOuterRels are replaced by Params, and entries are added to
4875 * root->curOuterParams if not already present.
4876 */
4877static Node *
4879{
4880 /* No setup needed for tree walk, so away we go */
4882}
4883
4884static Node *
4886{
4887 if (node == NULL)
4888 return NULL;
4889 if (IsA(node, Var))
4890 {
4891 Var *var = (Var *) node;
4892
4893 /* Upper-level Vars should be long gone at this point */
4894 Assert(var->varlevelsup == 0);
4895 /* If not to be replaced, we can just return the Var unmodified */
4896 if (IS_SPECIAL_VARNO(var->varno) ||
4897 !bms_is_member(var->varno, root->curOuterRels))
4898 return node;
4899 /* Replace the Var with a nestloop Param */
4900 return (Node *) replace_nestloop_param_var(root, var);
4901 }
4902 if (IsA(node, PlaceHolderVar))
4903 {
4904 PlaceHolderVar *phv = (PlaceHolderVar *) node;
4905
4906 /* Upper-level PlaceHolderVars should be long gone at this point */
4907 Assert(phv->phlevelsup == 0);
4908
4909 /* Check whether we need to replace the PHV */
4910 if (!bms_is_subset(find_placeholder_info(root, phv)->ph_eval_at,
4911 root->curOuterRels))
4912 {
4913 /*
4914 * We can't replace the whole PHV, but we might still need to
4915 * replace Vars or PHVs within its expression, in case it ends up
4916 * actually getting evaluated here. (It might get evaluated in
4917 * this plan node, or some child node; in the latter case we don't
4918 * really need to process the expression here, but we haven't got
4919 * enough info to tell if that's the case.) Flat-copy the PHV
4920 * node and then recurse on its expression.
4921 *
4922 * Note that after doing this, we might have different
4923 * representations of the contents of the same PHV in different
4924 * parts of the plan tree. This is OK because equal() will just
4925 * match on phid/phlevelsup, so setrefs.c will still recognize an
4926 * upper-level reference to a lower-level copy of the same PHV.
4927 */
4929
4930 memcpy(newphv, phv, sizeof(PlaceHolderVar));
4931 newphv->phexpr = (Expr *)
4933 root);
4934 return (Node *) newphv;
4935 }
4936 /* Replace the PlaceHolderVar with a nestloop Param */
4938 }
4940}
4941
4942/*
4943 * fix_indexqual_references
4944 * Adjust indexqual clauses to the form the executor's indexqual
4945 * machinery needs.
4946 *
4947 * We have three tasks here:
4948 * * Select the actual qual clauses out of the input IndexClause list,
4949 * and remove RestrictInfo nodes from the qual clauses.
4950 * * Replace any outer-relation Var or PHV nodes with nestloop Params.
4951 * (XXX eventually, that responsibility should go elsewhere?)
4952 * * Index keys must be represented by Var nodes with varattno set to the
4953 * index's attribute number, not the attribute number in the original rel.
4954 *
4955 * *stripped_indexquals_p receives a list of the actual qual clauses.
4956 *
4957 * *fixed_indexquals_p receives a list of the adjusted quals. This is a copy
4958 * that shares no substructure with the original; this is needed in case there
4959 * are subplans in it (we need two separate copies of the subplan tree, or
4960 * things will go awry).
4961 */
4962static void
4965{
4966 IndexOptInfo *index = index_path->indexinfo;
4969 ListCell *lc;
4970
4972
4973 foreach(lc, index_path->indexclauses)
4974 {
4976 int indexcol = iclause->indexcol;
4977 ListCell *lc2;
4978
4979 foreach(lc2, iclause->indexquals)
4980 {
4982 Node *clause = (Node *) rinfo->clause;
4983
4985 clause = fix_indexqual_clause(root, index, indexcol,
4986 clause, iclause->indexcols);
4988 }
4989 }
4990
4993}
4994
4995/*
4996 * fix_indexorderby_references
4997 * Adjust indexorderby clauses to the form the executor's index
4998 * machinery needs.
4999 *
5000 * This is a simplified version of fix_indexqual_references. The input is
5001 * bare clauses and a separate indexcol list, instead of IndexClauses.
5002 */
5003static List *
5005{
5006 IndexOptInfo *index = index_path->indexinfo;
5008 ListCell *lcc,
5009 *lci;
5010
5012
5013 forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
5014 {
5015 Node *clause = (Node *) lfirst(lcc);
5016 int indexcol = lfirst_int(lci);
5017
5018 clause = fix_indexqual_clause(root, index, indexcol, clause, NIL);
5020 }
5021
5022 return fixed_indexorderbys;
5023}
5024
5025/*
5026 * fix_indexqual_clause
5027 * Convert a single indexqual clause to the form needed by the executor.
5028 *
5029 * We replace nestloop params here, and replace the index key variables
5030 * or expressions by index Var nodes.
5031 */
5032static Node *
5034 Node *clause, List *indexcolnos)
5035{
5036 /*
5037 * Replace any outer-relation variables with nestloop params.
5038 *
5039 * This also makes a copy of the clause, so it's safe to modify it
5040 * in-place below.
5041 */
5042 clause = replace_nestloop_params(root, clause);
5043
5044 if (IsA(clause, OpExpr))
5045 {
5046 OpExpr *op = (OpExpr *) clause;
5047
5048 /* Replace the indexkey expression with an index Var. */
5050 index,
5051 indexcol);
5052 }
5053 else if (IsA(clause, RowCompareExpr))
5054 {
5055 RowCompareExpr *rc = (RowCompareExpr *) clause;
5056 ListCell *lca,
5057 *lcai;
5058
5059 /* Replace the indexkey expressions with index Vars. */
5062 {
5064 index,
5065 lfirst_int(lcai));
5066 }
5067 }
5068 else if (IsA(clause, ScalarArrayOpExpr))
5069 {
5070 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
5071
5072 /* Replace the indexkey expression with an index Var. */
5074 index,
5075 indexcol);
5076 }
5077 else if (IsA(clause, NullTest))
5078 {
5079 NullTest *nt = (NullTest *) clause;
5080
5081 /* Replace the indexkey expression with an index Var. */
5082 nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
5083 index,
5084 indexcol);
5085 }
5086 else
5087 elog(ERROR, "unsupported indexqual type: %d",
5088 (int) nodeTag(clause));
5089
5090 return clause;
5091}
5092
5093/*
5094 * fix_indexqual_operand
5095 * Convert an indexqual expression to a Var referencing the index column.
5096 *
5097 * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
5098 * equal to the index's attribute number (index column position).
5099 *
5100 * Most of the code here is just for sanity cross-checking that the given
5101 * expression actually matches the index column it's claimed to. It should
5102 * match the logic in match_index_to_operand().
5103 */
5104static Node *
5106{
5107 Var *result;
5108 int pos;
5110
5111 Assert(indexcol >= 0 && indexcol < index->ncolumns);
5112
5113 /*
5114 * Remove any PlaceHolderVar wrapping of the indexkey
5115 */
5116 node = strip_phvs_in_index_operand(node);
5117
5118 /*
5119 * Remove any binary-compatible relabeling of the indexkey
5120 */
5121 while (IsA(node, RelabelType))
5122 node = (Node *) ((RelabelType *) node)->arg;
5123
5124 if (index->indexkeys[indexcol] != 0)
5125 {
5126 /* It's a simple index column */
5127 if (IsA(node, Var) &&
5128 ((Var *) node)->varno == index->rel->relid &&
5129 ((Var *) node)->varattno == index->indexkeys[indexcol])
5130 {
5131 result = (Var *) copyObject(node);
5132 result->varno = INDEX_VAR;
5133 result->varattno = indexcol + 1;
5134 return (Node *) result;
5135 }
5136 else
5137 elog(ERROR, "index key does not match expected index column");
5138 }
5139
5140 /* It's an index expression, so find and cross-check the expression */
5141 indexpr_item = list_head(index->indexprs);
5142 for (pos = 0; pos < index->ncolumns; pos++)
5143 {
5144 if (index->indexkeys[pos] == 0)
5145 {
5146 if (indexpr_item == NULL)
5147 elog(ERROR, "too few entries in indexprs list");
5148 if (pos == indexcol)
5149 {
5150 Node *indexkey;
5151
5154 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
5155 if (equal(node, indexkey))
5156 {
5157 result = makeVar(INDEX_VAR, indexcol + 1,
5160 0);
5161 return (Node *) result;
5162 }
5163 else
5164 elog(ERROR, "index key does not match expected index column");
5165 }
5166 indexpr_item = lnext(index->indexprs, indexpr_item);
5167 }
5168 }
5169
5170 /* Oops... */
5171 elog(ERROR, "index key does not match expected index column");
5172 return NULL; /* keep compiler quiet */
5173}
5174
5175/*
5176 * get_switched_clauses
5177 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
5178 * extract the bare clauses, and rearrange the elements within the
5179 * clauses, if needed, so the outer join variable is on the left and
5180 * the inner is on the right. The original clause data structure is not
5181 * touched; a modified list is returned. We do, however, set the transient
5182 * outer_is_left field in each RestrictInfo to show which side was which.
5183 */
5184static List *
5185get_switched_clauses(List *clauses, Relids outerrelids)
5186{
5187 List *t_list = NIL;
5188 ListCell *l;
5189
5190 foreach(l, clauses)
5191 {
5193 OpExpr *clause = (OpExpr *) restrictinfo->clause;
5194
5195 Assert(is_opclause(clause));
5196 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
5197 {
5198 /*
5199 * Duplicate just enough of the structure to allow commuting the
5200 * clause without changing the original list. Could use
5201 * copyObject, but a complete deep copy is overkill.
5202 */
5204
5205 temp->opno = clause->opno;
5206 temp->opfuncid = InvalidOid;
5207 temp->opresulttype = clause->opresulttype;
5208 temp->opretset = clause->opretset;
5209 temp->opcollid = clause->opcollid;
5210 temp->inputcollid = clause->inputcollid;
5211 temp->args = list_copy(clause->args);
5212 temp->location = clause->location;
5213 /* Commute it --- note this modifies the temp node in-place. */
5216 restrictinfo->outer_is_left = false;
5217 }
5218 else
5219 {
5220 Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
5221 t_list = lappend(t_list, clause);
5222 restrictinfo->outer_is_left = true;
5223 }
5224 }
5225 return t_list;
5226}
5227
5228/*
5229 * order_qual_clauses
5230 * Given a list of qual clauses that will all be evaluated at the same
5231 * plan node, sort the list into the order we want to check the quals
5232 * in at runtime.
5233 *
5234 * When security barrier quals are used in the query, we may have quals with
5235 * different security levels in the list. Quals of lower security_level
5236 * must go before quals of higher security_level, except that we can grant
5237 * exceptions to move up quals that are leakproof. When security level
5238 * doesn't force the decision, we prefer to order clauses by estimated
5239 * execution cost, cheapest first.
5240 *
5241 * Ideally the order should be driven by a combination of execution cost and
5242 * selectivity, but it's not immediately clear how to account for both,
5243 * and given the uncertainty of the estimates the reliability of the decisions
5244 * would be doubtful anyway. So we just order by security level then
5245 * estimated per-tuple cost, being careful not to change the order when
5246 * (as is often the case) the estimates are identical.
5247 *
5248 * Although this will work on either bare clauses or RestrictInfos, it's
5249 * much faster to apply it to RestrictInfos, since it can re-use cost
5250 * information that is cached in RestrictInfos. XXX in the bare-clause
5251 * case, we are also not able to apply security considerations. That is
5252 * all right for the moment, because the bare-clause case doesn't occur
5253 * anywhere that barrier quals could be present, but it would be better to
5254 * get rid of it.
5255 *
5256 * Note: some callers pass lists that contain entries that will later be
5257 * removed; this is the easiest way to let this routine see RestrictInfos
5258 * instead of bare clauses. This is another reason why trying to consider
5259 * selectivity in the ordering would likely do the wrong thing.
5260 */
5261static List *
5263{
5264 typedef struct
5265 {
5266 Node *clause;
5267 Cost cost;
5268 Index security_level;
5269 } QualItem;
5270 int nitems = list_length(clauses);
5271 QualItem *items;
5272 ListCell *lc;
5273 int i;
5274 List *result;
5275
5276 /* No need to work hard for 0 or 1 clause */
5277 if (nitems <= 1)
5278 return clauses;
5279
5280 /*
5281 * Collect the items and costs into an array. This is to avoid repeated
5282 * cost_qual_eval work if the inputs aren't RestrictInfos.
5283 */
5284 items = (QualItem *) palloc(nitems * sizeof(QualItem));
5285 i = 0;
5286 foreach(lc, clauses)
5287 {
5288 Node *clause = (Node *) lfirst(lc);
5290
5291 cost_qual_eval_node(&qcost, clause, root);
5292 items[i].clause = clause;
5293 items[i].cost = qcost.per_tuple;
5294 if (IsA(clause, RestrictInfo))
5295 {
5296 RestrictInfo *rinfo = (RestrictInfo *) clause;
5297
5298 /*
5299 * If a clause is leakproof, it doesn't have to be constrained by
5300 * its nominal security level. If it's also reasonably cheap
5301 * (here defined as 10X cpu_operator_cost), pretend it has
5302 * security_level 0, which will allow it to go in front of
5303 * more-expensive quals of lower security levels. Of course, that
5304 * will also force it to go in front of cheaper quals of its own
5305 * security level, which is not so great, but we can alleviate
5306 * that risk by applying the cost limit cutoff.
5307 */
5308 if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
5309 items[i].security_level = 0;
5310 else
5311 items[i].security_level = rinfo->security_level;
5312 }
5313 else
5314 items[i].security_level = 0;
5315 i++;
5316 }
5317
5318 /*
5319 * Sort. We don't use qsort() because it's not guaranteed stable for
5320 * equal keys. The expected number of entries is small enough that a
5321 * simple insertion sort should be good enough.
5322 */
5323 for (i = 1; i < nitems; i++)
5324 {
5325 QualItem newitem = items[i];
5326 int j;
5327
5328 /* insert newitem into the already-sorted subarray */
5329 for (j = i; j > 0; j--)
5330 {
5331 QualItem *olditem = &items[j - 1];
5332
5333 if (newitem.security_level > olditem->security_level ||
5334 (newitem.security_level == olditem->security_level &&
5335 newitem.cost >= olditem->cost))
5336 break;
5337 items[j] = *olditem;
5338 }
5339 items[j] = newitem;
5340 }
5341
5342 /* Convert back to a list */
5343 result = NIL;
5344 for (i = 0; i < nitems; i++)
5345 result = lappend(result, items[i].clause);
5346
5347 return result;
5348}
5349
5350/*
5351 * Copy cost and size info from a Path node to the Plan node created from it.
5352 * The executor usually won't use this info, but it's needed by EXPLAIN.
5353 * Also copy the parallel-related flags, which the executor *will* use.
5354 */
5355static void
5357{
5358 dest->disabled_nodes = src->disabled_nodes;
5359 dest->startup_cost = src->startup_cost;
5360 dest->total_cost = src->total_cost;
5361 dest->plan_rows = src->rows;
5362 dest->plan_width = src->pathtarget->width;
5363 dest->parallel_aware = src->parallel_aware;
5364 dest->parallel_safe = src->parallel_safe;
5365}
5366
5367/*
5368 * Copy cost and size info from a lower plan node to an inserted node.
5369 * (Most callers alter the info after copying it.)
5370 */
5371static void
5373{
5374 dest->disabled_nodes = src->disabled_nodes;
5375 dest->startup_cost = src->startup_cost;
5376 dest->total_cost = src->total_cost;
5377 dest->plan_rows = src->plan_rows;
5378 dest->plan_width = src->plan_width;
5379 /* Assume the inserted node is not parallel-aware. */
5380 dest->parallel_aware = false;
5381 /* Assume the inserted node is parallel-safe, if child plan is. */
5382 dest->parallel_safe = src->parallel_safe;
5383}
5384
5385/*
5386 * Some places in this file build Sort nodes that don't have a directly
5387 * corresponding Path node. The cost of the sort is, or should have been,
5388 * included in the cost of the Path node we're working from, but since it's
5389 * not split out, we have to re-figure it using cost_sort(). This is just
5390 * to label the Sort node nicely for EXPLAIN.
5391 *
5392 * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
5393 */
5394static void
5396{
5397 Plan *lefttree = plan->plan.lefttree;
5398 Path sort_path; /* dummy for result of cost_sort */
5399
5400 Assert(IsA(plan, Sort));
5401
5403 plan->plan.disabled_nodes,
5404 lefttree->total_cost,
5405 lefttree->plan_rows,
5406 lefttree->plan_width,
5407 0.0,
5408 work_mem,
5409 limit_tuples);
5410 plan->plan.startup_cost = sort_path.startup_cost;
5411 plan->plan.total_cost = sort_path.total_cost;
5412 plan->plan.plan_rows = lefttree->plan_rows;
5413 plan->plan.plan_width = lefttree->plan_width;
5414 plan->plan.parallel_aware = false;
5415 plan->plan.parallel_safe = lefttree->parallel_safe;
5416}
5417
5418/*
5419 * Same as label_sort_with_costsize, but labels the IncrementalSort node
5420 * instead.
5421 */
5422static void
5424 List *pathkeys, double limit_tuples)
5425{
5426 Plan *lefttree = plan->sort.plan.lefttree;
5427 Path sort_path; /* dummy for result of cost_incremental_sort */
5428
5430
5432 plan->nPresortedCols,
5433 plan->sort.plan.disabled_nodes,
5434 lefttree->startup_cost,
5435 lefttree->total_cost,
5436 lefttree->plan_rows,
5437 lefttree->plan_width,
5438 0.0,
5439 work_mem,
5440 limit_tuples);
5441 plan->sort.plan.startup_cost = sort_path.startup_cost;
5442 plan->sort.plan.total_cost = sort_path.total_cost;
5443 plan->sort.plan.plan_rows = lefttree->plan_rows;
5444 plan->sort.plan.plan_width = lefttree->plan_width;
5445 plan->sort.plan.parallel_aware = false;
5446 plan->sort.plan.parallel_safe = lefttree->parallel_safe;
5447}
5448
5449/*
5450 * bitmap_subplan_mark_shared
5451 * Set isshared flag in bitmap subplan so that it will be created in
5452 * shared memory.
5453 */
5454static void
5456{
5457 if (IsA(plan, BitmapAnd))
5459 else if (IsA(plan, BitmapOr))
5460 {
5461 ((BitmapOr *) plan)->isshared = true;
5462 bitmap_subplan_mark_shared(linitial(((BitmapOr *) plan)->bitmapplans));
5463 }
5464 else if (IsA(plan, BitmapIndexScan))
5465 ((BitmapIndexScan *) plan)->isshared = true;
5466 else
5467 elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
5468}
5469
5470/*****************************************************************************
5471 *
5472 * PLAN NODE BUILDING ROUTINES
5473 *
5474 * In general, these functions are not passed the original Path and therefore
5475 * leave it to the caller to fill in the cost/width fields from the Path,
5476 * typically by calling copy_generic_path_info(). This convention is
5477 * somewhat historical, but it does support a few places above where we build
5478 * a plan node without having an exactly corresponding Path node. Under no
5479 * circumstances should one of these functions do its own cost calculations,
5480 * as that would be redundant with calculations done while building Paths.
5481 *
5482 *****************************************************************************/
5483
5484static SeqScan *
5486 List *qpqual,
5487 Index scanrelid)
5488{
5489 SeqScan *node = makeNode(SeqScan);
5490 Plan *plan = &node->scan.plan;
5491
5492 plan->targetlist = qptlist;
5493 plan->qual = qpqual;
5494 plan->lefttree = NULL;
5495 plan->righttree = NULL;
5496 node->scan.scanrelid = scanrelid;
5497
5498 return node;
5499}
5500
5501static SampleScan *
5503 List *qpqual,
5504 Index scanrelid,
5506{
5508 Plan *plan = &node->scan.plan;
5509
5510 plan->targetlist = qptlist;
5511 plan->qual = qpqual;
5512 plan->lefttree = NULL;
5513 plan->righttree = NULL;
5514 node->scan.scanrelid = scanrelid;
5515 node->tablesample = tsc;
5516
5517 return node;
5518}
5519
5520static IndexScan *
5522 List *qpqual,
5523 Index scanrelid,
5524 Oid indexid,
5525 List *indexqual,
5526 List *indexqualorig,
5527 List *indexorderby,
5528 List *indexorderbyorig,
5529 List *indexorderbyops,
5530 ScanDirection indexscandir)
5531{
5532 IndexScan *node = makeNode(IndexScan);
5533 Plan *plan = &node->scan.plan;
5534
5535 plan->targetlist = qptlist;
5536 plan->qual = qpqual;
5537 plan->lefttree = NULL;
5538 plan->righttree = NULL;
5539 node->scan.scanrelid = scanrelid;
5540 node->indexid = indexid;
5541 node->indexqual = indexqual;
5542 node->indexqualorig = indexqualorig;
5543 node->indexorderby = indexorderby;
5544 node->indexorderbyorig = indexorderbyorig;
5545 node->indexorderbyops = indexorderbyops;
5546 node->indexorderdir = indexscandir;
5547
5548 return node;
5549}
5550
5551static IndexOnlyScan *
5553 List *qpqual,
5554 Index scanrelid,
5555 Oid indexid,
5556 List *indexqual,
5557 List *recheckqual,
5558 List *indexorderby,
5559 List *indextlist,
5560 ScanDirection indexscandir)
5561{
5563 Plan *plan = &node->scan.plan;
5564
5565 plan->targetlist = qptlist;
5566 plan->qual = qpqual;
5567 plan->lefttree = NULL;
5568 plan->righttree = NULL;
5569 node->scan.scanrelid = scanrelid;
5570 node->indexid = indexid;
5571 node->indexqual = indexqual;
5572 node->recheckqual = recheckqual;
5573 node->indexorderby = indexorderby;
5574 node->indextlist = indextlist;
5575 node->indexorderdir = indexscandir;
5576
5577 return node;
5578}
5579
5580static BitmapIndexScan *
5582 Oid indexid,
5583 List *indexqual,
5584 List *indexqualorig)
5585{
5587 Plan *plan = &node->scan.plan;
5588
5589 plan->targetlist = NIL; /* not used */
5590 plan->qual = NIL; /* not used */
5591 plan->lefttree = NULL;
5592 plan->righttree = NULL;
5593 node->scan.scanrelid = scanrelid;
5594 node->indexid = indexid;
5595 node->indexqual = indexqual;
5596 node->indexqualorig = indexqualorig;
5597
5598 return node;
5599}
5600
5601static BitmapHeapScan *
5603 List *qpqual,
5604 Plan *lefttree,
5605 List *bitmapqualorig,
5606 Index scanrelid)
5607{
5609 Plan *plan = &node->scan.plan;
5610
5611 plan->targetlist = qptlist;
5612 plan->qual = qpqual;
5613 plan->lefttree = lefttree;
5614 plan->righttree = NULL;
5615 node->scan.scanrelid = scanrelid;
5616 node->bitmapqualorig = bitmapqualorig;
5617
5618 return node;
5619}
5620
5621static TidScan *
5623 List *qpqual,
5624 Index scanrelid,
5625 List *tidquals)
5626{
5627 TidScan *node = makeNode(TidScan);
5628 Plan *plan = &node->scan.plan;
5629
5630 plan->targetlist = qptlist;
5631 plan->qual = qpqual;
5632 plan->lefttree = NULL;
5633 plan->righttree = NULL;
5634 node->scan.scanrelid = scanrelid;
5635 node->tidquals = tidquals;
5636
5637 return node;
5638}
5639
5640static TidRangeScan *
5642 List *qpqual,
5643 Index scanrelid,
5644 List *tidrangequals)
5645{
5647 Plan *plan = &node->scan.plan;
5648
5649 plan->targetlist = qptlist;
5650 plan->qual = qpqual;
5651 plan->lefttree = NULL;
5652 plan->righttree = NULL;
5653 node->scan.scanrelid = scanrelid;
5654 node->tidrangequals = tidrangequals;
5655
5656 return node;
5657}
5658
5659static SubqueryScan *
5661 List *qpqual,
5662 Index scanrelid,
5663 Plan *subplan)
5664{
5666 Plan *plan = &node->scan.plan;
5667
5668 plan->targetlist = qptlist;
5669 plan->qual = qpqual;
5670 plan->lefttree = NULL;
5671 plan->righttree = NULL;
5672 node->scan.scanrelid = scanrelid;
5673 node->subplan = subplan;
5675
5676 return node;
5677}
5678
5679static FunctionScan *
5681 List *qpqual,
5682 Index scanrelid,
5683 List *functions,
5684 bool funcordinality)
5685{
5687 Plan *plan = &node->scan.plan;
5688
5689 plan->targetlist = qptlist;
5690 plan->qual = qpqual;
5691 plan->lefttree = NULL;
5692 plan->righttree = NULL;
5693 node->scan.scanrelid = scanrelid;
5694 node->functions = functions;
5695 node->funcordinality = funcordinality;
5696
5697 return node;
5698}
5699
5700static TableFuncScan *
5702 List *qpqual,
5703 Index scanrelid,
5704 TableFunc *tablefunc)
5705{
5707 Plan *plan = &node->scan.plan;
5708
5709 plan->targetlist = qptlist;
5710 plan->qual = qpqual;
5711 plan->lefttree = NULL;
5712 plan->righttree = NULL;
5713 node->scan.scanrelid = scanrelid;
5714 node->tablefunc = tablefunc;
5715
5716 return node;
5717}
5718
5719static ValuesScan *
5721 List *qpqual,
5722 Index scanrelid,
5723 List *values_lists)
5724{
5726 Plan *plan = &node->scan.plan;
5727
5728 plan->targetlist = qptlist;
5729 plan->qual = qpqual;
5730 plan->lefttree = NULL;
5731 plan->righttree = NULL;
5732 node->scan.scanrelid = scanrelid;
5733 node->values_lists = values_lists;
5734
5735 return node;
5736}
5737
5738static CteScan *
5740 List *qpqual,
5741 Index scanrelid,
5742 int ctePlanId,
5743 int cteParam)
5744{
5745 CteScan *node = makeNode(CteScan);
5746 Plan *plan = &node->scan.plan;
5747
5748 plan->targetlist = qptlist;
5749 plan->qual = qpqual;
5750 plan->lefttree = NULL;
5751 plan->righttree = NULL;
5752 node->scan.scanrelid = scanrelid;
5753 node->ctePlanId = ctePlanId;
5754 node->cteParam = cteParam;
5755
5756 return node;
5757}
5758
5759static NamedTuplestoreScan *
5761 List *qpqual,
5762 Index scanrelid,
5763 char *enrname)
5764{
5766 Plan *plan = &node->scan.plan;
5767
5768 /* cost should be inserted by caller */
5769 plan->targetlist = qptlist;
5770 plan->qual = qpqual;
5771 plan->lefttree = NULL;
5772 plan->righttree = NULL;
5773 node->scan.scanrelid = scanrelid;
5774 node->enrname = enrname;
5775
5776 return node;
5777}
5778
5779static WorkTableScan *
5781 List *qpqual,
5782 Index scanrelid,
5783 int wtParam)
5784{
5786 Plan *plan = &node->scan.plan;
5787
5788 plan->targetlist = qptlist;
5789 plan->qual = qpqual;
5790 plan->lefttree = NULL;
5791 plan->righttree = NULL;
5792 node->scan.scanrelid = scanrelid;
5793 node->wtParam = wtParam;
5794
5795 return node;
5796}
5797
5800 List *qpqual,
5801 Index scanrelid,
5802 List *fdw_exprs,
5803 List *fdw_private,
5804 List *fdw_scan_tlist,
5805 List *fdw_recheck_quals,
5806 Plan *outer_plan)
5807{
5809 Plan *plan = &node->scan.plan;
5810
5811 /* cost will be filled in by create_foreignscan_plan */
5812 plan->targetlist = qptlist;
5813 plan->qual = qpqual;
5814 plan->lefttree = outer_plan;
5815 plan->righttree = NULL;
5816 node->scan.scanrelid = scanrelid;
5817
5818 /* these may be overridden by the FDW's PlanDirectModify callback. */
5819 node->operation = CMD_SELECT;
5820 node->resultRelation = 0;
5821
5822 /* checkAsUser, fs_server will be filled in by create_foreignscan_plan */
5823 node->checkAsUser = InvalidOid;
5824 node->fs_server = InvalidOid;
5825 node->fdw_exprs = fdw_exprs;
5826 node->fdw_private = fdw_private;
5827 node->fdw_scan_tlist = fdw_scan_tlist;
5828 node->fdw_recheck_quals = fdw_recheck_quals;
5829 /* fs_relids, fs_base_relids will be filled by create_foreignscan_plan */
5830 node->fs_relids = NULL;
5831 node->fs_base_relids = NULL;
5832 /* fsSystemCol will be filled in by create_foreignscan_plan */
5833 node->fsSystemCol = false;
5834
5835 return node;
5836}
5837
5838static RecursiveUnion *
5840 Plan *lefttree,
5841 Plan *righttree,
5842 int wtParam,
5843 List *distinctList,
5844 Cardinality numGroups)
5845{
5847 Plan *plan = &node->plan;
5848 int numCols = list_length(distinctList);
5849
5850 plan->targetlist = tlist;
5851 plan->qual = NIL;
5852 plan->lefttree = lefttree;
5853 plan->righttree = righttree;
5854 node->wtParam = wtParam;
5855
5856 /*
5857 * convert SortGroupClause list into arrays of attr indexes and equality
5858 * operators, as wanted by executor
5859 */
5860 node->numCols = numCols;
5861 if (numCols > 0)
5862 {
5863 int keyno = 0;
5868
5869 dupColIdx = palloc_array(AttrNumber, numCols);
5870 dupOperators = palloc_array(Oid, numCols);
5871 dupCollations = palloc_array(Oid, numCols);
5872
5873 foreach(slitem, distinctList)
5874 {
5877 plan->targetlist);
5878
5879 dupColIdx[keyno] = tle->resno;
5880 dupOperators[keyno] = sortcl->eqop;
5881 dupCollations[keyno] = exprCollation((Node *) tle->expr);
5883 keyno++;
5884 }
5885 node->dupColIdx = dupColIdx;
5886 node->dupOperators = dupOperators;
5887 node->dupCollations = dupCollations;
5888 }
5889 node->numGroups = numGroups;
5890
5891 return node;
5892}
5893
5894static BitmapAnd *
5896{
5897 BitmapAnd *node = makeNode(BitmapAnd);
5898 Plan *plan = &node->plan;
5899
5900 plan->targetlist = NIL;
5901 plan->qual = NIL;
5902 plan->lefttree = NULL;
5903 plan->righttree = NULL;
5904 node->bitmapplans = bitmapplans;
5905
5906 return node;
5907}
5908
5909static BitmapOr *
5911{
5912 BitmapOr *node = makeNode(BitmapOr);
5913 Plan *plan = &node->plan;
5914
5915 plan->targetlist = NIL;
5916 plan->qual = NIL;
5917 plan->lefttree = NULL;
5918 plan->righttree = NULL;
5919 node->bitmapplans = bitmapplans;
5920
5921 return node;
5922}
5923
5924static NestLoop *
5926 List *joinclauses,
5928 List *nestParams,
5929 Plan *lefttree,
5930 Plan *righttree,
5931 JoinType jointype,
5932 bool inner_unique)
5933{
5934 NestLoop *node = makeNode(NestLoop);
5935 Plan *plan = &node->join.plan;
5936
5937 plan->targetlist = tlist;
5938 plan->qual = otherclauses;
5939 plan->lefttree = lefttree;
5940 plan->righttree = righttree;
5941 node->join.jointype = jointype;
5942 node->join.inner_unique = inner_unique;
5943 node->join.joinqual = joinclauses;
5944 node->nestParams = nestParams;
5945
5946 return node;
5947}
5948
5949static HashJoin *
5951 List *joinclauses,
5953 List *hashclauses,
5954 List *hashoperators,
5955 List *hashcollations,
5956 List *hashkeys,
5957 Plan *lefttree,
5958 Plan *righttree,
5959 JoinType jointype,
5960 bool inner_unique)
5961{
5962 HashJoin *node = makeNode(HashJoin);
5963 Plan *plan = &node->join.plan;
5964
5965 plan->targetlist = tlist;
5966 plan->qual = otherclauses;
5967 plan->lefttree = lefttree;
5968 plan->righttree = righttree;
5969 node->hashclauses = hashclauses;
5970 node->hashoperators = hashoperators;
5971 node->hashcollations = hashcollations;
5972 node->hashkeys = hashkeys;
5973 node->join.jointype = jointype;
5974 node->join.inner_unique = inner_unique;
5975 node->join.joinqual = joinclauses;
5976
5977 return node;
5978}
5979
5980static Hash *
5981make_hash(Plan *lefttree,
5982 List *hashkeys,
5983 Oid skewTable,
5984 AttrNumber skewColumn,
5985 bool skewInherit)
5986{
5987 Hash *node = makeNode(Hash);
5988 Plan *plan = &node->plan;
5989
5990 plan->targetlist = lefttree->targetlist;
5991 plan->qual = NIL;
5992 plan->lefttree = lefttree;
5993 plan->righttree = NULL;
5994
5995 node->hashkeys = hashkeys;
5996 node->skewTable = skewTable;
5997 node->skewColumn = skewColumn;
5998 node->skewInherit = skewInherit;
5999
6000 return node;
6001}
6002
6003static MergeJoin *
6005 List *joinclauses,
6007 List *mergeclauses,
6010 bool *mergereversals,
6011 bool *mergenullsfirst,
6012 Plan *lefttree,
6013 Plan *righttree,
6014 JoinType jointype,
6015 bool inner_unique,
6016 bool skip_mark_restore)
6017{
6018 MergeJoin *node = makeNode(MergeJoin);
6019 Plan *plan = &node->join.plan;
6020
6021 plan->targetlist = tlist;
6022 plan->qual = otherclauses;
6023 plan->lefttree = lefttree;
6024 plan->righttree = righttree;
6025 node->skip_mark_restore = skip_mark_restore;
6026 node->mergeclauses = mergeclauses;
6027 node->mergeFamilies = mergefamilies;
6028 node->mergeCollations = mergecollations;
6029 node->mergeReversals = mergereversals;
6030 node->mergeNullsFirst = mergenullsfirst;
6031 node->join.jointype = jointype;
6032 node->join.inner_unique = inner_unique;
6033 node->join.joinqual = joinclauses;
6034
6035 return node;
6036}
6037
6038/*
6039 * make_sort --- basic routine to build a Sort plan node
6040 *
6041 * Caller must have built the sortColIdx, sortOperators, collations, and
6042 * nullsFirst arrays already.
6043 */
6044static Sort *
6045make_sort(Plan *lefttree, int numCols,
6046 AttrNumber *sortColIdx, Oid *sortOperators,
6047 Oid *collations, bool *nullsFirst)
6048{
6049 Sort *node;
6050 Plan *plan;
6051
6052 node = makeNode(Sort);
6053
6054 plan = &node->plan;
6055 plan->targetlist = lefttree->targetlist;
6056 plan->disabled_nodes = lefttree->disabled_nodes + (enable_sort == false);
6057 plan->qual = NIL;
6058 plan->lefttree = lefttree;
6059 plan->righttree = NULL;
6060 node->numCols = numCols;
6061 node->sortColIdx = sortColIdx;
6062 node->sortOperators = sortOperators;
6063 node->collations = collations;
6064 node->nullsFirst = nullsFirst;
6065
6066 return node;
6067}
6068
6069/*
6070 * make_incrementalsort --- basic routine to build an IncrementalSort plan node
6071 *
6072 * Caller must have built the sortColIdx, sortOperators, collations, and
6073 * nullsFirst arrays already.
6074 */
6075static IncrementalSort *
6076make_incrementalsort(Plan *lefttree, int numCols, int nPresortedCols,
6077 AttrNumber *sortColIdx, Oid *sortOperators,
6078 Oid *collations, bool *nullsFirst)
6079{
6080 IncrementalSort *node;
6081 Plan *plan;
6082
6083 node = makeNode(IncrementalSort);
6084
6085 plan = &node->sort.plan;
6086 plan->targetlist = lefttree->targetlist;
6087 plan->qual = NIL;
6088 plan->lefttree = lefttree;
6089 plan->righttree = NULL;
6090 node->nPresortedCols = nPresortedCols;
6091 node->sort.numCols = numCols;
6092 node->sort.sortColIdx = sortColIdx;
6093 node->sort.sortOperators = sortOperators;
6094 node->sort.collations = collations;
6095 node->sort.nullsFirst = nullsFirst;
6096
6097 return node;
6098}
6099
6100/*
6101 * prepare_sort_from_pathkeys
6102 * Prepare to sort according to given pathkeys
6103 *
6104 * This is used to set up for Sort, MergeAppend, and Gather Merge nodes. It
6105 * calculates the executor's representation of the sort key information, and
6106 * adjusts the plan targetlist if needed to add resjunk sort columns.
6107 *
6108 * Input parameters:
6109 * 'lefttree' is the plan node which yields input tuples
6110 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
6111 * 'relids' identifies the child relation being sorted, if any
6112 * 'reqColIdx' is NULL or an array of required sort key column numbers
6113 * 'adjust_tlist_in_place' is true if lefttree must be modified in-place
6114 *
6115 * We must convert the pathkey information into arrays of sort key column
6116 * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
6117 * which is the representation the executor wants. These are returned into
6118 * the output parameters *p_numsortkeys etc.
6119 *
6120 * When looking for matches to an EquivalenceClass's members, we will only
6121 * consider child EC members if they belong to given 'relids'. This protects
6122 * against possible incorrect matches to child expressions that contain no
6123 * Vars.
6124 *
6125 * If reqColIdx isn't NULL then it contains sort key column numbers that
6126 * we should match. This is used when making child plans for a MergeAppend;
6127 * it's an error if we can't match the columns.
6128 *
6129 * If the pathkeys include expressions that aren't simple Vars, we will
6130 * usually need to add resjunk items to the input plan's targetlist to
6131 * compute these expressions, since a Sort or MergeAppend node itself won't
6132 * do any such calculations. If the input plan type isn't one that can do
6133 * projections, this means adding a Result node just to do the projection.
6134 * However, the caller can pass adjust_tlist_in_place = true to force the
6135 * lefttree tlist to be modified in-place regardless of whether the node type
6136 * can project --- we use this for fixing the tlist of MergeAppend itself.
6137 *
6138 * Returns the node which is to be the input to the Sort (either lefttree,
6139 * or a Result stacked atop lefttree).
6140 */
6141static Plan *
6143 Relids relids,
6144 const AttrNumber *reqColIdx,
6146 int *p_numsortkeys,
6149 Oid **p_collations,
6150 bool **p_nullsFirst)
6151{
6152 List *tlist = lefttree->targetlist;
6153 ListCell *i;
6154 int numsortkeys;
6155 AttrNumber *sortColIdx;
6156 Oid *sortOperators;
6157 Oid *collations;
6158 bool *nullsFirst;
6159
6160 /*
6161 * We will need at most list_length(pathkeys) sort columns; possibly less
6162 */
6163 numsortkeys = list_length(pathkeys);
6164 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
6165 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
6166 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
6167 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
6168
6169 numsortkeys = 0;
6170
6171 foreach(i, pathkeys)
6172 {
6173 PathKey *pathkey = (PathKey *) lfirst(i);
6174 EquivalenceClass *ec = pathkey->pk_eclass;
6176 TargetEntry *tle = NULL;
6178 Oid sortop;
6179 ListCell *j;
6180
6181 if (ec->ec_has_volatile)
6182 {
6183 /*
6184 * If the pathkey's EquivalenceClass is volatile, then it must
6185 * have come from an ORDER BY clause, and we have to match it to
6186 * that same targetlist entry.
6187 */
6188 if (ec->ec_sortref == 0) /* can't happen */
6189 elog(ERROR, "volatile EquivalenceClass has no sortref");
6190 tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
6191 Assert(tle);
6192 Assert(list_length(ec->ec_members) == 1);
6193 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
6194 }
6195 else if (reqColIdx != NULL)
6196 {
6197 /*
6198 * If we are given a sort column number to match, only consider
6199 * the single TLE at that position. It's possible that there is
6200 * no such TLE, in which case fall through and generate a resjunk
6201 * targetentry (we assume this must have happened in the parent
6202 * plan as well). If there is a TLE but it doesn't match the
6203 * pathkey's EC, we do the same, which is probably the wrong thing
6204 * but we'll leave it to caller to complain about the mismatch.
6205 */
6207 if (tle)
6208 {
6209 em = find_ec_member_matching_expr(ec, tle->expr, relids);
6210 if (em)
6211 {
6212 /* found expr at right place in tlist */
6213 pk_datatype = em->em_datatype;
6214 }
6215 else
6216 tle = NULL;
6217 }
6218 }
6219 else
6220 {
6221 /*
6222 * Otherwise, we can sort by any non-constant expression listed in
6223 * the pathkey's EquivalenceClass. For now, we take the first
6224 * tlist item found in the EC. If there's no match, we'll generate
6225 * a resjunk entry using the first EC member that is an expression
6226 * in the input's vars.
6227 *
6228 * XXX if we have a choice, is there any way of figuring out which
6229 * might be cheapest to execute? (For example, int4lt is likely
6230 * much cheaper to execute than numericlt, but both might appear
6231 * in the same equivalence class...) Not clear that we ever will
6232 * have an interesting choice in practice, so it may not matter.
6233 */
6234 foreach(j, tlist)
6235 {
6236 tle = (TargetEntry *) lfirst(j);
6237 em = find_ec_member_matching_expr(ec, tle->expr, relids);
6238 if (em)
6239 {
6240 /* found expr already in tlist */
6241 pk_datatype = em->em_datatype;
6242 break;
6243 }
6244 tle = NULL;
6245 }
6246 }
6247
6248 if (!tle)
6249 {
6250 /*
6251 * No matching tlist item; look for a computable expression.
6252 */
6253 em = find_computable_ec_member(NULL, ec, tlist, relids, false);
6254 if (!em)
6255 elog(ERROR, "could not find pathkey item to sort");
6256 pk_datatype = em->em_datatype;
6257
6258 /*
6259 * Do we need to insert a Result node?
6260 */
6261 if (!adjust_tlist_in_place &&
6262 !is_projection_capable_plan(lefttree))
6263 {
6264 /* copy needed so we don't modify input's tlist below */
6265 tlist = copyObject(tlist);
6266 lefttree = inject_projection_plan(lefttree, tlist,
6267 lefttree->parallel_safe);
6268 }
6269
6270 /* Don't bother testing is_projection_capable_plan again */
6271 adjust_tlist_in_place = true;
6272
6273 /*
6274 * Add resjunk entry to input's tlist
6275 */
6276 tle = makeTargetEntry(copyObject(em->em_expr),
6277 list_length(tlist) + 1,
6278 NULL,
6279 true);
6280 tlist = lappend(tlist, tle);
6281 lefttree->targetlist = tlist; /* just in case NIL before */
6282 }
6283
6284 /*
6285 * Look up the correct sort operator from the PathKey's slightly
6286 * abstracted representation.
6287 */
6288 sortop = get_opfamily_member_for_cmptype(pathkey->pk_opfamily,
6291 pathkey->pk_cmptype);
6292 if (!OidIsValid(sortop)) /* should not happen */
6293 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6294 pathkey->pk_cmptype, pk_datatype, pk_datatype,
6295 pathkey->pk_opfamily);
6296
6297 /* Add the column to the sort arrays */
6298 sortColIdx[numsortkeys] = tle->resno;
6299 sortOperators[numsortkeys] = sortop;
6300 collations[numsortkeys] = ec->ec_collation;
6301 nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
6302 numsortkeys++;
6303 }
6304
6305 /* Return results */
6307 *p_sortColIdx = sortColIdx;
6308 *p_sortOperators = sortOperators;
6309 *p_collations = collations;
6311
6312 return lefttree;
6313}
6314
6315/*
6316 * make_sort_from_pathkeys
6317 * Create sort plan to sort according to given pathkeys
6318 *
6319 * 'lefttree' is the node which yields input tuples
6320 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
6321 * 'relids' is the set of relations required by prepare_sort_from_pathkeys()
6322 */
6323static Sort *
6324make_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids)
6325{
6326 int numsortkeys;
6327 AttrNumber *sortColIdx;
6328 Oid *sortOperators;
6329 Oid *collations;
6330 bool *nullsFirst;
6331
6332 /* Compute sort column info, and adjust lefttree as needed */
6333 lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
6334 relids,
6335 NULL,
6336 false,
6337 &numsortkeys,
6338 &sortColIdx,
6339 &sortOperators,
6340 &collations,
6341 &nullsFirst);
6342
6343 /* Now build the Sort node */
6344 return make_sort(lefttree, numsortkeys,
6345 sortColIdx, sortOperators,
6346 collations, nullsFirst);
6347}
6348
6349/*
6350 * make_incrementalsort_from_pathkeys
6351 * Create sort plan to sort according to given pathkeys
6352 *
6353 * 'lefttree' is the node which yields input tuples
6354 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
6355 * 'relids' is the set of relations required by prepare_sort_from_pathkeys()
6356 * 'nPresortedCols' is the number of presorted columns in input tuples
6357 */
6358static IncrementalSort *
6360 Relids relids, int nPresortedCols)
6361{
6362 int numsortkeys;
6363 AttrNumber *sortColIdx;
6364 Oid *sortOperators;
6365 Oid *collations;
6366 bool *nullsFirst;
6367
6368 /* Compute sort column info, and adjust lefttree as needed */
6369 lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
6370 relids,
6371 NULL,
6372 false,
6373 &numsortkeys,
6374 &sortColIdx,
6375 &sortOperators,
6376 &collations,
6377 &nullsFirst);
6378
6379 /* Now build the Sort node */
6380 return make_incrementalsort(lefttree, numsortkeys, nPresortedCols,
6381 sortColIdx, sortOperators,
6382 collations, nullsFirst);
6383}
6384
6385/*
6386 * make_sort_from_sortclauses
6387 * Create sort plan to sort according to given sortclauses
6388 *
6389 * 'sortcls' is a list of SortGroupClauses
6390 * 'lefttree' is the node which yields input tuples
6391 */
6392Sort *
6394{
6395 List *sub_tlist = lefttree->targetlist;
6396 ListCell *l;
6397 int numsortkeys;
6398 AttrNumber *sortColIdx;
6399 Oid *sortOperators;
6400 Oid *collations;
6401 bool *nullsFirst;
6402
6403 /* Convert list-ish representation to arrays wanted by executor */
6405 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
6406 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
6407 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
6408 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
6409
6410 numsortkeys = 0;
6411 foreach(l, sortcls)
6412 {
6415
6416 sortColIdx[numsortkeys] = tle->resno;
6417 sortOperators[numsortkeys] = sortcl->sortop;
6418 collations[numsortkeys] = exprCollation((Node *) tle->expr);
6419 nullsFirst[numsortkeys] = sortcl->nulls_first;
6420 numsortkeys++;
6421 }
6422
6423 return make_sort(lefttree, numsortkeys,
6424 sortColIdx, sortOperators,
6425 collations, nullsFirst);
6426}
6427
6428/*
6429 * make_sort_from_groupcols
6430 * Create sort plan to sort based on grouping columns
6431 *
6432 * 'groupcls' is the list of SortGroupClauses
6433 * 'grpColIdx' gives the column numbers to use
6434 *
6435 * This might look like it could be merged with make_sort_from_sortclauses,
6436 * but presently we *must* use the grpColIdx[] array to locate sort columns,
6437 * because the child plan's tlist is not marked with ressortgroupref info
6438 * appropriate to the grouping node. So, only the sort ordering info
6439 * is used from the SortGroupClause entries.
6440 */
6441static Sort *
6444 Plan *lefttree)
6445{
6446 List *sub_tlist = lefttree->targetlist;
6447 ListCell *l;
6448 int numsortkeys;
6449 AttrNumber *sortColIdx;
6450 Oid *sortOperators;
6451 Oid *collations;
6452 bool *nullsFirst;
6453
6454 /* Convert list-ish representation to arrays wanted by executor */
6456 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
6457 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
6458 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
6459 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
6460
6461 numsortkeys = 0;
6462 foreach(l, groupcls)
6463 {
6466
6467 if (!tle)
6468 elog(ERROR, "could not retrieve tle for sort-from-groupcols");
6469
6470 sortColIdx[numsortkeys] = tle->resno;
6471 sortOperators[numsortkeys] = grpcl->sortop;
6472 collations[numsortkeys] = exprCollation((Node *) tle->expr);
6473 nullsFirst[numsortkeys] = grpcl->nulls_first;
6474 numsortkeys++;
6475 }
6476
6477 return make_sort(lefttree, numsortkeys,
6478 sortColIdx, sortOperators,
6479 collations, nullsFirst);
6480}
6481
6482static Material *
6484{
6485 Material *node = makeNode(Material);
6486 Plan *plan = &node->plan;
6487
6488 plan->targetlist = lefttree->targetlist;
6489 plan->qual = NIL;
6490 plan->lefttree = lefttree;
6491 plan->righttree = NULL;
6492
6493 return node;
6494}
6495
6496/*
6497 * materialize_finished_plan: stick a Material node atop a completed plan
6498 *
6499 * There are a couple of places where we want to attach a Material node
6500 * after completion of create_plan(), without any MaterialPath path.
6501 * Those places should probably be refactored someday to do this on the
6502 * Path representation, but it's not worth the trouble yet.
6503 */
6504Plan *
6506{
6507 Plan *matplan;
6508 Path matpath; /* dummy for cost_material */
6510 bool unsafe_initplans;
6511
6512 matplan = (Plan *) make_material(subplan);
6513
6514 /*
6515 * XXX horrid kluge: if there are any initPlans attached to the subplan,
6516 * move them up to the Material node, which is now effectively the top
6517 * plan node in its query level. This prevents failure in
6518 * SS_finalize_plan(), which see for comments.
6519 */
6520 matplan->initPlan = subplan->initPlan;
6521 subplan->initPlan = NIL;
6522
6523 /* Move the initplans' cost delta, as well */
6526 subplan->startup_cost -= initplan_cost;
6527 subplan->total_cost -= initplan_cost;
6528
6529 /* Clear fields that cost_material() will consult */
6530 matpath.parallel_workers = 0;
6531 matpath.parent = NULL;
6532
6533 /* Set cost data */
6536 subplan->disabled_nodes,
6537 subplan->startup_cost,
6538 subplan->total_cost,
6539 subplan->plan_rows,
6540 subplan->plan_width);
6541 matplan->disabled_nodes = subplan->disabled_nodes;
6542 matplan->startup_cost = matpath.startup_cost + initplan_cost;
6543 matplan->total_cost = matpath.total_cost + initplan_cost;
6544 matplan->plan_rows = subplan->plan_rows;
6545 matplan->plan_width = subplan->plan_width;
6546 matplan->parallel_aware = false;
6547 matplan->parallel_safe = subplan->parallel_safe;
6548
6549 return matplan;
6550}
6551
6552static Memoize *
6553make_memoize(Plan *lefttree, Oid *hashoperators, Oid *collations,
6554 List *param_exprs, bool singlerow, bool binary_mode,
6555 uint32 est_entries, Bitmapset *keyparamids,
6556 Cardinality est_calls, Cardinality est_unique_keys,
6557 double est_hit_ratio)
6558{
6559 Memoize *node = makeNode(Memoize);
6560 Plan *plan = &node->plan;
6561
6562 plan->targetlist = lefttree->targetlist;
6563 plan->qual = NIL;
6564 plan->lefttree = lefttree;
6565 plan->righttree = NULL;
6566
6567 node->numKeys = list_length(param_exprs);
6568 node->hashOperators = hashoperators;
6569 node->collations = collations;
6570 node->param_exprs = param_exprs;
6571 node->singlerow = singlerow;
6572 node->binary_mode = binary_mode;
6573 node->est_entries = est_entries;
6574 node->keyparamids = keyparamids;
6575 node->est_calls = est_calls;
6576 node->est_unique_keys = est_unique_keys;
6577 node->est_hit_ratio = est_hit_ratio;
6578
6579 return node;
6580}
6581
6582Agg *
6583make_agg(List *tlist, List *qual,
6584 AggStrategy aggstrategy, AggSplit aggsplit,
6586 List *groupingSets, List *chain, Cardinality numGroups,
6587 Size transitionSpace, Plan *lefttree)
6588{
6589 Agg *node = makeNode(Agg);
6590 Plan *plan = &node->plan;
6591
6592 node->aggstrategy = aggstrategy;
6593 node->aggsplit = aggsplit;
6594 node->numCols = numGroupCols;
6595 node->grpColIdx = grpColIdx;
6596 node->grpOperators = grpOperators;
6597 node->grpCollations = grpCollations;
6598 node->numGroups = numGroups;
6599 node->transitionSpace = transitionSpace;
6600 node->aggParams = NULL; /* SS_finalize_plan() will fill this */
6601 node->groupingSets = groupingSets;
6602 node->chain = chain;
6603
6604 plan->qual = qual;
6605 plan->targetlist = tlist;
6606 plan->lefttree = lefttree;
6607 plan->righttree = NULL;
6608
6609 return node;
6610}
6611
6612static WindowAgg *
6616 List *runCondition, List *qual, bool topWindow, Plan *lefttree)
6617{
6618 WindowAgg *node = makeNode(WindowAgg);
6619 Plan *plan = &node->plan;
6620
6621 node->winname = wc->name;
6622 node->winref = wc->winref;
6623 node->partNumCols = partNumCols;
6624 node->partColIdx = partColIdx;
6625 node->partOperators = partOperators;
6626 node->partCollations = partCollations;
6627 node->ordNumCols = ordNumCols;
6628 node->ordColIdx = ordColIdx;
6629 node->ordOperators = ordOperators;
6630 node->ordCollations = ordCollations;
6631 node->frameOptions = wc->frameOptions;
6632 node->startOffset = wc->startOffset;
6633 node->endOffset = wc->endOffset;
6634 node->runCondition = runCondition;
6635 /* a duplicate of the above for EXPLAIN */
6636 node->runConditionOrig = runCondition;
6637 node->startInRangeFunc = wc->startInRangeFunc;
6638 node->endInRangeFunc = wc->endInRangeFunc;
6639 node->inRangeColl = wc->inRangeColl;
6640 node->inRangeAsc = wc->inRangeAsc;
6641 node->inRangeNullsFirst = wc->inRangeNullsFirst;
6642 node->topWindow = topWindow;
6643
6644 plan->targetlist = tlist;
6645 plan->lefttree = lefttree;
6646 plan->righttree = NULL;
6647 plan->qual = qual;
6648
6649 return node;
6650}
6651
6652static Group *
6654 List *qual,
6655 int numGroupCols,
6659 Plan *lefttree)
6660{
6661 Group *node = makeNode(Group);
6662 Plan *plan = &node->plan;
6663
6664 node->numCols = numGroupCols;
6665 node->grpColIdx = grpColIdx;
6666 node->grpOperators = grpOperators;
6667 node->grpCollations = grpCollations;
6668
6669 plan->qual = qual;
6670 plan->targetlist = tlist;
6671 plan->lefttree = lefttree;
6672 plan->righttree = NULL;
6673
6674 return node;
6675}
6676
6677/*
6678 * pathkeys is a list of PathKeys, identifying the sort columns and semantics.
6679 * The input plan must already be sorted accordingly.
6680 *
6681 * relids identifies the child relation being unique-ified, if any.
6682 */
6683static Unique *
6684make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols,
6685 Relids relids)
6686{
6687 Unique *node = makeNode(Unique);
6688 Plan *plan = &node->plan;
6689 int keyno = 0;
6693 ListCell *lc;
6694
6695 plan->targetlist = lefttree->targetlist;
6696 plan->qual = NIL;
6697 plan->lefttree = lefttree;
6698 plan->righttree = NULL;
6699
6700 /*
6701 * Convert pathkeys list into arrays of attr indexes and equality
6702 * operators, as wanted by executor. This has a lot in common with
6703 * prepare_sort_from_pathkeys ... maybe unify sometime?
6704 */
6705 Assert(numCols >= 0 && numCols <= list_length(pathkeys));
6707 uniqOperators = palloc_array(Oid, numCols);
6708 uniqCollations = palloc_array(Oid, numCols);
6709
6710 foreach(lc, pathkeys)
6711 {
6713 EquivalenceClass *ec = pathkey->pk_eclass;
6715 TargetEntry *tle = NULL;
6717 Oid eqop;
6718 ListCell *j;
6719
6720 /* Ignore pathkeys beyond the specified number of columns */
6721 if (keyno >= numCols)
6722 break;
6723
6724 if (ec->ec_has_volatile)
6725 {
6726 /*
6727 * If the pathkey's EquivalenceClass is volatile, then it must
6728 * have come from an ORDER BY clause, and we have to match it to
6729 * that same targetlist entry.
6730 */
6731 if (ec->ec_sortref == 0) /* can't happen */
6732 elog(ERROR, "volatile EquivalenceClass has no sortref");
6733 tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
6734 Assert(tle);
6735 Assert(list_length(ec->ec_members) == 1);
6736 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
6737 }
6738 else
6739 {
6740 /*
6741 * Otherwise, we can use any non-constant expression listed in the
6742 * pathkey's EquivalenceClass. For now, we take the first tlist
6743 * item found in the EC.
6744 */
6745 foreach(j, plan->targetlist)
6746 {
6747 tle = (TargetEntry *) lfirst(j);
6748 em = find_ec_member_matching_expr(ec, tle->expr, relids);
6749 if (em)
6750 {
6751 /* found expr already in tlist */
6752 pk_datatype = em->em_datatype;
6753 break;
6754 }
6755 tle = NULL;
6756 }
6757 }
6758
6759 if (!tle)
6760 elog(ERROR, "could not find pathkey item to sort");
6761
6762 /*
6763 * Look up the correct equality operator from the PathKey's slightly
6764 * abstracted representation.
6765 */
6766 eqop = get_opfamily_member_for_cmptype(pathkey->pk_opfamily,
6769 COMPARE_EQ);
6770 if (!OidIsValid(eqop)) /* should not happen */
6771 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
6773 pathkey->pk_opfamily);
6774
6775 uniqColIdx[keyno] = tle->resno;
6776 uniqOperators[keyno] = eqop;
6777 uniqCollations[keyno] = ec->ec_collation;
6778
6779 keyno++;
6780 }
6781
6782 node->numCols = numCols;
6783 node->uniqColIdx = uniqColIdx;
6784 node->uniqOperators = uniqOperators;
6785 node->uniqCollations = uniqCollations;
6786
6787 return node;
6788}
6789
6790static Gather *
6792 List *qpqual,
6793 int nworkers,
6794 int rescan_param,
6795 bool single_copy,
6796 Plan *subplan)
6797{
6798 Gather *node = makeNode(Gather);
6799 Plan *plan = &node->plan;
6800
6802 plan->qual = qpqual;
6803 plan->lefttree = subplan;
6804 plan->righttree = NULL;
6805 node->num_workers = nworkers;
6806 node->rescan_param = rescan_param;
6807 node->single_copy = single_copy;
6808 node->invisible = false;
6809 node->initParam = NULL;
6810
6811 return node;
6812}
6813
6814/*
6815 * groupList is a list of SortGroupClauses, identifying the targetlist
6816 * items that should be considered by the SetOp filter. The input plans must
6817 * already be sorted accordingly, if we're doing SETOP_SORTED mode.
6818 */
6819static SetOp *
6821 List *tlist, Plan *lefttree, Plan *righttree,
6822 List *groupList, Cardinality numGroups)
6823{
6824 SetOp *node = makeNode(SetOp);
6825 Plan *plan = &node->plan;
6826 int numCols = list_length(groupList);
6827 int keyno = 0;
6831 bool *cmpNullsFirst;
6833
6834 plan->targetlist = tlist;
6835 plan->qual = NIL;
6836 plan->lefttree = lefttree;
6837 plan->righttree = righttree;
6838
6839 /*
6840 * convert SortGroupClause list into arrays of attr indexes and comparison
6841 * operators, as wanted by executor
6842 */
6843 cmpColIdx = palloc_array(AttrNumber, numCols);
6844 cmpOperators = palloc_array(Oid, numCols);
6845 cmpCollations = palloc_array(Oid, numCols);
6846 cmpNullsFirst = palloc_array(bool, numCols);
6847
6848 foreach(slitem, groupList)
6849 {
6852
6853 cmpColIdx[keyno] = tle->resno;
6854 if (strategy == SETOP_HASHED)
6855 cmpOperators[keyno] = sortcl->eqop;
6856 else
6857 cmpOperators[keyno] = sortcl->sortop;
6859 cmpCollations[keyno] = exprCollation((Node *) tle->expr);
6860 cmpNullsFirst[keyno] = sortcl->nulls_first;
6861 keyno++;
6862 }
6863
6864 node->cmd = cmd;
6865 node->strategy = strategy;
6866 node->numCols = numCols;
6867 node->cmpColIdx = cmpColIdx;
6868 node->cmpOperators = cmpOperators;
6869 node->cmpCollations = cmpCollations;
6870 node->cmpNullsFirst = cmpNullsFirst;
6871 node->numGroups = numGroups;
6872
6873 return node;
6874}
6875
6876/*
6877 * make_lockrows
6878 * Build a LockRows plan node
6879 */
6880static LockRows *
6881make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
6882{
6883 LockRows *node = makeNode(LockRows);
6884 Plan *plan = &node->plan;
6885
6886 plan->targetlist = lefttree->targetlist;
6887 plan->qual = NIL;
6888 plan->lefttree = lefttree;
6889 plan->righttree = NULL;
6890
6891 node->rowMarks = rowMarks;
6892 node->epqParam = epqParam;
6893
6894 return node;
6895}
6896
6897/*
6898 * make_limit
6899 * Build a Limit plan node
6900 */
6901Limit *
6902make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
6903 LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx,
6905{
6906 Limit *node = makeNode(Limit);
6907 Plan *plan = &node->plan;
6908
6909 plan->targetlist = lefttree->targetlist;
6910 plan->qual = NIL;
6911 plan->lefttree = lefttree;
6912 plan->righttree = NULL;
6913
6914 node->limitOffset = limitOffset;
6915 node->limitCount = limitCount;
6916 node->limitOption = limitOption;
6917 node->uniqNumCols = uniqNumCols;
6918 node->uniqColIdx = uniqColIdx;
6919 node->uniqOperators = uniqOperators;
6920 node->uniqCollations = uniqCollations;
6921
6922 return node;
6923}
6924
6925/*
6926 * make_gating_result
6927 * Build a Result plan node that performs projection of a subplan, and/or
6928 * applies a one time filter (resconstantqual)
6929 */
6930static Result *
6932 Node *resconstantqual,
6933 Plan *subplan)
6934{
6935 Result *node = makeNode(Result);
6936 Plan *plan = &node->plan;
6937
6938 Assert(subplan != NULL);
6939
6940 plan->targetlist = tlist;
6941 plan->qual = NIL;
6942 plan->lefttree = subplan;
6943 plan->righttree = NULL;
6945 node->resconstantqual = resconstantqual;
6946 node->relids = NULL;
6947
6948 return node;
6949}
6950
6951/*
6952 * make_one_row_result
6953 * Build a Result plan node that returns a single row (or possibly no rows,
6954 * if the one-time filtered defined by resconstantqual returns false)
6955 *
6956 * 'rel' should be this path's RelOptInfo. In essence, we're saying that this
6957 * Result node generates all the tuples for that RelOptInfo. Note that the same
6958 * consideration can never arise in make_gating_result(), because in that case
6959 * the tuples are always coming from some subordinate node.
6960 */
6961static Result *
6963 Node *resconstantqual,
6964 RelOptInfo *rel)
6965{
6966 Result *node = makeNode(Result);
6967 Plan *plan = &node->plan;
6968
6969 plan->targetlist = tlist;
6970 plan->qual = NIL;
6971 plan->lefttree = NULL;
6972 plan->righttree = NULL;
6975 node->resconstantqual = resconstantqual;
6976 node->relids = rel->relids;
6977
6978 return node;
6979}
6980
6981/*
6982 * make_project_set
6983 * Build a ProjectSet plan node
6984 */
6985static ProjectSet *
6987 Plan *subplan)
6988{
6990 Plan *plan = &node->plan;
6991
6992 plan->targetlist = tlist;
6993 plan->qual = NIL;
6994 plan->lefttree = subplan;
6995 plan->righttree = NULL;
6996
6997 return node;
6998}
6999
7000/*
7001 * make_modifytable
7002 * Build a ModifyTable plan node
7003 */
7004static ModifyTable *
7006 CmdType operation, bool canSetTag,
7007 Index nominalRelation, Index rootRelation,
7008 List *resultRelations,
7009 List *updateColnosLists,
7010 List *withCheckOptionLists, List *returningLists,
7011 List *rowMarks, OnConflictExpr *onconflict,
7012 List *mergeActionLists, List *mergeJoinConditions,
7013 int epqParam)
7014{
7016 bool returning_old_or_new = false;
7017 bool returning_old_or_new_valid = false;
7018 bool transition_tables = false;
7019 bool transition_tables_valid = false;
7022 ListCell *lc;
7023 int i;
7024
7025 Assert(operation == CMD_MERGE ||
7026 (operation == CMD_UPDATE ?
7027 list_length(resultRelations) == list_length(updateColnosLists) :
7028 updateColnosLists == NIL));
7029 Assert(withCheckOptionLists == NIL ||
7030 list_length(resultRelations) == list_length(withCheckOptionLists));
7031 Assert(returningLists == NIL ||
7032 list_length(resultRelations) == list_length(returningLists));
7033
7034 node->plan.lefttree = subplan;
7035 node->plan.righttree = NULL;
7036 node->plan.qual = NIL;
7037 /* setrefs.c will fill in the targetlist, if needed */
7038 node->plan.targetlist = NIL;
7039
7040 node->operation = operation;
7041 node->canSetTag = canSetTag;
7042 node->nominalRelation = nominalRelation;
7043 node->rootRelation = rootRelation;
7044 node->resultRelations = resultRelations;
7045 if (!onconflict)
7046 {
7048 node->onConflictSet = NIL;
7049 node->onConflictCols = NIL;
7050 node->onConflictWhere = NULL;
7051 node->arbiterIndexes = NIL;
7052 node->exclRelRTI = 0;
7053 node->exclRelTlist = NIL;
7054 }
7055 else
7056 {
7057 node->onConflictAction = onconflict->action;
7058
7059 /*
7060 * Here we convert the ON CONFLICT UPDATE tlist, if any, to the
7061 * executor's convention of having consecutive resno's. The actual
7062 * target column numbers are saved in node->onConflictCols. (This
7063 * could be done earlier, but there seems no need to.)
7064 */
7065 node->onConflictSet = onconflict->onConflictSet;
7066 node->onConflictCols =
7068 node->onConflictWhere = onconflict->onConflictWhere;
7069
7070 /*
7071 * If a set of unique index inference elements was provided (an
7072 * INSERT...ON CONFLICT "inference specification"), then infer
7073 * appropriate unique indexes (or throw an error if none are
7074 * available).
7075 */
7077
7078 node->exclRelRTI = onconflict->exclRelIndex;
7079 node->exclRelTlist = onconflict->exclRelTlist;
7080 }
7081 node->updateColnosLists = updateColnosLists;
7082 node->withCheckOptionLists = withCheckOptionLists;
7083 node->returningOldAlias = root->parse->returningOldAlias;
7084 node->returningNewAlias = root->parse->returningNewAlias;
7085 node->returningLists = returningLists;
7086 node->rowMarks = rowMarks;
7087 node->mergeActionLists = mergeActionLists;
7088 node->mergeJoinConditions = mergeJoinConditions;
7089 node->epqParam = epqParam;
7090
7091 /*
7092 * For each result relation that is a foreign table, allow the FDW to
7093 * construct private plan data, and accumulate it all into a list.
7094 */
7097 i = 0;
7098 foreach(lc, resultRelations)
7099 {
7100 Index rti = lfirst_int(lc);
7101 FdwRoutine *fdwroutine;
7102 List *fdw_private;
7103 bool direct_modify;
7104
7105 /*
7106 * If possible, we want to get the FdwRoutine from our RelOptInfo for
7107 * the table. But sometimes we don't have a RelOptInfo and must get
7108 * it the hard way. (In INSERT, the target relation is not scanned,
7109 * so it's not a baserel; and there are also corner cases for
7110 * updatable views where the target rel isn't a baserel.)
7111 */
7112 if (rti < root->simple_rel_array_size &&
7113 root->simple_rel_array[rti] != NULL)
7114 {
7115 RelOptInfo *resultRel = root->simple_rel_array[rti];
7116
7117 fdwroutine = resultRel->fdwroutine;
7118 }
7119 else
7120 {
7122
7123 if (rte->rtekind == RTE_RELATION &&
7124 rte->relkind == RELKIND_FOREIGN_TABLE)
7125 {
7126 /* Check if the access to foreign tables is restricted */
7128 {
7129 /* there must not be built-in foreign tables */
7130 Assert(rte->relid >= FirstNormalObjectId);
7131 ereport(ERROR,
7133 errmsg("access to non-system foreign table is restricted")));
7134 }
7135
7136 fdwroutine = GetFdwRoutineByRelId(rte->relid);
7137 }
7138 else
7139 fdwroutine = NULL;
7140 }
7141
7142 /*
7143 * MERGE is not currently supported for foreign tables. We already
7144 * checked that when the table mentioned in the query is foreign; but
7145 * we can still get here if a partitioned table has a foreign table as
7146 * partition. Disallow that now, to avoid an uglier error message
7147 * later.
7148 */
7149 if (operation == CMD_MERGE && fdwroutine != NULL)
7150 {
7152
7153 ereport(ERROR,
7155 errmsg("cannot execute MERGE on relation \"%s\"",
7156 get_rel_name(rte->relid)),
7158 }
7159
7160 /*
7161 * Try to modify the foreign table directly if (1) the FDW provides
7162 * callback functions needed for that and (2) there are no local
7163 * structures that need to be run for each modified row: row-level
7164 * triggers on the foreign table, stored generated columns, WITH CHECK
7165 * OPTIONs from parent views, Vars returning OLD/NEW in the RETURNING
7166 * list, or transition tables on the named relation.
7167 */
7168 direct_modify = false;
7169 if (fdwroutine != NULL &&
7170 fdwroutine->PlanDirectModify != NULL &&
7171 fdwroutine->BeginDirectModify != NULL &&
7172 fdwroutine->IterateDirectModify != NULL &&
7173 fdwroutine->EndDirectModify != NULL &&
7174 withCheckOptionLists == NIL &&
7175 !has_row_triggers(root, rti, operation) &&
7177 {
7178 /*
7179 * returning_old_or_new and transition_tables are the same for all
7180 * result relations, respectively
7181 */
7183 {
7186 root->parse->returningList);
7188 }
7190 {
7192 {
7194 nominalRelation,
7195 operation);
7197 }
7198 if (!transition_tables)
7199 direct_modify = fdwroutine->PlanDirectModify(root, node,
7200 rti, i);
7201 }
7202 }
7203 if (direct_modify)
7205
7206 if (!direct_modify &&
7207 fdwroutine != NULL &&
7208 fdwroutine->PlanForeignModify != NULL)
7209 fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
7210 else
7211 fdw_private = NIL;
7213 i++;
7214 }
7217
7218 return node;
7219}
7220
7221/*
7222 * is_projection_capable_path
7223 * Check whether a given Path node is able to do projection.
7224 */
7225bool
7227{
7228 /* Most plan types can project, so just list the ones that can't */
7229 switch (path->pathtype)
7230 {
7231 case T_Hash:
7232 case T_Material:
7233 case T_Memoize:
7234 case T_Sort:
7235 case T_IncrementalSort:
7236 case T_Unique:
7237 case T_SetOp:
7238 case T_LockRows:
7239 case T_Limit:
7240 case T_ModifyTable:
7241 case T_MergeAppend:
7242 case T_RecursiveUnion:
7243 return false;
7244 case T_CustomScan:
7246 return true;
7247 return false;
7248 case T_Append:
7249
7250 /*
7251 * Append can't project, but if an AppendPath is being used to
7252 * represent a dummy path, what will actually be generated is a
7253 * Result which can project.
7254 */
7255 return IS_DUMMY_APPEND(path);
7256 case T_ProjectSet:
7257
7258 /*
7259 * Although ProjectSet certainly projects, say "no" because we
7260 * don't want the planner to randomly replace its tlist with
7261 * something else; the SRFs have to stay at top level. This might
7262 * get relaxed later.
7263 */
7264 return false;
7265 default:
7266 break;
7267 }
7268 return true;
7269}
7270
7271/*
7272 * is_projection_capable_plan
7273 * Check whether a given Plan node is able to do projection.
7274 */
7275bool
7277{
7278 /* Most plan types can project, so just list the ones that can't */
7279 switch (nodeTag(plan))
7280 {
7281 case T_Hash:
7282 case T_Material:
7283 case T_Memoize:
7284 case T_Sort:
7285 case T_Unique:
7286 case T_SetOp:
7287 case T_LockRows:
7288 case T_Limit:
7289 case T_ModifyTable:
7290 case T_Append:
7291 case T_MergeAppend:
7292 case T_RecursiveUnion:
7293 return false;
7294 case T_CustomScan:
7296 return true;
7297 return false;
7298 case T_ProjectSet:
7299
7300 /*
7301 * Although ProjectSet certainly projects, say "no" because we
7302 * don't want the planner to randomly replace its tlist with
7303 * something else; the SRFs have to stay at top level. This might
7304 * get relaxed later.
7305 */
7306 return false;
7307 default:
7308 break;
7309 }
7310 return true;
7311}
Datum sort(PG_FUNCTION_ARGS)
Definition _int_op.c:198
int16 AttrNumber
Definition attnum.h:21
#define InvalidAttrNumber
Definition attnum.h:23
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:346
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:412
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:814
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:251
bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:640
#define bms_is_empty(a)
Definition bitmapset.h:118
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:223
#define Assert(condition)
Definition c.h:873
#define unlikely(x)
Definition c.h:412
uint32_t uint32
Definition c.h:546
unsigned int Index
Definition c.h:628
#define OidIsValid(objectId)
Definition c.h:788
size_t Size
Definition c.h:619
bool contain_mutable_functions(Node *clause)
Definition clauses.c:379
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition clauses.c:762
Bitmapset * pull_paramids(Expr *expr)
Definition clauses.c:5800
void CommuteOpExpr(OpExpr *clause)
Definition clauses.c:2159
@ COMPARE_GT
Definition cmptype.h:38
@ COMPARE_EQ
Definition cmptype.h:36
double cpu_operator_cost
Definition costsize.c:134
void cost_material(Path *path, bool enabled, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
Definition costsize.c:2582
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, int input_disabled_nodes, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition costsize.c:2200
bool enable_material
Definition costsize.c:154
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition costsize.c:4929
void cost_incremental_sort(Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition costsize.c:2052
bool enable_async_append
Definition costsize.c:165
double clamp_row_est(double nrows)
Definition costsize.c:213
bool enable_partition_pruning
Definition costsize.c:163
bool enable_sort
Definition costsize.c:150
bool enable_incremental_sort
Definition costsize.c:151
static Plan * create_join_plan(PlannerInfo *root, JoinPath *best_path)
static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags)
Definition createplan.c:856
static ModifyTable * make_modifytable(PlannerInfo *root, Plan *subplan, CmdType operation, bool canSetTag, Index nominalRelation, Index rootRelation, List *resultRelations, List *updateColnosLists, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, List *mergeActionLists, List *mergeJoinConditions, int epqParam)
static SeqScan * create_seqscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static WorkTableScan * make_worktablescan(List *qptlist, List *qpqual, Index scanrelid, int wtParam)
static Plan * create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path, int flags)
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
static MergeJoin * make_mergejoin(List *tlist, List *joinclauses, List *otherclauses, List *mergeclauses, Oid *mergefamilies, Oid *mergecollations, bool *mergereversals, bool *mergenullsfirst, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique, bool skip_mark_restore)
static GatherMerge * create_gather_merge_plan(PlannerInfo *root, GatherMergePath *best_path)
static ValuesScan * create_valuesscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static void copy_generic_path_info(Plan *dest, Path *src)
static WindowAgg * make_windowagg(List *tlist, WindowClause *wc, int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations, int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations, List *runCondition, List *qual, bool topWindow, Plan *lefttree)
Sort * make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
static BitmapOr * make_bitmap_or(List *bitmapplans)
static HashJoin * create_hashjoin_plan(PlannerInfo *root, HashPath *best_path)
static SeqScan * make_seqscan(List *qptlist, List *qpqual, Index scanrelid)
static TableFuncScan * create_tablefuncscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static CustomScan * create_customscan_plan(PlannerInfo *root, CustomPath *best_path, List *tlist, List *scan_clauses)
static Node * fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
static void fix_indexqual_references(PlannerInfo *root, IndexPath *index_path, List **stripped_indexquals_p, List **fixed_indexquals_p)
static List * fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
static AttrNumber * remap_groupColIdx(PlannerInfo *root, List *groupClause)
static Plan * create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
static void bitmap_subplan_mark_shared(Plan *plan)
static Unique * create_unique_plan(PlannerInfo *root, UniquePath *best_path, int flags)
static Result * make_one_row_result(List *tlist, Node *resconstantqual, RelOptInfo *rel)
static TidScan * make_tidscan(List *qptlist, List *qpqual, Index scanrelid, List *tidquals)
static MergeJoin * create_mergejoin_plan(PlannerInfo *root, MergePath *best_path)
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition createplan.c:389
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
static ForeignScan * create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path, List *tlist, List *scan_clauses)
static BitmapHeapScan * create_bitmap_scan_plan(PlannerInfo *root, BitmapHeapPath *best_path, List *tlist, List *scan_clauses)
static IncrementalSort * make_incrementalsort(Plan *lefttree, int numCols, int nPresortedCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
static Result * create_group_result_plan(PlannerInfo *root, GroupResultPath *best_path)
static Limit * create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
static Unique * make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols, Relids relids)
static Agg * create_agg_plan(PlannerInfo *root, AggPath *best_path)
bool is_projection_capable_path(Path *path)
static CteScan * make_ctescan(List *qptlist, List *qpqual, Index scanrelid, int ctePlanId, int cteParam)
static TidScan * create_tidscan_plan(PlannerInfo *root, TidPath *best_path, List *tlist, List *scan_clauses)
static TidRangeScan * make_tidrangescan(List *qptlist, List *qpqual, Index scanrelid, List *tidrangequals)
static Plan * create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs)
static RecursiveUnion * make_recursive_union(List *tlist, Plan *lefttree, Plan *righttree, int wtParam, List *distinctList, Cardinality numGroups)
static Node * fix_indexqual_clause(PlannerInfo *root, IndexOptInfo *index, int indexcol, Node *clause, List *indexcolnos)
static WorkTableScan * create_worktablescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static Plan * create_gating_plan(PlannerInfo *root, Path *path, Plan *plan, List *gating_quals)
static Memoize * make_memoize(Plan *lefttree, Oid *hashoperators, Oid *collations, List *param_exprs, bool singlerow, bool binary_mode, uint32 est_entries, Bitmapset *keyparamids, Cardinality est_calls, Cardinality est_unique_keys, double est_hit_ratio)
static FunctionScan * create_functionscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static Result * create_resultscan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static BitmapHeapScan * make_bitmap_heapscan(List *qptlist, List *qpqual, Plan *lefttree, List *bitmapqualorig, Index scanrelid)
static Node * replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
static SetOp * create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
bool is_projection_capable_plan(Plan *plan)
static CteScan * create_ctescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static Sort * create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
#define CP_SMALL_TLIST
Definition createplan.c:69
static ProjectSet * make_project_set(List *tlist, Plan *subplan)
static Sort * make_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids)
static HashJoin * make_hashjoin(List *tlist, List *joinclauses, List *otherclauses, List *hashclauses, List *hashoperators, List *hashcollations, List *hashkeys, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
static Gather * make_gather(List *qptlist, List *qpqual, int nworkers, int rescan_param, bool single_copy, Plan *subplan)
static Gather * create_gather_plan(PlannerInfo *root, GatherPath *best_path)
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Limit * make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount, LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx, Oid *uniqOperators, Oid *uniqCollations)
static ProjectSet * create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path)
static void label_incrementalsort_with_costsize(PlannerInfo *root, IncrementalSort *plan, List *pathkeys, double limit_tuples)
static SetOp * make_setop(SetOpCmd cmd, SetOpStrategy strategy, List *tlist, Plan *lefttree, Plan *righttree, List *groupList, Cardinality numGroups)
ForeignScan * make_foreignscan(List *qptlist, List *qpqual, Index scanrelid, List *fdw_exprs, List *fdw_private, List *fdw_scan_tlist, List *fdw_recheck_quals, Plan *outer_plan)
static Group * create_group_plan(PlannerInfo *root, GroupPath *best_path)
static ModifyTable * create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
static Result * create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
static LockRows * create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path, int flags)
static Material * create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
static List * get_gating_quals(PlannerInfo *root, List *quals)
Definition createplan.c:993
static Plan * create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
Definition createplan.c:550
static Group * make_group(List *tlist, List *qual, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, Plan *lefttree)
static LockRows * make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
static IncrementalSort * create_incrementalsort_plan(PlannerInfo *root, IncrementalSortPath *best_path, int flags)
static NamedTuplestoreScan * create_namedtuplestorescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
static Plan * create_projection_plan(PlannerInfo *root, ProjectionPath *best_path, int flags)
static IndexOnlyScan * make_indexonlyscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *recheckqual, List *indexorderby, List *indextlist, ScanDirection indexscandir)
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition createplan.c:816
static IndexScan * make_indexscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig, List *indexorderby, List *indexorderbyorig, List *indexorderbyops, ScanDirection indexscandir)
static FunctionScan * make_functionscan(List *qptlist, List *qpqual, Index scanrelid, List *functions, bool funcordinality)
static TableFuncScan * make_tablefuncscan(List *qptlist, List *qpqual, Index scanrelid, TableFunc *tablefunc)
static SubqueryScan * create_subqueryscan_plan(PlannerInfo *root, SubqueryScanPath *best_path, List *tlist, List *scan_clauses)
static Plan * inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
static TidRangeScan * create_tidrangescan_plan(PlannerInfo *root, TidRangePath *best_path, List *tlist, List *scan_clauses)
static List * get_switched_clauses(List *clauses, Relids outerrelids)
static void copy_plan_costsize(Plan *dest, Plan *src)
static ValuesScan * make_valuesscan(List *qptlist, List *qpqual, Index scanrelid, List *values_lists)
Plan * materialize_finished_plan(Plan *subplan)
static SampleScan * make_samplescan(List *qptlist, List *qpqual, Index scanrelid, TableSampleClause *tsc)
static NestLoop * create_nestloop_plan(PlannerInfo *root, NestPath *best_path)
static Memoize * create_memoize_plan(PlannerInfo *root, MemoizePath *best_path, int flags)
static Result * make_gating_result(List *tlist, Node *resconstantqual, Plan *subplan)
Agg * make_agg(List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, List *groupingSets, List *chain, Cardinality numGroups, Size transitionSpace, Plan *lefttree)
#define CP_EXACT_TLIST
Definition createplan.c:68
static NamedTuplestoreScan * make_namedtuplestorescan(List *qptlist, List *qpqual, Index scanrelid, char *enrname)
static bool mark_async_capable_plan(Plan *plan, Path *path)
static Material * make_material(Plan *lefttree)
Plan * change_plan_targetlist(Plan *subplan, List *tlist, bool tlist_parallel_safe)
static NestLoop * make_nestloop(List *tlist, List *joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
static BitmapIndexScan * make_bitmap_indexscan(Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig)
static SubqueryScan * make_subqueryscan(List *qptlist, List *qpqual, Index scanrelid, Plan *subplan)
static Hash * make_hash(Plan *lefttree, List *hashkeys, Oid skewTable, AttrNumber skewColumn, bool skewInherit)
static WindowAgg * create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
#define CP_LABEL_TLIST
Definition createplan.c:70
static BitmapAnd * make_bitmap_and(List *bitmapplans)
static Plan * create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path)
static RecursiveUnion * create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
static Sort * make_sort_from_groupcols(List *groupcls, AttrNumber *grpColIdx, Plan *lefttree)
#define CP_IGNORE_TLIST
Definition createplan.c:71
static Scan * create_indexscan_plan(PlannerInfo *root, IndexPath *best_path, List *tlist, List *scan_clauses, bool indexonly)
static Plan * prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst)
static IncrementalSort * make_incrementalsort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids, int nPresortedCols)
static SampleScan * create_samplescan_plan(PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition createplan.c:338
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
EquivalenceMember * find_ec_member_matching_expr(EquivalenceClass *ec, Expr *expr, Relids relids)
Definition equivclass.c:916
EquivalenceMember * find_computable_ec_member(PlannerInfo *root, EquivalenceClass *ec, List *exprs, Relids relids, bool require_parallel_safe)
Definition equivclass.c:991
bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
#define CUSTOMPATH_SUPPORT_PROJECTION
Definition extensible.h:86
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_array(type, count)
Definition fe_memutils.h:77
FdwRoutine * GetFdwRoutineByRelId(Oid relid)
Definition foreign.c:420
int work_mem
Definition globals.c:131
void parse(int)
Definition parse.c:49
#define nitems(x)
Definition indent.h:31
Node * strip_phvs_in_index_operand(Node *operand)
Definition indxpath.c:4449
return true
Definition isn.c:130
int j
Definition isn.c:78
int i
Definition isn.c:77
List * list_difference(const List *list1, const List *list2)
Definition list.c:1237
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_difference_ptr(const List *list1, const List *list2)
Definition list.c:1263
List * list_concat(List *list1, const List *list2)
Definition list.c:561
List * list_concat_copy(const List *list1, const List *list2)
Definition list.c:598
List * list_copy(const List *oldlist)
Definition list.c:1573
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
bool list_member_ptr(const List *list, const void *datum)
Definition list.c:682
bool list_member(const List *list, const void *datum)
Definition list.c:661
List * list_copy_head(const List *oldlist, int len)
Definition list.c:1593
List * list_concat_unique(List *list1, const List *list2)
Definition list.c:1405
char * get_rel_name(Oid relid)
Definition lsyscache.c:2078
Oid get_opfamily_member_for_cmptype(Oid opfamily, Oid lefttype, Oid righttype, CompareType cmptype)
Definition lsyscache.c:197
Datum lca(PG_FUNCTION_ARGS)
Definition ltree_op.c:563
Datum subpath(PG_FUNCTION_ARGS)
Definition ltree_op.c:311
Expr * make_orclause(List *orclauses)
Definition makefuncs.c:743
Expr * make_ands_explicit(List *andclauses)
Definition makefuncs.c:799
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
Node * makeBoolConst(bool value, bool isnull)
Definition makefuncs.c:408
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition makefuncs.c:289
void * palloc0(Size size)
Definition mcxt.c:1417
void * palloc(Size size)
Definition mcxt.c:1387
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:821
#define expression_tree_mutator(n, m, c)
Definition nodeFuncs.h:155
static bool is_opclause(const void *clause)
Definition nodeFuncs.h:76
SetOpCmd
Definition nodes.h:407
SetOpStrategy
Definition nodes.h:415
@ SETOP_HASHED
Definition nodes.h:417
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define copyObject(obj)
Definition nodes.h:232
double Cost
Definition nodes.h:261
#define nodeTag(nodeptr)
Definition nodes.h:139
#define IS_OUTER_JOIN(jointype)
Definition nodes.h:348
@ ONCONFLICT_NONE
Definition nodes.h:428
double Cardinality
Definition nodes.h:262
CmdType
Definition nodes.h:273
@ CMD_MERGE
Definition nodes.h:279
@ CMD_UPDATE
Definition nodes.h:276
@ CMD_SELECT
Definition nodes.h:275
AggStrategy
Definition nodes.h:363
@ AGG_SORTED
Definition nodes.h:365
@ AGG_HASHED
Definition nodes.h:366
@ AGG_PLAIN
Definition nodes.h:364
AggSplit
Definition nodes.h:385
@ AGGSPLIT_SIMPLE
Definition nodes.h:387
LimitOption
Definition nodes.h:440
@ LIMIT_OPTION_WITH_TIES
Definition nodes.h:442
#define makeNode(_type_)
Definition nodes.h:161
#define castNode(_type_, nodeptr)
Definition nodes.h:182
JoinType
Definition nodes.h:298
void process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
List * identify_current_nestloop_params(PlannerInfo *root, Relids leftrelids, Relids outerrelids)
Param * replace_nestloop_param_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
int assign_special_exec_param(PlannerInfo *root)
Param * replace_nestloop_param_var(PlannerInfo *root, Var *var)
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
@ RTE_CTE
@ RTE_NAMEDTUPLESTORE
@ RTE_VALUES
@ RTE_SUBQUERY
@ RTE_RESULT
@ RTE_FUNCTION
@ RTE_TABLEFUNC
@ RTE_RELATION
int make_partition_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel, List *subpaths, List *prunequal)
Definition partprune.c:224
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition pathkeys.c:558
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition pathkeys.c:343
Path * reparameterize_path_by_child(PlannerInfo *root, Path *path, RelOptInfo *child_rel)
Definition pathnode.c:4029
#define IS_DUMMY_APPEND(p)
Definition pathnodes.h:2264
#define IS_JOIN_REL(rel)
Definition pathnodes.h:976
#define PATH_REQ_OUTER(path)
Definition pathnodes.h:1995
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:686
@ RELOPT_BASEREL
Definition pathnodes.h:959
@ RELOPT_UPPER_REL
Definition pathnodes.h:963
#define IS_OTHER_REL(rel)
Definition pathnodes.h:986
#define IS_UPPER_REL(rel)
Definition pathnodes.h:981
void * arg
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
#define lfirst(lc)
Definition pg_list.h:172
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:518
#define lfirst_int(lc)
Definition pg_list.h:173
#define list_make1(x1)
Definition pg_list.h:212
#define linitial_int(l)
Definition pg_list.h:179
#define for_each_from(cell, lst, N)
Definition pg_list.h:414
#define linitial(l)
Definition pg_list.h:178
#define lsecond(l)
Definition pg_list.h:183
static ListCell * list_head(const List *l)
Definition pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:343
#define lfirst_oid(lc)
Definition pg_list.h:174
static int list_nth_int(const List *list, int n)
Definition pg_list.h:310
#define plan(x)
Definition pg_regress.c:161
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv)
Definition placeholder.c:83
bool has_stored_generated_columns(PlannerInfo *root, Index rti)
Definition plancat.c:2615
bool has_row_triggers(PlannerInfo *root, Index rti, CmdType event)
Definition plancat.c:2511
List * build_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
Definition plancat.c:2044
bool has_transition_tables(PlannerInfo *root, Index rti, CmdType event)
Definition plancat.c:2561
List * infer_arbiter_indexes(PlannerInfo *root)
Definition plancat.c:816
@ SUBQUERY_SCAN_UNKNOWN
Definition plannodes.h:747
@ RESULT_TYPE_UPPER
Definition plannodes.h:274
@ RESULT_TYPE_SCAN
Definition plannodes.h:272
@ RESULT_TYPE_GATING
Definition plannodes.h:271
@ RESULT_TYPE_MINMAX
Definition plannodes.h:275
@ RESULT_TYPE_JOIN
Definition plannodes.h:273
int restrict_nonsystem_relation_kind
Definition postgres.c:106
#define InvalidOid
unsigned int Oid
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition predtest.c:152
static int fb(int x)
List * extract_update_targetlist_colnos(List *tlist)
Definition preptlist.c:348
#define IS_SPECIAL_VARNO(varno)
Definition primnodes.h:247
#define INDEX_VAR
Definition primnodes.h:244
tree ctl root
Definition radixtree.h:1857
static const struct fns functions
Definition regcomp.c:358
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
void extract_actual_join_clauses(List *restrictinfo_list, Relids joinrelids, List **joinquals, List **otherquals)
List * get_actual_clauses(List *restrictinfo_list)
ScanDirection
Definition sdir.h:25
@ BackwardScanDirection
Definition sdir.h:26
@ ForwardScanDirection
Definition sdir.h:28
bool trivial_subqueryscan(SubqueryScan *plan)
Definition setrefs.c:1497
void check_stack_depth(void)
Definition stack_depth.c:95
AggSplit aggsplit
Definition plannodes.h:1196
List * chain
Definition plannodes.h:1223
List * groupingSets
Definition plannodes.h:1220
Bitmapset * aggParams
Definition plannodes.h:1215
Cardinality numGroups
Definition plannodes.h:1209
Plan plan
Definition plannodes.h:1190
int numCols
Definition plannodes.h:1199
uint64 transitionSpace
Definition plannodes.h:1212
AggStrategy aggstrategy
Definition plannodes.h:1193
Plan plan
Definition plannodes.h:491
List * bitmapplans
Definition plannodes.h:492
List * bitmapqualorig
Definition plannodes.h:693
List * indexqualorig
Definition plannodes.h:677
List * bitmapplans
Definition plannodes.h:507
Plan plan
Definition plannodes.h:505
int ctePlanId
Definition plannodes.h:802
int cteParam
Definition plannodes.h:804
Scan scan
Definition plannodes.h:800
Bitmapset * custom_relids
Definition plannodes.h:925
List * custom_exprs
Definition plannodes.h:919
const struct CustomScanMethods * methods
Definition plannodes.h:932
BeginDirectModify_function BeginDirectModify
Definition fdwapi.h:242
PlanForeignModify_function PlanForeignModify
Definition fdwapi.h:230
PlanDirectModify_function PlanDirectModify
Definition fdwapi.h:241
IterateDirectModify_function IterateDirectModify
Definition fdwapi.h:243
EndDirectModify_function EndDirectModify
Definition fdwapi.h:244
IsForeignPathAsyncCapable_function IsForeignPathAsyncCapable
Definition fdwapi.h:277
Oid checkAsUser
Definition plannodes.h:877
CmdType operation
Definition plannodes.h:873
List * fdw_exprs
Definition plannodes.h:881
bool fsSystemCol
Definition plannodes.h:893
Bitmapset * fs_relids
Definition plannodes.h:889
List * fdw_private
Definition plannodes.h:883
Bitmapset * fs_base_relids
Definition plannodes.h:891
Index resultRelation
Definition plannodes.h:875
List * fdw_recheck_quals
Definition plannodes.h:887
List * fdw_scan_tlist
Definition plannodes.h:885
List * functions
Definition plannodes.h:767
bool funcordinality
Definition plannodes.h:769
int num_workers
Definition plannodes.h:1339
bool invisible
Definition plannodes.h:1345
Bitmapset * initParam
Definition plannodes.h:1351
bool single_copy
Definition plannodes.h:1343
Plan plan
Definition plannodes.h:1337
int rescan_param
Definition plannodes.h:1341
int numCols
Definition plannodes.h:1164
Plan plan
Definition plannodes.h:1161
List * hashcollations
Definition plannodes.h:1048
List * hashclauses
Definition plannodes.h:1046
List * hashoperators
Definition plannodes.h:1047
Join join
Definition plannodes.h:1045
List * hashkeys
Definition plannodes.h:1054
AttrNumber skewColumn
Definition plannodes.h:1413
List * hashkeys
Definition plannodes.h:1409
Oid skewTable
Definition plannodes.h:1411
bool skewInherit
Definition plannodes.h:1415
Plan plan
Definition plannodes.h:1402
List * indexqual
Definition plannodes.h:639
List * recheckqual
Definition plannodes.h:641
List * indextlist
Definition plannodes.h:645
ScanDirection indexorderdir
Definition plannodes.h:647
List * indexorderby
Definition plannodes.h:643
List * indextlist
Definition pathnodes.h:1392
List * indexorderby
Definition plannodes.h:593
List * indexorderbyops
Definition plannodes.h:597
ScanDirection indexorderdir
Definition plannodes.h:599
Scan scan
Definition plannodes.h:585
List * indexqualorig
Definition plannodes.h:591
Oid indexid
Definition plannodes.h:587
List * indexqual
Definition plannodes.h:589
List * indexorderbyorig
Definition plannodes.h:595
List * joinqual
Definition plannodes.h:971
JoinType jointype
Definition plannodes.h:968
bool inner_unique
Definition plannodes.h:969
LimitOption limitOption
Definition plannodes.h:1488
Plan plan
Definition plannodes.h:1479
Node * limitCount
Definition plannodes.h:1485
int uniqNumCols
Definition plannodes.h:1491
Node * limitOffset
Definition plannodes.h:1482
Definition pg_list.h:54
int epqParam
Definition plannodes.h:1467
List * rowMarks
Definition plannodes.h:1465
Plan plan
Definition plannodes.h:1463
Plan plan
Definition plannodes.h:1063
Plan plan
Definition plannodes.h:1072
bool singlerow
Definition plannodes.h:1090
Cardinality est_calls
Definition plannodes.h:1108
Bitmapset * keyparamids
Definition plannodes.h:1105
bool binary_mode
Definition plannodes.h:1096
int numKeys
Definition plannodes.h:1075
Cardinality est_unique_keys
Definition plannodes.h:1111
List * param_exprs
Definition plannodes.h:1084
double est_hit_ratio
Definition plannodes.h:1114
uint32 est_entries
Definition plannodes.h:1102
int part_prune_index
Definition plannodes.h:447
Bitmapset * apprelids
Definition plannodes.h:421
List * mergeplans
Definition plannodes.h:423
List * mergeclauses
Definition plannodes.h:1022
bool skip_mark_restore
Definition plannodes.h:1019
List * updateColnosLists
Definition plannodes.h:344
Index nominalRelation
Definition plannodes.h:338
List * arbiterIndexes
Definition plannodes.h:364
List * onConflictCols
Definition plannodes.h:368
List * mergeJoinConditions
Definition plannodes.h:378
char * returningOldAlias
Definition plannodes.h:348
char * returningNewAlias
Definition plannodes.h:350
CmdType operation
Definition plannodes.h:334
List * resultRelations
Definition plannodes.h:342
Bitmapset * fdwDirectModifyPlans
Definition plannodes.h:356
List * onConflictSet
Definition plannodes.h:366
List * exclRelTlist
Definition plannodes.h:374
List * mergeActionLists
Definition plannodes.h:376
bool canSetTag
Definition plannodes.h:336
List * fdwPrivLists
Definition plannodes.h:354
List * returningLists
Definition plannodes.h:352
List * withCheckOptionLists
Definition plannodes.h:346
Index rootRelation
Definition plannodes.h:340
Node * onConflictWhere
Definition plannodes.h:370
List * rowMarks
Definition plannodes.h:358
OnConflictAction onConflictAction
Definition plannodes.h:362
Index exclRelRTI
Definition plannodes.h:372
List * nestParams
Definition plannodes.h:989
Join join
Definition plannodes.h:987
Definition nodes.h:135
OnConflictAction action
Definition primnodes.h:2373
List * onConflictSet
Definition primnodes.h:2382
List * exclRelTlist
Definition primnodes.h:2385
Node * onConflictWhere
Definition primnodes.h:2383
Oid opno
Definition primnodes.h:850
List * args
Definition primnodes.h:868
ParseLoc location
Definition primnodes.h:871
List * exprs
Definition pathnodes.h:1858
NodeTag pathtype
Definition pathnodes.h:1951
Cardinality rows
Definition pathnodes.h:1985
Cost startup_cost
Definition pathnodes.h:1987
int disabled_nodes
Definition pathnodes.h:1986
Cost total_cost
Definition pathnodes.h:1988
bool parallel_aware
Definition pathnodes.h:1978
bool parallel_safe
Definition pathnodes.h:1980
struct Plan * lefttree
Definition plannodes.h:233
bool async_capable
Definition plannodes.h:221
Cost total_cost
Definition plannodes.h:199
struct Plan * righttree
Definition plannodes.h:234
Cost startup_cost
Definition plannodes.h:197
List * qual
Definition plannodes.h:231
int plan_width
Definition plannodes.h:207
bool parallel_safe
Definition plannodes.h:215
Cardinality plan_rows
Definition plannodes.h:205
int disabled_nodes
Definition plannodes.h:195
List * targetlist
Definition plannodes.h:229
List * initPlan
Definition plannodes.h:236
Query * parse
Definition pathnodes.h:303
Cardinality numGroups
Definition plannodes.h:478
List * baserestrictinfo
Definition pathnodes.h:1124
List * subplan_params
Definition pathnodes.h:1083
bool useridiscurrent
Definition pathnodes.h:1097
Relids relids
Definition pathnodes.h:1003
struct PathTarget * reltarget
Definition pathnodes.h:1027
Index relid
Definition pathnodes.h:1051
RelOptKind reloptkind
Definition pathnodes.h:997
PlannerInfo * subroot
Definition pathnodes.h:1082
AttrNumber min_attr
Definition pathnodes.h:1057
RTEKind rtekind
Definition pathnodes.h:1055
Index security_level
Definition pathnodes.h:2892
Expr * clause
Definition pathnodes.h:2870
Node * resconstantqual
Definition plannodes.h:299
ResultType result_type
Definition plannodes.h:298
Bitmapset * relids
Definition plannodes.h:300
Plan plan
Definition plannodes.h:297
struct TableSampleClause * tablesample
Definition plannodes.h:543
Index scanrelid
Definition plannodes.h:523
Scan scan
Definition plannodes.h:532
SetOpStrategy strategy
Definition plannodes.h:1433
SetOpCmd cmd
Definition plannodes.h:1430
int numCols
Definition plannodes.h:1436
Plan plan
Definition plannodes.h:1427
Cardinality numGroups
Definition plannodes.h:1449
int numCols
Definition plannodes.h:1127
Plan plan
Definition plannodes.h:1124
SubqueryScanStatus scanstatus
Definition plannodes.h:756
Plan * subplan
Definition plannodes.h:755
TableFunc * tablefunc
Definition plannodes.h:791
List * tidrangequals
Definition plannodes.h:722
Scan scan
Definition plannodes.h:706
List * tidquals
Definition plannodes.h:708
Plan plan
Definition plannodes.h:1309
int numCols
Definition plannodes.h:1312
List * values_lists
Definition plannodes.h:780
AttrNumber varattno
Definition primnodes.h:274
int varno
Definition primnodes.h:269
Index varlevelsup
Definition primnodes.h:294
char * winname
Definition plannodes.h:1235
int partNumCols
Definition plannodes.h:1241
Oid endInRangeFunc
Definition plannodes.h:1285
Node * endOffset
Definition plannodes.h:1271
bool topWindow
Definition plannodes.h:1300
List * runConditionOrig
Definition plannodes.h:1277
Oid inRangeColl
Definition plannodes.h:1288
Node * startOffset
Definition plannodes.h:1268
List * runCondition
Definition plannodes.h:1274
Oid startInRangeFunc
Definition plannodes.h:1282
bool inRangeAsc
Definition plannodes.h:1291
Index winref
Definition plannodes.h:1238
bool inRangeNullsFirst
Definition plannodes.h:1294
int ordNumCols
Definition plannodes.h:1253
int frameOptions
Definition plannodes.h:1265
Node * startOffset
List * partitionClause
Node * endOffset
List * orderClause
Definition type.h:96
void SS_attach_initplans(PlannerInfo *root, Plan *plan)
Definition subselect.c:2389
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition subselect.c:2348
void SS_make_initplan_from_plan(PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
Definition subselect.c:3165
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
#define RESTRICT_RELKIND_FOREIGN_TABLE
Definition tcopprot.h:45
static ItemArray items
Oid * extract_grouping_ops(List *groupClause)
Definition tlist.c:472
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition tlist.c:88
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition tlist.c:227
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition tlist.c:327
void apply_pathtarget_labeling_to_tlist(List *tlist, PathTarget *target)
Definition tlist.c:783
AttrNumber * extract_grouping_cols(List *groupClause, List *tlist)
Definition tlist.c:523
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition tlist.c:376
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition tlist.c:354
Oid * extract_grouping_collations(List *groupClause, List *tlist)
Definition tlist.c:498
#define FirstNormalObjectId
Definition transam.h:197
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition var.c:296
bool contain_vars_returning_old_or_new(Node *node)
Definition var.c:511