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