PostgreSQL Source Code git master
Loading...
Searching...
No Matches
planner.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * planner.c
4 * The query optimizer external interface.
5 *
6 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/optimizer/plan/planner.c
12 *
13 *-------------------------------------------------------------------------
14 */
15
16#include "postgres.h"
17
18#include <limits.h>
19#include <math.h>
20
21#include "access/genam.h"
22#include "access/parallel.h"
23#include "access/sysattr.h"
24#include "access/table.h"
26#include "catalog/pg_inherits.h"
27#include "catalog/pg_proc.h"
28#include "catalog/pg_type.h"
29#include "executor/executor.h"
30#include "foreign/fdwapi.h"
31#include "jit/jit.h"
32#include "lib/bipartite_match.h"
33#include "lib/knapsack.h"
34#include "miscadmin.h"
35#include "nodes/makefuncs.h"
36#include "nodes/nodeFuncs.h"
37#ifdef OPTIMIZER_DEBUG
38#include "nodes/print.h"
39#endif
40#include "nodes/supportnodes.h"
42#include "optimizer/clauses.h"
43#include "optimizer/cost.h"
44#include "optimizer/optimizer.h"
46#include "optimizer/pathnode.h"
47#include "optimizer/paths.h"
48#include "optimizer/plancat.h"
49#include "optimizer/planmain.h"
50#include "optimizer/planner.h"
51#include "optimizer/prep.h"
52#include "optimizer/subselect.h"
53#include "optimizer/tlist.h"
54#include "parser/analyze.h"
55#include "parser/parse_agg.h"
56#include "parser/parse_clause.h"
58#include "parser/parsetree.h"
61#include "utils/acl.h"
63#include "utils/lsyscache.h"
64#include "utils/rel.h"
65#include "utils/selfuncs.h"
66
67/* GUC parameters */
72
73/* Hook for plugins to get control in planner() */
75
76/* Hook for plugins to get control after PlannerGlobal is initialized */
78
79/* Hook for plugins to get control before PlannerGlobal is discarded */
81
82/* Hook for plugins to get control when grouping_planner() plans upper rels */
84
85
86/* Expression kind codes for preprocess_expression */
87#define EXPRKIND_QUAL 0
88#define EXPRKIND_TARGET 1
89#define EXPRKIND_RTFUNC 2
90#define EXPRKIND_RTFUNC_LATERAL 3
91#define EXPRKIND_VALUES 4
92#define EXPRKIND_VALUES_LATERAL 5
93#define EXPRKIND_LIMIT 6
94#define EXPRKIND_APPINFO 7
95#define EXPRKIND_PHV 8
96#define EXPRKIND_TABLESAMPLE 9
97#define EXPRKIND_ARBITER_ELEM 10
98#define EXPRKIND_TABLEFUNC 11
99#define EXPRKIND_TABLEFUNC_LATERAL 12
100#define EXPRKIND_GROUPEXPR 13
101
102/*
103 * Data specific to grouping sets
104 */
116
117/*
118 * Temporary structure for use during WindowClause reordering in order to be
119 * able to sort WindowClauses on partitioning/ordering prefix.
120 */
121typedef struct
122{
124 List *uniqueOrder; /* A List of unique ordering/partitioning
125 * clauses per Window */
127
128/* Passthrough data for standard_qp_callback */
129typedef struct
130{
131 List *activeWindows; /* active windows, if any */
132 grouping_sets_data *gset_data; /* grouping sets data, if any */
133 SetOperationStmt *setop; /* parent set operation or NULL if not a
134 * subquery belonging to a set operation */
136
137/*
138 * Context for the find_having_collation_conflicts walker.
139 *
140 * ancestor_collids is a stack of inputcollids contributed by collation-aware
141 * ancestors of the current node. Entries are pushed before recursing into a
142 * node's children and popped afterwards, so the stack reflects exactly the
143 * inputcollids on the current root-to-node path.
144 */
150
151/* Local functions */
152static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
153static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
155 Index group_rtindex);
156static bool having_collation_conflict_walker(Node *node,
158static void grouping_planner(PlannerInfo *root, double tuple_fraction,
161static List *remap_to_groupclause_idx(List *groupClause, List *gsets,
162 int *tleref_to_colnum_map);
164static double preprocess_limit(PlannerInfo *root,
165 double tuple_fraction,
166 int64 *offset_est, int64 *count_est);
168static List *extract_rollup_sets(List *groupingSets);
169static List *reorder_grouping_sets(List *groupingSets, List *sortclause);
170static void standard_qp_callback(PlannerInfo *root, void *extra);
172 double path_rows,
177 PathTarget *target,
178 bool target_parallel_safe,
183 RelOptInfo *grouped_rel);
185 PathTarget *target, bool target_parallel_safe,
186 Node *havingQual);
189 RelOptInfo *grouped_rel,
192 GroupPathExtraData *extra,
195 RelOptInfo *grouped_rel,
196 Path *path,
197 bool is_sorted,
198 bool can_hash,
201 double dNumGroups);
208 List *activeWindows);
211 Path *path,
215 List *activeWindows);
218 PathTarget *target);
222 PathTarget *target);
231 PathTarget *target,
232 bool target_parallel_safe,
233 double limit_tuples);
238 Node *havingQual);
243static void name_active_windows(List *activeWindows);
246 List *activeWindows);
248 List *tlist);
251 bool *have_postponed_srfs);
253 List *targets, List *targets_contain_srfs);
255 RelOptInfo *grouped_rel,
259 GroupPathExtraData *extra);
261 RelOptInfo *grouped_rel,
264 GroupPathExtraData *extra,
265 bool force_rel_creation);
267 RelOptInfo *rel,
268 Path *path,
270 List *pathkeys,
271 double limit_tuples);
273static bool can_partial_agg(PlannerInfo *root);
275 RelOptInfo *rel,
279 bool tlist_same_exprs);
282 RelOptInfo *grouped_rel,
287 GroupPathExtraData *extra);
289 List *targetList,
290 List *groupClause);
291static int common_prefix_cmp(const void *a, const void *b);
293 List *targetlist);
295 List *sortPathkeys, List *groupClause,
296 SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
298 List *sortPathkeys, List *groupClause,
299 SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
300
301
302/*****************************************************************************
303 *
304 * Query optimizer entry point
305 *
306 * Inputs:
307 * parse: an analyzed-and-rewritten query tree for an optimizable statement
308 * query_string: source text for the query tree (used for error reports)
309 * cursorOptions: bitmask of CURSOR_OPT_XXX flags, see parsenodes.h
310 * boundParams: passed-in parameter values, or NULL if none
311 * es: ExplainState if being called from EXPLAIN, else NULL
312 *
313 * The result is a PlannedStmt tree.
314 *
315 * PARAM_EXTERN Param nodes within the parse tree can be replaced by Consts
316 * using values from boundParams, if those values are marked PARAM_FLAG_CONST.
317 * Parameter values not so marked are still relied on for estimation purposes.
318 *
319 * The ExplainState pointer is not currently used by the core planner, but it
320 * is passed through to some planner hooks so that they can report information
321 * back to EXPLAIN extension hooks.
322 *
323 * To support loadable plugins that monitor or modify planner behavior,
324 * we provide a hook variable that lets a plugin get control before and
325 * after the standard planning process. The plugin would normally call
326 * standard_planner().
327 *
328 * Note to plugin authors: standard_planner() scribbles on its Query input,
329 * so you'd better copy that data structure if you want to plan more than once.
330 *
331 *****************************************************************************/
333planner(Query *parse, const char *query_string, int cursorOptions,
334 ParamListInfo boundParams, ExplainState *es)
335{
337
338 if (planner_hook)
339 result = (*planner_hook) (parse, query_string, cursorOptions,
340 boundParams, es);
341 else
342 result = standard_planner(parse, query_string, cursorOptions,
343 boundParams, es);
344
345 pgstat_report_plan_id(result->planId, false);
346
347 return result;
348}
349
351standard_planner(Query *parse, const char *query_string, int cursorOptions,
352 ParamListInfo boundParams, ExplainState *es)
353{
355 PlannerGlobal *glob;
356 double tuple_fraction;
360 Plan *top_plan;
361 ListCell *lp,
362 *lr,
363 *lc;
364
365 /*
366 * Set up global state for this planner invocation. This data is needed
367 * across all levels of sub-Query that might exist in the given command,
368 * so we keep it in a separate struct that's linked to by each per-Query
369 * PlannerInfo.
370 */
371 glob = makeNode(PlannerGlobal);
372
373 glob->boundParams = boundParams;
374 glob->subplans = NIL;
375 glob->subpaths = NIL;
376 glob->subroots = NIL;
377 glob->rewindPlanIDs = NULL;
378 glob->finalrtable = NIL;
379 glob->allRelids = NULL;
380 glob->prunableRelids = NULL;
381 glob->finalrteperminfos = NIL;
382 glob->finalrowmarks = NIL;
383 glob->resultRelations = NIL;
384 glob->appendRelations = NIL;
385 glob->partPruneInfos = NIL;
386 glob->relationOids = NIL;
387 glob->invalItems = NIL;
388 glob->paramExecTypes = NIL;
389 glob->lastPHId = 0;
390 glob->lastRowMarkId = 0;
391 glob->lastPlanNodeId = 0;
392 glob->transientPlan = false;
393 glob->dependsOnRole = false;
394 glob->partition_directory = NULL;
395 glob->rel_notnullatts_hash = NULL;
396
397 /*
398 * Assess whether it's feasible to use parallel mode for this query. We
399 * can't do this in a standalone backend, or if the command will try to
400 * modify any data, or if this is a cursor operation, or if GUCs are set
401 * to values that don't permit parallelism, or if parallel-unsafe
402 * functions are present in the query tree.
403 *
404 * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
405 * MATERIALIZED VIEW to use parallel plans, but this is safe only because
406 * the command is writing into a completely new table which workers won't
407 * be able to see. If the workers could see the table, the fact that
408 * group locking would cause them to ignore the leader's heavyweight GIN
409 * page locks would make this unsafe. We'll have to fix that somehow if
410 * we want to allow parallel inserts in general; updates and deletes have
411 * additional problems especially around combo CIDs.)
412 *
413 * For now, we don't try to use parallel mode if we're running inside a
414 * parallel worker. We might eventually be able to relax this
415 * restriction, but for now it seems best not to have parallel workers
416 * trying to create their own parallel workers.
417 */
418 if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
420 parse->commandType == CMD_SELECT &&
421 !parse->hasModifyingCTE &&
424 {
425 /* all the cheap tests pass, so scan the query tree */
428 }
429 else
430 {
431 /* skip the query tree scan, just assume it's unsafe */
433 glob->parallelModeOK = false;
434 }
435
436 /*
437 * glob->parallelModeNeeded is normally set to false here and changed to
438 * true during plan creation if a Gather or Gather Merge plan is actually
439 * created (cf. create_gather_plan, create_gather_merge_plan).
440 *
441 * However, if debug_parallel_query = on or debug_parallel_query =
442 * regress, then we impose parallel mode whenever it's safe to do so, even
443 * if the final plan doesn't use parallelism. It's not safe to do so if
444 * the query contains anything parallel-unsafe; parallelModeOK will be
445 * false in that case. Note that parallelModeOK can't change after this
446 * point. Otherwise, everything in the query is either parallel-safe or
447 * parallel-restricted, and in either case it should be OK to impose
448 * parallel-mode restrictions. If that ends up breaking something, then
449 * either some function the user included in the query is incorrectly
450 * labeled as parallel-safe or parallel-restricted when in reality it's
451 * parallel-unsafe, or else the query planner itself has a bug.
452 */
453 glob->parallelModeNeeded = glob->parallelModeOK &&
455
456 /* Determine what fraction of the plan is likely to be scanned */
457 if (cursorOptions & CURSOR_OPT_FAST_PLAN)
458 {
459 /*
460 * We have no real idea how many tuples the user will ultimately FETCH
461 * from a cursor, but it is often the case that he doesn't want 'em
462 * all, or would prefer a fast-start plan anyway so that he can
463 * process some of the tuples sooner. Use a GUC parameter to decide
464 * what fraction to optimize for.
465 */
466 tuple_fraction = cursor_tuple_fraction;
467
468 /*
469 * We document cursor_tuple_fraction as simply being a fraction, which
470 * means the edge cases 0 and 1 have to be treated specially here. We
471 * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
472 */
473 if (tuple_fraction >= 1.0)
474 tuple_fraction = 0.0;
475 else if (tuple_fraction <= 0.0)
476 tuple_fraction = 1e-10;
477 }
478 else
479 {
480 /* Default assumption is we need all the tuples */
481 tuple_fraction = 0.0;
482 }
483
484 /*
485 * Compute the initial path generation strategy mask.
486 *
487 * Some strategies, such as PGS_FOREIGNJOIN, have no corresponding enable_*
488 * GUC, and so the corresponding bits are always set in the default
489 * strategy mask.
490 *
491 * It may seem surprising that enable_indexscan sets both PGS_INDEXSCAN
492 * and PGS_INDEXONLYSCAN. However, the historical behavior of this GUC
493 * corresponds to this exactly: enable_indexscan=off disables both
494 * index-scan and index-only scan paths, whereas enable_indexonlyscan=off
495 * converts the index-only scan paths that we would have considered into
496 * index scan paths.
497 */
500 if (enable_tidscan)
502 if (enable_seqscan)
511 {
513 if (enable_material)
515 }
516 if (enable_nestloop)
517 {
519 if (enable_material)
521 if (enable_memoize)
523 }
524 if (enable_hashjoin)
530
531 /* Allow plugins to take control after we've initialized "glob" */
533 (*planner_setup_hook) (glob, parse, query_string, cursorOptions,
534 &tuple_fraction, es);
535
536 /* primary planning entry point (may recurse for subqueries) */
537 root = subquery_planner(glob, parse, NULL, NULL, NULL, false,
538 tuple_fraction, NULL);
539
540 /* Select best Path and turn it into a Plan */
543
545
546 /*
547 * If creating a plan for a scrollable cursor, make sure it can run
548 * backwards on demand. Add a Material node at the top at need.
549 */
550 if (cursorOptions & CURSOR_OPT_SCROLL)
551 {
554 }
555
556 /*
557 * Optionally add a Gather node for testing purposes, provided this is
558 * actually a safe thing to do.
559 *
560 * We can add Gather even when top_plan has parallel-safe initPlans, but
561 * then we have to move the initPlans to the Gather node because of
562 * SS_finalize_plan's limitations. That would cause cosmetic breakage of
563 * regression tests when debug_parallel_query = regress, because initPlans
564 * that would normally appear on the top_plan move to the Gather, causing
565 * them to disappear from EXPLAIN output. That doesn't seem worth kluging
566 * EXPLAIN to hide, so skip it when debug_parallel_query = regress.
567 */
569 top_plan->parallel_safe &&
570 (top_plan->initPlan == NIL ||
572 {
575 bool unsafe_initplans;
576
577 gather->plan.targetlist = top_plan->targetlist;
578 gather->plan.qual = NIL;
579 gather->plan.lefttree = top_plan;
580 gather->plan.righttree = NULL;
581 gather->num_workers = 1;
582 gather->single_copy = true;
584
585 /* Transfer any initPlans to the new top node */
586 gather->plan.initPlan = top_plan->initPlan;
587 top_plan->initPlan = NIL;
588
589 /*
590 * Since this Gather has no parallel-aware descendants to signal to,
591 * we don't need a rescan Param.
592 */
593 gather->rescan_param = -1;
594
595 /*
596 * Ideally we'd use cost_gather here, but setting up dummy path data
597 * to satisfy it doesn't seem much cleaner than knowing what it does.
598 */
599 gather->plan.startup_cost = top_plan->startup_cost +
601 gather->plan.total_cost = top_plan->total_cost +
603 gather->plan.plan_rows = top_plan->plan_rows;
604 gather->plan.plan_width = top_plan->plan_width;
605 gather->plan.parallel_aware = false;
606 gather->plan.parallel_safe = false;
607
608 /*
609 * Delete the initplans' cost from top_plan. We needn't add it to the
610 * Gather node, since the above coding already included it there.
611 */
612 SS_compute_initplan_cost(gather->plan.initPlan,
614 top_plan->startup_cost -= initplan_cost;
615 top_plan->total_cost -= initplan_cost;
616
617 /* use parallel mode for parallel plans. */
618 root->glob->parallelModeNeeded = true;
619
620 top_plan = &gather->plan;
621 }
622
623 /*
624 * If any Params were generated, run through the plan tree and compute
625 * each plan node's extParam/allParam sets. Ideally we'd merge this into
626 * set_plan_references' tree traversal, but for now it has to be separate
627 * because we need to visit subplans before not after main plan.
628 */
629 if (glob->paramExecTypes != NIL)
630 {
631 Assert(list_length(glob->subplans) == list_length(glob->subroots));
632 forboth(lp, glob->subplans, lr, glob->subroots)
633 {
634 Plan *subplan = (Plan *) lfirst(lp);
636
637 SS_finalize_plan(subroot, subplan);
638 }
640 }
641
642 /* final cleanup of the plan */
643 Assert(glob->finalrtable == NIL);
644 Assert(glob->finalrteperminfos == NIL);
645 Assert(glob->finalrowmarks == NIL);
646 Assert(glob->resultRelations == NIL);
647 Assert(glob->appendRelations == NIL);
649 /* ... and the subplans (both regular subplans and initplans) */
650 Assert(list_length(glob->subplans) == list_length(glob->subroots));
651 forboth(lp, glob->subplans, lr, glob->subroots)
652 {
653 Plan *subplan = (Plan *) lfirst(lp);
655
656 lfirst(lp) = set_plan_references(subroot, subplan);
657 }
658
659 /* build the PlannedStmt result */
661
662 result->commandType = parse->commandType;
663 result->queryId = parse->queryId;
664 result->planOrigin = PLAN_STMT_STANDARD;
665 result->hasReturning = (parse->returningList != NIL);
666 result->hasModifyingCTE = parse->hasModifyingCTE;
667 result->canSetTag = parse->canSetTag;
668 result->transientPlan = glob->transientPlan;
669 result->dependsOnRole = glob->dependsOnRole;
670 result->parallelModeNeeded = glob->parallelModeNeeded;
671 result->planTree = top_plan;
672 result->partPruneInfos = glob->partPruneInfos;
673 result->rtable = glob->finalrtable;
674 result->unprunableRelids = bms_difference(glob->allRelids,
675 glob->prunableRelids);
676 result->permInfos = glob->finalrteperminfos;
677 result->subrtinfos = glob->subrtinfos;
678 result->appendRelations = glob->appendRelations;
679 result->subplans = glob->subplans;
680 result->rewindPlanIDs = glob->rewindPlanIDs;
681 result->rowMarks = glob->finalrowmarks;
682
683 /*
684 * Compute resultRelationRelids and rowMarkRelids from resultRelations and
685 * rowMarks. These can be used for cheap membership checks.
686 */
687 foreach(lc, glob->resultRelations)
688 result->resultRelationRelids = bms_add_member(result->resultRelationRelids,
689 lfirst_int(lc));
690 foreach(lc, glob->finalrowmarks)
691 result->rowMarkRelids = bms_add_member(result->rowMarkRelids,
692 ((PlanRowMark *) lfirst(lc))->rti);
693
694 result->relationOids = glob->relationOids;
695 result->invalItems = glob->invalItems;
696 result->paramExecTypes = glob->paramExecTypes;
697 /* utilityStmt should be null, but we might as well copy it */
698 result->utilityStmt = parse->utilityStmt;
699 result->elidedNodes = glob->elidedNodes;
700 result->stmt_location = parse->stmt_location;
701 result->stmt_len = parse->stmt_len;
702
703 result->jitFlags = PGJIT_NONE;
704 if (jit_enabled && jit_above_cost >= 0 &&
705 top_plan->total_cost > jit_above_cost)
706 {
707 result->jitFlags |= PGJIT_PERFORM;
708
709 /*
710 * Decide how much effort should be put into generating better code.
711 */
712 if (jit_optimize_above_cost >= 0 &&
713 top_plan->total_cost > jit_optimize_above_cost)
714 result->jitFlags |= PGJIT_OPT3;
715 if (jit_inline_above_cost >= 0 &&
716 top_plan->total_cost > jit_inline_above_cost)
717 result->jitFlags |= PGJIT_INLINE;
718
719 /*
720 * Decide which operations should be JITed.
721 */
722 if (jit_expressions)
723 result->jitFlags |= PGJIT_EXPR;
725 result->jitFlags |= PGJIT_DEFORM;
726 }
727
728 /* Allow plugins to take control before we discard "glob" */
730 (*planner_shutdown_hook) (glob, parse, query_string, result);
731
732 if (glob->partition_directory != NULL)
733 DestroyPartitionDirectory(glob->partition_directory);
734
735 return result;
736}
737
738
739/*--------------------
740 * subquery_planner
741 * Invokes the planner on a subquery. We recurse to here for each
742 * sub-SELECT found in the query tree.
743 *
744 * glob is the global state for the current planner run.
745 * parse is the querytree produced by the parser & rewriter.
746 * plan_name is the name to assign to this subplan (NULL at the top level).
747 * parent_root is the immediate parent Query's info (NULL at the top level).
748 * alternative_root is a previously created PlannerInfo for which this query
749 * level is an alternative implementation, or else NULL.
750 * hasRecursion is true if this is a recursive WITH query.
751 * tuple_fraction is the fraction of tuples we expect will be retrieved.
752 * tuple_fraction is interpreted as explained for grouping_planner, below.
753 * setops is used for set operation subqueries to provide the subquery with
754 * the context in which it's being used so that Paths correctly sorted for the
755 * set operation can be generated. NULL when not planning a set operation
756 * child, or when a child of a set op that isn't interested in sorted input.
757 *
758 * Basically, this routine does the stuff that should only be done once
759 * per Query object. It then calls grouping_planner. At one time,
760 * grouping_planner could be invoked recursively on the same Query object;
761 * that's not currently true, but we keep the separation between the two
762 * routines anyway, in case we need it again someday.
763 *
764 * subquery_planner will be called recursively to handle sub-Query nodes
765 * found within the query's expressions and rangetable.
766 *
767 * Returns the PlannerInfo struct ("root") that contains all data generated
768 * while planning the subquery. In particular, the Path(s) attached to
769 * the (UPPERREL_FINAL, NULL) upperrel represent our conclusions about the
770 * cheapest way(s) to implement the query. The top level will select the
771 * best Path and pass it through createplan.c to produce a finished Plan.
772 *--------------------
773 */
775subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name,
777 bool hasRecursion, double tuple_fraction,
779{
784 int havingIdx;
785 bool hasOuterJoins;
786 bool hasResultRTEs;
788 ListCell *l;
789
790 /* Create a PlannerInfo data structure for this subquery */
792 root->parse = parse;
793 root->glob = glob;
794 root->query_level = parent_root ? parent_root->query_level + 1 : 1;
795 root->plan_name = plan_name;
796 if (alternative_root != NULL)
797 root->alternative_plan_name = alternative_root->plan_name;
798 else
799 root->alternative_plan_name = plan_name;
800 root->parent_root = parent_root;
801 root->plan_params = NIL;
802 root->outer_params = NULL;
803 root->planner_cxt = CurrentMemoryContext;
804 root->init_plans = NIL;
805 root->cte_plan_ids = NIL;
806 root->multiexpr_params = NIL;
807 root->join_domains = NIL;
808 root->eq_classes = NIL;
809 root->ec_merging_done = false;
810 root->last_rinfo_serial = 0;
811 root->all_result_relids =
812 parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL;
813 root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */
814 root->append_rel_list = NIL;
815 root->row_identity_vars = NIL;
816 root->rowMarks = NIL;
817 memset(root->upper_rels, 0, sizeof(root->upper_rels));
818 memset(root->upper_targets, 0, sizeof(root->upper_targets));
819 root->processed_groupClause = NIL;
820 root->processed_distinctClause = NIL;
821 root->processed_tlist = NIL;
822 root->update_colnos = NIL;
823 root->grouping_map = NULL;
824 root->minmax_aggs = NIL;
825 root->qual_security_level = 0;
826 root->hasPseudoConstantQuals = false;
827 root->hasAlternativeSubPlans = false;
828 root->placeholdersFrozen = false;
829 root->hasRecursion = hasRecursion;
830 root->assumeReplanning = false;
831 if (hasRecursion)
832 root->wt_param_id = assign_special_exec_param(root);
833 else
834 root->wt_param_id = -1;
835 root->non_recursive_path = NULL;
836
837 /*
838 * Create the top-level join domain. This won't have valid contents until
839 * deconstruct_jointree fills it in, but the node needs to exist before
840 * that so we can build EquivalenceClasses referencing it.
841 */
842 root->join_domains = list_make1(makeNode(JoinDomain));
843
844 /*
845 * If there is a WITH list, process each WITH query and either convert it
846 * to RTE_SUBQUERY RTE(s) or build an initplan SubPlan structure for it.
847 */
848 if (parse->cteList)
850
851 /*
852 * If it's a MERGE command, transform the joinlist as appropriate.
853 */
855
856 /*
857 * Scan the rangetable for relation RTEs and retrieve the necessary
858 * catalog information for each relation. Using this information, clear
859 * the inh flag for any relation that has no children, collect not-null
860 * attribute numbers for any relation that has column not-null
861 * constraints, and expand virtual generated columns for any relation that
862 * contains them. Note that this step does not descend into sublinks and
863 * subqueries; if we pull up any sublinks or subqueries below, their
864 * relation RTEs are processed just before pulling them up.
865 */
867
868 /*
869 * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
870 * that we don't need so many special cases to deal with that situation.
871 */
873
874 /*
875 * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
876 * to transform them into joins. Note that this step does not descend
877 * into subqueries; if we pull up any subqueries below, their SubLinks are
878 * processed just before pulling them up.
879 */
880 if (parse->hasSubLinks)
882
883 /*
884 * Scan the rangetable for function RTEs, do const-simplification on them,
885 * and then inline them if possible (producing subqueries that might get
886 * pulled up next). Recursion issues here are handled in the same way as
887 * for SubLinks.
888 */
890
891 /*
892 * Check to see if any subqueries in the jointree can be merged into this
893 * query.
894 */
896
897 /*
898 * If this is a simple UNION ALL query, flatten it into an appendrel. We
899 * do this now because it requires applying pull_up_subqueries to the leaf
900 * queries of the UNION ALL, which weren't touched above because they
901 * weren't referenced by the jointree (they will be after we do this).
902 */
903 if (parse->setOperations)
905
906 /*
907 * Survey the rangetable to see what kinds of entries are present. We can
908 * skip some later processing if relevant SQL features are not used; for
909 * example if there are no JOIN RTEs we can avoid the expense of doing
910 * flatten_join_alias_vars(). This must be done after we have finished
911 * adding rangetable entries, of course. (Note: actually, processing of
912 * inherited or partitioned rels can cause RTEs for their child tables to
913 * get added later; but those must all be RTE_RELATION entries, so they
914 * don't invalidate the conclusions drawn here.)
915 */
916 root->hasJoinRTEs = false;
917 root->hasLateralRTEs = false;
918 root->group_rtindex = 0;
919 hasOuterJoins = false;
920 hasResultRTEs = false;
921 foreach(l, parse->rtable)
922 {
924
925 switch (rte->rtekind)
926 {
927 case RTE_JOIN:
928 root->hasJoinRTEs = true;
929 if (IS_OUTER_JOIN(rte->jointype))
930 hasOuterJoins = true;
931 break;
932 case RTE_RESULT:
933 hasResultRTEs = true;
934 break;
935 case RTE_GROUP:
936 Assert(parse->hasGroupRTE);
937 root->group_rtindex = list_cell_number(parse->rtable, l) + 1;
938 break;
939 default:
940 /* No work here for other RTE types */
941 break;
942 }
943
944 if (rte->lateral)
945 root->hasLateralRTEs = true;
946
947 /*
948 * We can also determine the maximum security level required for any
949 * securityQuals now. Addition of inheritance-child RTEs won't affect
950 * this, because child tables don't have their own securityQuals; see
951 * expand_single_inheritance_child().
952 */
953 if (rte->securityQuals)
954 root->qual_security_level = Max(root->qual_security_level,
955 list_length(rte->securityQuals));
956 }
957
958 /*
959 * If we have now verified that the query target relation is
960 * non-inheriting, mark it as a leaf target.
961 */
962 if (parse->resultRelation)
963 {
964 RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable);
965
966 if (!rte->inh)
967 root->leaf_result_relids =
968 bms_make_singleton(parse->resultRelation);
969 }
970
971 /*
972 * This would be a convenient time to check access permissions for all
973 * relations mentioned in the query, since it would be better to fail now,
974 * before doing any detailed planning. However, for historical reasons,
975 * we leave this to be done at executor startup.
976 *
977 * Note, however, that we do need to check access permissions for any view
978 * relations mentioned in the query, in order to prevent information being
979 * leaked by selectivity estimation functions, which only check view owner
980 * permissions on underlying tables (see all_rows_selectable() and its
981 * callers). This is a little ugly, because it means that access
982 * permissions for views will be checked twice, which is another reason
983 * why it would be better to do all the ACL checks here.
984 */
985 foreach(l, parse->rtable)
986 {
988
989 if (rte->perminfoindex != 0 &&
990 rte->relkind == RELKIND_VIEW)
991 {
993 bool result;
994
995 perminfo = getRTEPermissionInfo(parse->rteperminfos, rte);
997 if (!result)
999 get_rel_name(perminfo->relid));
1000 }
1001 }
1002
1003 /*
1004 * Preprocess RowMark information. We need to do this after subquery
1005 * pullup, so that all base relations are present.
1006 */
1008
1009 /*
1010 * Set hasHavingQual to remember if HAVING clause is present. Needed
1011 * because preprocess_expression will reduce a constant-true condition to
1012 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
1013 */
1014 root->hasHavingQual = (parse->havingQual != NULL);
1015
1016 /*
1017 * Do expression preprocessing on targetlist and quals, as well as other
1018 * random expressions in the querytree. Note that we do not need to
1019 * handle sort/group expressions explicitly, because they are actually
1020 * part of the targetlist.
1021 */
1022 parse->targetList = (List *)
1023 preprocess_expression(root, (Node *) parse->targetList,
1025
1027 foreach(l, parse->withCheckOptions)
1028 {
1030
1031 wco->qual = preprocess_expression(root, wco->qual,
1033 if (wco->qual != NULL)
1035 }
1036 parse->withCheckOptions = newWithCheckOptions;
1037
1038 parse->returningList = (List *)
1039 preprocess_expression(root, (Node *) parse->returningList,
1041
1042 preprocess_qual_conditions(root, (Node *) parse->jointree);
1043
1044 parse->havingQual = preprocess_expression(root, parse->havingQual,
1046
1047 foreach(l, parse->windowClause)
1048 {
1050
1051 /* partitionClause/orderClause are sort/group expressions */
1056 }
1057
1058 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
1060 parse->limitCount = preprocess_expression(root, parse->limitCount,
1062
1063 if (parse->onConflict)
1064 {
1065 parse->onConflict->arbiterElems = (List *)
1067 (Node *) parse->onConflict->arbiterElems,
1069 parse->onConflict->arbiterWhere =
1071 parse->onConflict->arbiterWhere,
1073 parse->onConflict->onConflictSet = (List *)
1075 (Node *) parse->onConflict->onConflictSet,
1077 parse->onConflict->onConflictWhere =
1079 parse->onConflict->onConflictWhere,
1081 /* exclRelTlist contains only Vars, so no preprocessing needed */
1082 }
1083
1084 foreach(l, parse->mergeActionList)
1085 {
1086 MergeAction *action = (MergeAction *) lfirst(l);
1087
1088 action->targetList = (List *)
1090 (Node *) action->targetList,
1092 action->qual =
1094 (Node *) action->qual,
1096 }
1097
1098 parse->mergeJoinCondition =
1099 preprocess_expression(root, parse->mergeJoinCondition, EXPRKIND_QUAL);
1100
1101 root->append_rel_list = (List *)
1102 preprocess_expression(root, (Node *) root->append_rel_list,
1104
1105 /* Also need to preprocess expressions within RTEs */
1106 foreach(l, parse->rtable)
1107 {
1109 int kind;
1110 ListCell *lcsq;
1111
1112 if (rte->rtekind == RTE_RELATION)
1113 {
1114 if (rte->tablesample)
1115 rte->tablesample = (TableSampleClause *)
1117 (Node *) rte->tablesample,
1119 }
1120 else if (rte->rtekind == RTE_SUBQUERY)
1121 {
1122 /*
1123 * We don't want to do all preprocessing yet on the subquery's
1124 * expressions, since that will happen when we plan it. But if it
1125 * contains any join aliases of our level, those have to get
1126 * expanded now, because planning of the subquery won't do it.
1127 * That's only possible if the subquery is LATERAL.
1128 */
1129 if (rte->lateral && root->hasJoinRTEs)
1130 rte->subquery = (Query *)
1132 (Node *) rte->subquery);
1133 }
1134 else if (rte->rtekind == RTE_FUNCTION)
1135 {
1136 /* Preprocess the function expression(s) fully */
1137 kind = rte->lateral ? EXPRKIND_RTFUNC_LATERAL : EXPRKIND_RTFUNC;
1138 rte->functions = (List *)
1139 preprocess_expression(root, (Node *) rte->functions, kind);
1140 }
1141 else if (rte->rtekind == RTE_TABLEFUNC)
1142 {
1143 /* Preprocess the function expression(s) fully */
1145 rte->tablefunc = (TableFunc *)
1146 preprocess_expression(root, (Node *) rte->tablefunc, kind);
1147 }
1148 else if (rte->rtekind == RTE_VALUES)
1149 {
1150 /* Preprocess the values lists fully */
1151 kind = rte->lateral ? EXPRKIND_VALUES_LATERAL : EXPRKIND_VALUES;
1152 rte->values_lists = (List *)
1153 preprocess_expression(root, (Node *) rte->values_lists, kind);
1154 }
1155 else if (rte->rtekind == RTE_GROUP)
1156 {
1157 /* Preprocess the groupexprs list fully */
1158 rte->groupexprs = (List *)
1159 preprocess_expression(root, (Node *) rte->groupexprs,
1161 }
1162
1163 /*
1164 * Process each element of the securityQuals list as if it were a
1165 * separate qual expression (as indeed it is). We need to do it this
1166 * way to get proper canonicalization of AND/OR structure. Note that
1167 * this converts each element into an implicit-AND sublist.
1168 */
1169 foreach(lcsq, rte->securityQuals)
1170 {
1172 (Node *) lfirst(lcsq),
1174 }
1175 }
1176
1177 /*
1178 * Now that we are done preprocessing expressions, and in particular done
1179 * flattening join alias variables, get rid of the joinaliasvars lists.
1180 * They no longer match what expressions in the rest of the tree look
1181 * like, because we have not preprocessed expressions in those lists (and
1182 * do not want to; for example, expanding a SubLink there would result in
1183 * a useless unreferenced subplan). Leaving them in place simply creates
1184 * a hazard for later scans of the tree. We could try to prevent that by
1185 * using QTW_IGNORE_JOINALIASES in every tree scan done after this point,
1186 * but that doesn't sound very reliable.
1187 */
1188 if (root->hasJoinRTEs)
1189 {
1190 foreach(l, parse->rtable)
1191 {
1193
1194 rte->joinaliasvars = NIL;
1195 }
1196 }
1197
1198 /*
1199 * Before we flatten GROUP Vars, check which HAVING clauses have collation
1200 * conflicts. When GROUP BY uses a nondeterministic collation, values
1201 * that are "equal" for grouping may be distinguishable under a different
1202 * collation. If such a HAVING clause were moved to WHERE, it would
1203 * filter individual rows before grouping, potentially eliminating some
1204 * members of a group and thereby changing aggregate results.
1205 *
1206 * We do this check before flatten_group_exprs because we can easily
1207 * identify grouping expressions by checking whether a Var references
1208 * RTE_GROUP, and such Vars directly carry the GROUP BY collation as their
1209 * varcollid. After flattening, these Vars are replaced by the underlying
1210 * expressions, and we would have to match expressions in the HAVING
1211 * clause back to grouping expressions, which is much more complex.
1212 */
1213 if (parse->hasGroupRTE)
1216 else
1218
1219 /*
1220 * Replace any Vars in the subquery's targetlist and havingQual that
1221 * reference GROUP outputs with the underlying grouping expressions.
1222 *
1223 * Note that we need to perform this replacement after we've preprocessed
1224 * the grouping expressions. This is to ensure that there is only one
1225 * instance of SubPlan for each SubLink contained within the grouping
1226 * expressions.
1227 */
1228 if (parse->hasGroupRTE)
1229 {
1230 parse->targetList = (List *)
1231 flatten_group_exprs(root, root->parse, (Node *) parse->targetList);
1232 parse->havingQual =
1233 flatten_group_exprs(root, root->parse, parse->havingQual);
1234 }
1235
1236 /* Constant-folding might have removed all set-returning functions */
1237 if (parse->hasTargetSRFs)
1238 parse->hasTargetSRFs = expression_returns_set((Node *) parse->targetList);
1239
1240 /*
1241 * If we have grouping sets, expand the groupingSets tree of this query to
1242 * a flat list of grouping sets. We need to do this before optimizing
1243 * HAVING, since we can't easily tell if there's an empty grouping set
1244 * until we have this representation.
1245 */
1246 if (parse->groupingSets)
1247 {
1248 parse->groupingSets =
1249 expand_grouping_sets(parse->groupingSets, parse->groupDistinct, -1);
1250 }
1251
1252 /*
1253 * In some cases we may want to transfer a HAVING clause into WHERE. We
1254 * cannot do so if the HAVING clause contains aggregates (obviously) or
1255 * volatile functions (since a HAVING clause is supposed to be executed
1256 * only once per group). We also can't do this if there are any grouping
1257 * sets and the clause references any columns that are nullable by the
1258 * grouping sets; the nulled values of those columns are not available
1259 * before the grouping step. (The test on groupClause might seem wrong,
1260 * but it's okay: it's just an optimization to avoid running pull_varnos
1261 * when there cannot be any Vars in the HAVING clause.)
1262 *
1263 * We also cannot do this if the HAVING clause uses a different collation
1264 * than the GROUP BY for any grouping expression whose GROUP BY collation
1265 * is nondeterministic. This is detected before flatten_group_exprs (see
1266 * find_having_collation_conflicts above) and recorded in the
1267 * havingCollationConflicts bitmapset. The bitmapset indexes remain valid
1268 * here because flatten_group_exprs uses expression_tree_mutator, which
1269 * preserves the list length and ordering of havingQual.
1270 *
1271 * Also, it may be that the clause is so expensive to execute that we're
1272 * better off doing it only once per group, despite the loss of
1273 * selectivity. This is hard to estimate short of doing the entire
1274 * planning process twice, so we use a heuristic: clauses containing
1275 * subplans are left in HAVING. Otherwise, we move or copy the HAVING
1276 * clause into WHERE, in hopes of eliminating tuples before aggregation
1277 * instead of after.
1278 *
1279 * If the query has no empty grouping set then we can simply move such a
1280 * clause into WHERE; any group that fails the clause will not be in the
1281 * output because none of its tuples will reach the grouping or
1282 * aggregation stage. Otherwise we have to keep the clause in HAVING to
1283 * ensure that we don't emit a bogus aggregated row. But then the HAVING
1284 * clause must be degenerate (variable-free), so we can copy it into WHERE
1285 * so that query_planner() can use it in a gating Result node. (This could
1286 * be done better, but it seems not worth optimizing.)
1287 *
1288 * Note that a HAVING clause may contain expressions that are not fully
1289 * preprocessed. This can happen if these expressions are part of
1290 * grouping items. In such cases, they are replaced with GROUP Vars in
1291 * the parser and then replaced back after we're done with expression
1292 * preprocessing on havingQual. This is not an issue if the clause
1293 * remains in HAVING, because these expressions will be matched to lower
1294 * target items in setrefs.c. However, if the clause is moved or copied
1295 * into WHERE, we need to ensure that these expressions are fully
1296 * preprocessed.
1297 *
1298 * Note that both havingQual and parse->jointree->quals are in
1299 * implicitly-ANDed-list form at this point, even though they are declared
1300 * as Node *.
1301 */
1302 newHaving = NIL;
1303 havingIdx = 0;
1304 foreach(l, (List *) parse->havingQual)
1305 {
1306 Node *havingclause = (Node *) lfirst(l);
1307
1312 (parse->groupClause && parse->groupingSets &&
1313 bms_is_member(root->group_rtindex, pull_varnos(root, havingclause))))
1314 {
1315 /* keep it in HAVING */
1317 }
1318 else if (parse->groupClause &&
1319 (parse->groupingSets == NIL ||
1320 (List *) linitial(parse->groupingSets) != NIL))
1321 {
1322 /* There is GROUP BY, but no empty grouping set */
1324
1325 /* Preprocess the HAVING clause fully */
1328 /* ... and move it to WHERE */
1329 parse->jointree->quals = (Node *)
1330 list_concat((List *) parse->jointree->quals,
1331 (List *) whereclause);
1332 }
1333 else
1334 {
1335 /* There is an empty grouping set (perhaps implicitly) */
1337
1338 /* Preprocess the HAVING clause fully */
1341 /* ... and put a copy in WHERE */
1342 parse->jointree->quals = (Node *)
1343 list_concat((List *) parse->jointree->quals,
1344 (List *) whereclause);
1345 /* ... and also keep it in HAVING */
1347 }
1348
1349 havingIdx++;
1350 }
1351 parse->havingQual = (Node *) newHaving;
1352
1353 /*
1354 * If we have any outer joins, try to reduce them to plain inner joins.
1355 * This step is most easily done after we've done expression
1356 * preprocessing.
1357 */
1358 if (hasOuterJoins)
1360
1361 /*
1362 * If we have any RTE_RESULT relations, see if they can be deleted from
1363 * the jointree. We also rely on this processing to flatten single-child
1364 * FromExprs underneath outer joins. This step is most effectively done
1365 * after we've done expression preprocessing and outer join reduction.
1366 */
1369
1370 /*
1371 * Do the main planning.
1372 */
1373 grouping_planner(root, tuple_fraction, setops);
1374
1375 /*
1376 * Capture the set of outer-level param IDs we have access to, for use in
1377 * extParam/allParam calculations later.
1378 */
1380
1381 /*
1382 * If any initPlans were created in this query level, adjust the surviving
1383 * Paths' costs and parallel-safety flags to account for them. The
1384 * initPlans won't actually get attached to the plan tree till
1385 * create_plan() runs, but we must include their effects now.
1386 */
1389
1390 /*
1391 * Make sure we've identified the cheapest Path for the final rel. (By
1392 * doing this here not in grouping_planner, we include initPlan costs in
1393 * the decision, though it's unlikely that will change anything.)
1394 */
1396
1397 return root;
1398}
1399
1400/*
1401 * preprocess_expression
1402 * Do subquery_planner's preprocessing work for an expression,
1403 * which can be a targetlist, a WHERE clause (including JOIN/ON
1404 * conditions), a HAVING clause, or a few other things.
1405 */
1406static Node *
1408{
1409 /*
1410 * Fall out quickly if expression is empty. This occurs often enough to
1411 * be worth checking. Note that null->null is the correct conversion for
1412 * implicit-AND result format, too.
1413 */
1414 if (expr == NULL)
1415 return NULL;
1416
1417 /*
1418 * If the query has any join RTEs, replace join alias variables with
1419 * base-relation variables. We must do this first, since any expressions
1420 * we may extract from the joinaliasvars lists have not been preprocessed.
1421 * For example, if we did this after sublink processing, sublinks expanded
1422 * out from join aliases would not get processed. But we can skip this in
1423 * non-lateral RTE functions, VALUES lists, and TABLESAMPLE clauses, since
1424 * they can't contain any Vars of the current query level.
1425 */
1426 if (root->hasJoinRTEs &&
1427 !(kind == EXPRKIND_RTFUNC ||
1428 kind == EXPRKIND_VALUES ||
1429 kind == EXPRKIND_TABLESAMPLE ||
1430 kind == EXPRKIND_TABLEFUNC))
1431 expr = flatten_join_alias_vars(root, root->parse, expr);
1432
1433 /*
1434 * Simplify constant expressions. For function RTEs, this was already
1435 * done by preprocess_function_rtes. (But note we must do it again for
1436 * EXPRKIND_RTFUNC_LATERAL, because those might by now contain
1437 * un-simplified subexpressions inserted by flattening of subqueries or
1438 * join alias variables.)
1439 *
1440 * Note: an essential effect of this is to convert named-argument function
1441 * calls to positional notation and insert the current actual values of
1442 * any default arguments for functions. To ensure that happens, we *must*
1443 * process all expressions here. Previous PG versions sometimes skipped
1444 * const-simplification if it didn't seem worth the trouble, but we can't
1445 * do that anymore.
1446 *
1447 * Note: this also flattens nested AND and OR expressions into N-argument
1448 * form. All processing of a qual expression after this point must be
1449 * careful to maintain AND/OR flatness --- that is, do not generate a tree
1450 * with AND directly under AND, nor OR directly under OR.
1451 */
1452 if (kind != EXPRKIND_RTFUNC)
1453 expr = eval_const_expressions(root, expr);
1454
1455 /*
1456 * If it's a qual or havingQual, canonicalize it.
1457 */
1458 if (kind == EXPRKIND_QUAL)
1459 {
1460 expr = (Node *) canonicalize_qual((Expr *) expr, false);
1461
1462#ifdef OPTIMIZER_DEBUG
1463 printf("After canonicalize_qual()\n");
1464 pprint(expr);
1465#endif
1466 }
1467
1468 /*
1469 * Check for ANY ScalarArrayOpExpr with Const arrays and set the
1470 * hashfuncid of any that might execute more quickly by using hash lookups
1471 * instead of a linear search.
1472 */
1473 if (kind == EXPRKIND_QUAL || kind == EXPRKIND_TARGET)
1474 {
1476 }
1477
1478 /* Expand SubLinks to SubPlans */
1479 if (root->parse->hasSubLinks)
1480 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
1481
1482 /*
1483 * XXX do not insert anything here unless you have grokked the comments in
1484 * SS_replace_correlation_vars ...
1485 */
1486
1487 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
1488 if (root->query_level > 1)
1489 expr = SS_replace_correlation_vars(root, expr);
1490
1491 /*
1492 * If it's a qual or havingQual, convert it to implicit-AND format. (We
1493 * don't want to do this before eval_const_expressions, since the latter
1494 * would be unable to simplify a top-level AND correctly. Also,
1495 * SS_process_sublinks expects explicit-AND format.)
1496 */
1497 if (kind == EXPRKIND_QUAL)
1498 expr = (Node *) make_ands_implicit((Expr *) expr);
1499
1500 return expr;
1501}
1502
1503/*
1504 * preprocess_qual_conditions
1505 * Recursively scan the query's jointree and do subquery_planner's
1506 * preprocessing work on each qual condition found therein.
1507 */
1508static void
1510{
1511 if (jtnode == NULL)
1512 return;
1513 if (IsA(jtnode, RangeTblRef))
1514 {
1515 /* nothing to do here */
1516 }
1517 else if (IsA(jtnode, FromExpr))
1518 {
1519 FromExpr *f = (FromExpr *) jtnode;
1520 ListCell *l;
1521
1522 foreach(l, f->fromlist)
1524
1526 }
1527 else if (IsA(jtnode, JoinExpr))
1528 {
1529 JoinExpr *j = (JoinExpr *) jtnode;
1530
1533
1534 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
1535 }
1536 else
1537 elog(ERROR, "unrecognized node type: %d",
1538 (int) nodeTag(jtnode));
1539}
1540
1541/*
1542 * find_having_collation_conflicts
1543 * Identify HAVING clauses that must not be moved to WHERE due to collation
1544 * mismatches with GROUP BY.
1545 *
1546 * This must be called before flatten_group_exprs, while the HAVING clause
1547 * still contains GROUP Vars (Vars referencing RTE_GROUP). These GROUP Vars
1548 * carry the GROUP BY collation as their varcollid. A GROUP Var with a
1549 * nondeterministic varcollid conflicts whenever some collation-aware ancestor
1550 * on its path applies a different inputcollid: that operator would distinguish
1551 * values which the GROUP BY considers equal, so the clause is unsafe to push
1552 * to WHERE.
1553 *
1554 * Returns a Bitmapset of zero-based indexes into the havingQual list for
1555 * clauses that have collation conflicts and must stay in HAVING.
1556 */
1557static Bitmapset *
1559{
1562 int idx;
1563
1564 if (parse->havingQual == NULL)
1565 return NULL;
1566
1567 ctx.group_rtindex = group_rtindex;
1568 ctx.ancestor_collids = NIL;
1569
1570 idx = 0;
1571 foreach_ptr(Node, clause, (List *) parse->havingQual)
1572 {
1573 if (having_collation_conflict_walker(clause, &ctx))
1575 idx++;
1576 Assert(ctx.ancestor_collids == NIL);
1577 }
1578
1579 return result;
1580}
1581
1582/*
1583 * Walker function for find_having_collation_conflicts.
1584 *
1585 * Walk the clause top-down, maintaining a stack of inputcollids contributed
1586 * by collation-aware ancestors. At each GROUP Var with a nondeterministic
1587 * varcollid, the clause has a conflict if any ancestor's inputcollid differs
1588 * from the GROUP Var's varcollid. Most collation-aware nodes expose their
1589 * inputcollid through exprInputCollation(); RowCompareExpr is the exception,
1590 * as it carries one inputcollid per column in inputcollids[], so we descend
1591 * into its (largs[i], rargs[i]) pairs explicitly with the matching collation
1592 * pushed onto the stack.
1593 */
1594static bool
1596{
1598 bool result;
1599
1600 if (node == NULL)
1601 return false;
1602
1603 if (IsA(node, Var))
1604 {
1605 Var *var = (Var *) node;
1606
1607 /* We should not see any upper-level Vars here */
1608 Assert(var->varlevelsup == 0);
1609
1610 if (var->varno == ctx->group_rtindex &&
1611 OidIsValid(var->varcollid) &&
1612 !get_collation_isdeterministic(var->varcollid))
1613 {
1615 {
1616 if (collid != var->varcollid)
1617 return true;
1618 }
1619 }
1620 return false;
1621 }
1622
1623 if (IsA(node, RowCompareExpr))
1624 {
1626 ListCell *lc_l;
1627 ListCell *lc_r;
1628 ListCell *lc_c;
1629
1630 /*
1631 * Each column of a row comparison is compared under its own
1632 * inputcollids[i]. Walk each (largs[i], rargs[i]) pair with that
1633 * collation pushed, so a Var in column i is checked against the
1634 * collation that actually applies to it.
1635 */
1636 forthree(lc_l, rcexpr->largs,
1637 lc_r, rcexpr->rargs,
1638 lc_c, rcexpr->inputcollids)
1639 {
1641 bool found;
1642
1643 if (OidIsValid(collid))
1645 collid);
1646
1648 ctx) ||
1650 ctx);
1651
1652 if (OidIsValid(collid))
1653 ctx->ancestor_collids =
1655
1656 if (found)
1657 return true;
1658 }
1659 return false;
1660 }
1661
1665 this_collid);
1666
1668 ctx);
1669
1672
1673 return result;
1674}
1675
1676/*
1677 * preprocess_phv_expression
1678 * Do preprocessing on a PlaceHolderVar expression that's been pulled up.
1679 *
1680 * If a LATERAL subquery references an output of another subquery, and that
1681 * output must be wrapped in a PlaceHolderVar because of an intermediate outer
1682 * join, then we'll push the PlaceHolderVar expression down into the subquery
1683 * and later pull it back up during find_lateral_references, which runs after
1684 * subquery_planner has preprocessed all the expressions that were in the
1685 * current query level to start with. So we need to preprocess it then.
1686 */
1687Expr *
1692
1693/*--------------------
1694 * grouping_planner
1695 * Perform planning steps related to grouping, aggregation, etc.
1696 *
1697 * This function adds all required top-level processing to the scan/join
1698 * Path(s) produced by query_planner.
1699 *
1700 * tuple_fraction is the fraction of tuples we expect will be retrieved.
1701 * tuple_fraction is interpreted as follows:
1702 * 0: expect all tuples to be retrieved (normal case)
1703 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
1704 * from the plan to be retrieved
1705 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
1706 * expected to be retrieved (ie, a LIMIT specification).
1707 * setops is used for set operation subqueries to provide the subquery with
1708 * the context in which it's being used so that Paths correctly sorted for the
1709 * set operation can be generated. NULL when not planning a set operation
1710 * child, or when a child of a set op that isn't interested in sorted input.
1711 *
1712 * Returns nothing; the useful output is in the Paths we attach to the
1713 * (UPPERREL_FINAL, NULL) upperrel in *root. In addition,
1714 * root->processed_tlist contains the final processed targetlist.
1715 *
1716 * Note that we have not done set_cheapest() on the final rel; it's convenient
1717 * to leave this to the caller.
1718 *--------------------
1719 */
1720static void
1721grouping_planner(PlannerInfo *root, double tuple_fraction,
1723{
1724 Query *parse = root->parse;
1725 int64 offset_est = 0;
1726 int64 count_est = 0;
1727 double limit_tuples = -1.0;
1728 bool have_postponed_srfs = false;
1735 FinalPathExtraData extra;
1736 ListCell *lc;
1737
1738 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
1739 if (parse->limitCount || parse->limitOffset)
1740 {
1741 tuple_fraction = preprocess_limit(root, tuple_fraction,
1742 &offset_est, &count_est);
1743
1744 /*
1745 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1746 * estimate the effects of using a bounded sort.
1747 */
1748 if (count_est > 0 && offset_est >= 0)
1749 limit_tuples = (double) count_est + (double) offset_est;
1750 }
1751
1752 /* Make tuple_fraction accessible to lower-level routines */
1753 root->tuple_fraction = tuple_fraction;
1754
1755 if (parse->setOperations)
1756 {
1757 /*
1758 * Construct Paths for set operations. The results will not need any
1759 * work except perhaps a top-level sort and/or LIMIT. Note that any
1760 * special work for recursive unions is the responsibility of
1761 * plan_set_operations.
1762 */
1764
1765 /*
1766 * We should not need to call preprocess_targetlist, since we must be
1767 * in a SELECT query node. Instead, use the processed_tlist returned
1768 * by plan_set_operations (since this tells whether it returned any
1769 * resjunk columns!), and transfer any sort key information from the
1770 * original tlist.
1771 */
1772 Assert(parse->commandType == CMD_SELECT);
1773
1774 /* for safety, copy processed_tlist instead of modifying in-place */
1775 root->processed_tlist =
1776 postprocess_setop_tlist(copyObject(root->processed_tlist),
1777 parse->targetList);
1778
1779 /* Also extract the PathTarget form of the setop result tlist */
1780 final_target = current_rel->cheapest_total_path->pathtarget;
1781
1782 /* And check whether it's parallel safe */
1785
1786 /* The setop result tlist couldn't contain any SRFs */
1787 Assert(!parse->hasTargetSRFs);
1789
1790 /*
1791 * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1792 * checked already, but let's make sure).
1793 */
1794 if (parse->rowMarks)
1795 ereport(ERROR,
1797 /*------
1798 translator: %s is a SQL row locking clause such as FOR UPDATE */
1799 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1801 parse->rowMarks)->strength))));
1802
1803 /*
1804 * Calculate pathkeys that represent result ordering requirements
1805 */
1806 Assert(parse->distinctClause == NIL);
1807 root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
1808 parse->sortClause,
1809 root->processed_tlist);
1810 }
1811 else
1812 {
1813 /* No set operations, do regular planning */
1827 bool have_grouping;
1829 List *activeWindows = NIL;
1830 grouping_sets_data *gset_data = NULL;
1832
1833 /* A recursive query should always have setOperations */
1834 Assert(!root->hasRecursion);
1835
1836 /* Preprocess grouping sets and GROUP BY clause, if any */
1837 if (parse->groupingSets)
1838 {
1839 gset_data = preprocess_grouping_sets(root);
1840 }
1841 else if (parse->groupClause)
1842 {
1843 /* Preprocess regular GROUP BY clause, if any */
1844 root->processed_groupClause = preprocess_groupclause(root, NIL);
1845 }
1846
1847 /*
1848 * Preprocess targetlist. Note that much of the remaining planning
1849 * work will be done with the PathTarget representation of tlists, but
1850 * we must also maintain the full representation of the final tlist so
1851 * that we can transfer its decoration (resnames etc) to the topmost
1852 * tlist of the finished Plan. This is kept in processed_tlist.
1853 */
1855
1856 /*
1857 * Mark all the aggregates with resolved aggtranstypes, and detect
1858 * aggregates that are duplicates or can share transition state. We
1859 * must do this before slicing and dicing the tlist into various
1860 * pathtargets, else some copies of the Aggref nodes might escape
1861 * being marked.
1862 */
1863 if (parse->hasAggs)
1864 {
1865 preprocess_aggrefs(root, (Node *) root->processed_tlist);
1866 preprocess_aggrefs(root, (Node *) parse->havingQual);
1867 }
1868
1869 /*
1870 * Locate any window functions in the tlist. (We don't need to look
1871 * anywhere else, since expressions used in ORDER BY will be in there
1872 * too.) Note that they could all have been eliminated by constant
1873 * folding, in which case we don't need to do any more work.
1874 */
1875 if (parse->hasWindowFuncs)
1876 {
1877 wflists = find_window_functions((Node *) root->processed_tlist,
1878 list_length(parse->windowClause));
1879 if (wflists->numWindowFuncs > 0)
1880 {
1881 /*
1882 * See if any modifications can be made to each WindowClause
1883 * to allow the executor to execute the WindowFuncs more
1884 * quickly.
1885 */
1887
1888 /* Extract the list of windows actually in use. */
1889 activeWindows = select_active_windows(root, wflists);
1890
1891 /* Make sure they all have names, for EXPLAIN's use. */
1892 name_active_windows(activeWindows);
1893 }
1894 else
1895 parse->hasWindowFuncs = false;
1896 }
1897
1898 /*
1899 * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1900 * adding logic between here and the query_planner() call. Anything
1901 * that is needed in MIN/MAX-optimizable cases will have to be
1902 * duplicated in planagg.c.
1903 */
1904 if (parse->hasAggs)
1906
1907 /*
1908 * Figure out whether there's a hard limit on the number of rows that
1909 * query_planner's result subplan needs to return. Even if we know a
1910 * hard limit overall, it doesn't apply if the query has any
1911 * grouping/aggregation operations, or SRFs in the tlist.
1912 */
1913 if (parse->groupClause ||
1914 parse->groupingSets ||
1915 parse->distinctClause ||
1916 parse->hasAggs ||
1917 parse->hasWindowFuncs ||
1918 parse->hasTargetSRFs ||
1919 root->hasHavingQual)
1920 root->limit_tuples = -1.0;
1921 else
1922 root->limit_tuples = limit_tuples;
1923
1924 /* Set up data needed by standard_qp_callback */
1925 qp_extra.activeWindows = activeWindows;
1926 qp_extra.gset_data = gset_data;
1927
1928 /*
1929 * If we're a subquery for a set operation, store the SetOperationStmt
1930 * in qp_extra.
1931 */
1932 qp_extra.setop = setops;
1933
1934 /*
1935 * Generate the best unsorted and presorted paths for the scan/join
1936 * portion of this Query, ie the processing represented by the
1937 * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1938 * We also generate (in standard_qp_callback) pathkey representations
1939 * of the query's sort clause, distinct clause, etc.
1940 */
1942
1943 /*
1944 * Convert the query's result tlist into PathTarget format.
1945 *
1946 * Note: this cannot be done before query_planner() has performed
1947 * appendrel expansion, because that might add resjunk entries to
1948 * root->processed_tlist. Waiting till afterwards is also helpful
1949 * because the target width estimates can use per-Var width numbers
1950 * that were obtained within query_planner().
1951 */
1952 final_target = create_pathtarget(root, root->processed_tlist);
1955
1956 /*
1957 * If ORDER BY was given, consider whether we should use a post-sort
1958 * projection, and compute the adjusted target for preceding steps if
1959 * so.
1960 */
1961 if (parse->sortClause)
1962 {
1968 }
1969 else
1970 {
1973 }
1974
1975 /*
1976 * If we have window functions to deal with, the output from any
1977 * grouping step needs to be what the window functions want;
1978 * otherwise, it should be sort_input_target.
1979 */
1980 if (activeWindows)
1981 {
1984 activeWindows);
1987 }
1988 else
1989 {
1992 }
1993
1994 /*
1995 * If we have grouping or aggregation to do, the topmost scan/join
1996 * plan node must emit what the grouping step wants; otherwise, it
1997 * should emit grouping_target.
1998 */
1999 have_grouping = (parse->groupClause || parse->groupingSets ||
2000 parse->hasAggs || root->hasHavingQual);
2001 if (have_grouping)
2002 {
2006 }
2007 else
2008 {
2011 }
2012
2013 /*
2014 * If there are any SRFs in the targetlist, we must separate each of
2015 * these PathTargets into SRF-computing and SRF-free targets. Replace
2016 * each of the named targets with a SRF-free version, and remember the
2017 * list of additional projection steps we need to add afterwards.
2018 */
2019 if (parse->hasTargetSRFs)
2020 {
2021 /* final_target doesn't recompute any SRFs in sort_input_target */
2027 /* likewise for sort_input_target vs. grouping_target */
2033 /* likewise for grouping_target vs. scanjoin_target */
2040 /* scanjoin_target will not have any SRFs precomputed for it */
2046 }
2047 else
2048 {
2049 /* initialize lists; for most of these, dummy values are OK */
2055 }
2056
2057 /* Apply scan/join target. */
2059 && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
2064
2065 /*
2066 * Save the various upper-rel PathTargets we just computed into
2067 * root->upper_targets[]. The core code doesn't use this, but it
2068 * provides a convenient place for extensions to get at the info. For
2069 * consistency, we save all the intermediate targets, even though some
2070 * of the corresponding upperrels might not be needed for this query.
2071 */
2072 root->upper_targets[UPPERREL_FINAL] = final_target;
2073 root->upper_targets[UPPERREL_ORDERED] = final_target;
2074 root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
2076 root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
2077 root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
2078
2079 /*
2080 * If we have grouping and/or aggregation, consider ways to implement
2081 * that. We build a new upperrel representing the output of this
2082 * phase.
2083 */
2084 if (have_grouping)
2085 {
2090 gset_data);
2091 /* Fix things up if grouping_target contains SRFs */
2092 if (parse->hasTargetSRFs)
2096 }
2097
2098 /*
2099 * If we have window functions, consider ways to implement those. We
2100 * build a new upperrel representing the output of this phase.
2101 */
2102 if (activeWindows)
2103 {
2109 wflists,
2110 activeWindows);
2111 /* Fix things up if sort_input_target contains SRFs */
2112 if (parse->hasTargetSRFs)
2116 }
2117
2118 /*
2119 * If there is a DISTINCT clause, consider ways to implement that. We
2120 * build a new upperrel representing the output of this phase.
2121 */
2122 if (parse->distinctClause)
2123 {
2127 }
2128 } /* end of if (setOperations) */
2129
2130 /*
2131 * If ORDER BY was given, consider ways to implement that, and generate a
2132 * new upperrel containing only paths that emit the correct ordering and
2133 * project the correct final_target. We can apply the original
2134 * limit_tuples limit in sort costing here, but only if there are no
2135 * postponed SRFs.
2136 */
2137 if (parse->sortClause)
2138 {
2143 have_postponed_srfs ? -1.0 :
2144 limit_tuples);
2145 /* Fix things up if final_target contains SRFs */
2146 if (parse->hasTargetSRFs)
2150 }
2151
2152 /*
2153 * Now we are prepared to build the final-output upperrel.
2154 */
2156
2157 /*
2158 * If the input rel is marked consider_parallel and there's nothing that's
2159 * not parallel-safe in the LIMIT clause, then the final_rel can be marked
2160 * consider_parallel as well. Note that if the query has rowMarks or is
2161 * not a SELECT, consider_parallel will be false for every relation in the
2162 * query.
2163 */
2164 if (current_rel->consider_parallel &&
2165 is_parallel_safe(root, parse->limitOffset) &&
2166 is_parallel_safe(root, parse->limitCount))
2167 final_rel->consider_parallel = true;
2168
2169 /*
2170 * If the current_rel belongs to a single FDW, so does the final_rel.
2171 */
2172 final_rel->serverid = current_rel->serverid;
2173 final_rel->userid = current_rel->userid;
2174 final_rel->useridiscurrent = current_rel->useridiscurrent;
2175 final_rel->fdwroutine = current_rel->fdwroutine;
2176
2177 /*
2178 * Generate paths for the final_rel. Insert all surviving paths, with
2179 * LockRows, Limit, and/or ModifyTable steps added if needed.
2180 */
2181 foreach(lc, current_rel->pathlist)
2182 {
2183 Path *path = (Path *) lfirst(lc);
2184
2185 /*
2186 * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
2187 * (Note: we intentionally test parse->rowMarks not root->rowMarks
2188 * here. If there are only non-locking rowmarks, they should be
2189 * handled by the ModifyTable node instead. However, root->rowMarks
2190 * is what goes into the LockRows node.)
2191 */
2192 if (parse->rowMarks)
2193 {
2194 path = (Path *) create_lockrows_path(root, final_rel, path,
2195 root->rowMarks,
2197 }
2198
2199 /*
2200 * If there is a LIMIT/OFFSET clause, add the LIMIT node.
2201 */
2202 if (limit_needed(parse))
2203 {
2204 path = (Path *) create_limit_path(root, final_rel, path,
2205 parse->limitOffset,
2206 parse->limitCount,
2207 parse->limitOption,
2208 offset_est, count_est);
2209 }
2210
2211 /*
2212 * If this is an INSERT/UPDATE/DELETE/MERGE, add the ModifyTable node.
2213 */
2214 if (parse->commandType != CMD_SELECT)
2215 {
2216 Index rootRelation;
2217 List *resultRelations = NIL;
2218 List *updateColnosLists = NIL;
2219 List *withCheckOptionLists = NIL;
2220 List *returningLists = NIL;
2221 List *mergeActionLists = NIL;
2222 List *mergeJoinConditions = NIL;
2223 List *rowMarks;
2224
2225 if (bms_membership(root->all_result_relids) == BMS_MULTIPLE)
2226 {
2227 /* Inherited UPDATE/DELETE/MERGE */
2229 parse->resultRelation);
2230 int resultRelation = -1;
2231
2232 /* Pass the root result rel forward to the executor. */
2233 rootRelation = parse->resultRelation;
2234
2235 /* Add only leaf children to ModifyTable. */
2236 while ((resultRelation = bms_next_member(root->leaf_result_relids,
2237 resultRelation)) >= 0)
2238 {
2240 resultRelation);
2241
2242 /*
2243 * Also exclude any leaf rels that have turned dummy since
2244 * being added to the list, for example, by being excluded
2245 * by constraint exclusion.
2246 */
2248 continue;
2249
2250 /* Build per-target-rel lists needed by ModifyTable */
2251 resultRelations = lappend_int(resultRelations,
2252 resultRelation);
2253 if (parse->commandType == CMD_UPDATE)
2254 {
2255 List *update_colnos = root->update_colnos;
2256
2258 update_colnos =
2260 update_colnos,
2261 this_result_rel->relid,
2262 top_result_rel->relid);
2263 updateColnosLists = lappend(updateColnosLists,
2264 update_colnos);
2265 }
2266 if (parse->withCheckOptions)
2267 {
2268 List *withCheckOptions = parse->withCheckOptions;
2269
2276 withCheckOptionLists = lappend(withCheckOptionLists,
2278 }
2279 if (parse->returningList)
2280 {
2281 List *returningList = parse->returningList;
2282
2284 returningList = (List *)
2286 (Node *) returningList,
2289 returningLists = lappend(returningLists,
2290 returningList);
2291 }
2292 if (parse->mergeActionList)
2293 {
2294 ListCell *l;
2295 List *mergeActionList = NIL;
2296
2297 /*
2298 * Copy MergeActions and translate stuff that
2299 * references attribute numbers.
2300 */
2301 foreach(l, parse->mergeActionList)
2302 {
2303 MergeAction *action = lfirst(l),
2304 *leaf_action = copyObject(action);
2305
2306 leaf_action->qual =
2308 (Node *) action->qual,
2311 leaf_action->targetList = (List *)
2313 (Node *) action->targetList,
2316 if (leaf_action->commandType == CMD_UPDATE)
2317 leaf_action->updateColnos =
2319 action->updateColnos,
2320 this_result_rel->relid,
2321 top_result_rel->relid);
2322 mergeActionList = lappend(mergeActionList,
2323 leaf_action);
2324 }
2325
2326 mergeActionLists = lappend(mergeActionLists,
2327 mergeActionList);
2328 }
2329 if (parse->commandType == CMD_MERGE)
2330 {
2331 Node *mergeJoinCondition = parse->mergeJoinCondition;
2332
2334 mergeJoinCondition =
2336 mergeJoinCondition,
2339 mergeJoinConditions = lappend(mergeJoinConditions,
2340 mergeJoinCondition);
2341 }
2342 }
2343
2344 if (resultRelations == NIL)
2345 {
2346 /*
2347 * We managed to exclude every child rel, so generate a
2348 * dummy one-relation plan using info for the top target
2349 * rel (even though that may not be a leaf target).
2350 * Although it's clear that no data will be updated or
2351 * deleted, we still need to have a ModifyTable node so
2352 * that any statement triggers will be executed. (This
2353 * could be cleaner if we fixed nodeModifyTable.c to allow
2354 * zero target relations, but that probably wouldn't be a
2355 * net win.)
2356 */
2357 resultRelations = list_make1_int(parse->resultRelation);
2358 if (parse->commandType == CMD_UPDATE)
2359 updateColnosLists = list_make1(root->update_colnos);
2360 if (parse->withCheckOptions)
2361 withCheckOptionLists = list_make1(parse->withCheckOptions);
2362 if (parse->returningList)
2363 returningLists = list_make1(parse->returningList);
2364 if (parse->mergeActionList)
2365 mergeActionLists = list_make1(parse->mergeActionList);
2366 if (parse->commandType == CMD_MERGE)
2367 mergeJoinConditions = list_make1(parse->mergeJoinCondition);
2368 }
2369 }
2370 else
2371 {
2372 /* Single-relation INSERT/UPDATE/DELETE/MERGE. */
2373 rootRelation = 0; /* there's no separate root rel */
2374 resultRelations = list_make1_int(parse->resultRelation);
2375 if (parse->commandType == CMD_UPDATE)
2376 updateColnosLists = list_make1(root->update_colnos);
2377 if (parse->withCheckOptions)
2378 withCheckOptionLists = list_make1(parse->withCheckOptions);
2379 if (parse->returningList)
2380 returningLists = list_make1(parse->returningList);
2381 if (parse->mergeActionList)
2382 mergeActionLists = list_make1(parse->mergeActionList);
2383 if (parse->commandType == CMD_MERGE)
2384 mergeJoinConditions = list_make1(parse->mergeJoinCondition);
2385 }
2386
2387 /*
2388 * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
2389 * will have dealt with fetching non-locked marked rows, else we
2390 * need to have ModifyTable do that.
2391 */
2392 if (parse->rowMarks)
2393 rowMarks = NIL;
2394 else
2395 rowMarks = root->rowMarks;
2396
2397 path = (Path *)
2399 path,
2400 parse->commandType,
2401 parse->canSetTag,
2402 parse->resultRelation,
2403 rootRelation,
2404 resultRelations,
2405 updateColnosLists,
2406 withCheckOptionLists,
2407 returningLists,
2408 rowMarks,
2409 parse->onConflict,
2410 mergeActionLists,
2411 mergeJoinConditions,
2412 parse->forPortionOf,
2414 }
2415
2416 /* And shove it into final_rel */
2417 add_path(final_rel, path);
2418 }
2419
2420 /*
2421 * Generate partial paths for final_rel, too, if outer query levels might
2422 * be able to make use of them.
2423 */
2424 if (final_rel->consider_parallel && root->query_level > 1 &&
2426 {
2427 Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
2428 foreach(lc, current_rel->partial_pathlist)
2429 {
2430 Path *partial_path = (Path *) lfirst(lc);
2431
2433 }
2434 }
2435
2437 extra.limit_tuples = limit_tuples;
2438 extra.count_est = count_est;
2439 extra.offset_est = offset_est;
2440
2441 /*
2442 * If there is an FDW that's responsible for all baserels of the query,
2443 * let it consider adding ForeignPaths.
2444 */
2445 if (final_rel->fdwroutine &&
2446 final_rel->fdwroutine->GetForeignUpperPaths)
2447 final_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_FINAL,
2449 &extra);
2450
2451 /* Let extensions possibly add some more paths */
2453 (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2454 current_rel, final_rel, &extra);
2455
2456 /* Note: currently, we leave it to callers to do set_cheapest() */
2457}
2458
2459/*
2460 * Do preprocessing for groupingSets clause and related data.
2461 *
2462 * We expect that parse->groupingSets has already been expanded into a flat
2463 * list of grouping sets (that is, just integer Lists of ressortgroupref
2464 * numbers) by expand_grouping_sets(). This function handles the preliminary
2465 * steps of organizing the grouping sets into lists of rollups, and preparing
2466 * annotations which will later be filled in with size estimates.
2467 */
2468static grouping_sets_data *
2470{
2471 Query *parse = root->parse;
2472 List *sets;
2473 int maxref = 0;
2476
2477 /*
2478 * We don't currently make any attempt to optimize the groupClause when
2479 * there are grouping sets, so just duplicate it in processed_groupClause.
2480 */
2481 root->processed_groupClause = parse->groupClause;
2482
2483 /* Detect unhashable and unsortable grouping expressions */
2484 gd->any_hashable = false;
2485 gd->unhashable_refs = NULL;
2486 gd->unsortable_refs = NULL;
2487 gd->unsortable_sets = NIL;
2488
2489 if (parse->groupClause)
2490 {
2491 ListCell *lc;
2492
2493 foreach(lc, parse->groupClause)
2494 {
2496 Index ref = gc->tleSortGroupRef;
2497
2498 if (ref > maxref)
2499 maxref = ref;
2500
2501 if (!gc->hashable)
2502 gd->unhashable_refs = bms_add_member(gd->unhashable_refs, ref);
2503
2504 if (!OidIsValid(gc->sortop))
2505 gd->unsortable_refs = bms_add_member(gd->unsortable_refs, ref);
2506 }
2507 }
2508
2509 /* Allocate workspace array for remapping */
2510 gd->tleref_to_colnum_map = (int *) palloc((maxref + 1) * sizeof(int));
2511
2512 /*
2513 * If we have any unsortable sets, we must extract them before trying to
2514 * prepare rollups. Unsortable sets don't go through
2515 * reorder_grouping_sets, so we must apply the GroupingSetData annotation
2516 * here.
2517 */
2518 if (!bms_is_empty(gd->unsortable_refs))
2519 {
2521 ListCell *lc;
2522
2523 foreach(lc, parse->groupingSets)
2524 {
2525 List *gset = (List *) lfirst(lc);
2526
2527 if (bms_overlap_list(gd->unsortable_refs, gset))
2528 {
2530
2531 gs->set = gset;
2532 gd->unsortable_sets = lappend(gd->unsortable_sets, gs);
2533
2534 /*
2535 * We must enforce here that an unsortable set is hashable;
2536 * later code assumes this. Parse analysis only checks that
2537 * every individual column is either hashable or sortable.
2538 *
2539 * Note that passing this test doesn't guarantee we can
2540 * generate a plan; there might be other showstoppers.
2541 */
2542 if (bms_overlap_list(gd->unhashable_refs, gset))
2543 ereport(ERROR,
2545 errmsg("could not implement GROUP BY"),
2546 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2547 }
2548 else
2550 }
2551
2552 if (sortable_sets)
2554 else
2555 sets = NIL;
2556 }
2557 else
2558 sets = extract_rollup_sets(parse->groupingSets);
2559
2560 foreach(lc_set, sets)
2561 {
2565
2566 /*
2567 * Reorder the current list of grouping sets into correct prefix
2568 * order. If only one aggregation pass is needed, try to make the
2569 * list match the ORDER BY clause; if more than one pass is needed, we
2570 * don't bother with that.
2571 *
2572 * Note that this reorders the sets from smallest-member-first to
2573 * largest-member-first, and applies the GroupingSetData annotations,
2574 * though the data will be filled in later.
2575 */
2577 (list_length(sets) == 1
2578 ? parse->sortClause
2579 : NIL));
2580
2581 /*
2582 * Get the initial (and therefore largest) grouping set.
2583 */
2585
2586 /*
2587 * Order the groupClause appropriately. If the first grouping set is
2588 * empty, then the groupClause must also be empty; otherwise we have
2589 * to force the groupClause to match that grouping set's order.
2590 *
2591 * (The first grouping set can be empty even though parse->groupClause
2592 * is not empty only if all non-empty grouping sets are unsortable.
2593 * The groupClauses for hashed grouping sets are built later on.)
2594 */
2595 if (gs->set)
2596 rollup->groupClause = preprocess_groupclause(root, gs->set);
2597 else
2598 rollup->groupClause = NIL;
2599
2600 /*
2601 * Is it hashable? We pretend empty sets are hashable even though we
2602 * actually force them not to be hashed later. But don't bother if
2603 * there's nothing but empty sets (since in that case we can't hash
2604 * anything).
2605 */
2606 if (gs->set &&
2607 !bms_overlap_list(gd->unhashable_refs, gs->set))
2608 {
2609 rollup->hashable = true;
2610 gd->any_hashable = true;
2611 }
2612
2613 /*
2614 * Now that we've pinned down an order for the groupClause for this
2615 * list of grouping sets, we need to remap the entries in the grouping
2616 * sets from sortgrouprefs to plain indices (0-based) into the
2617 * groupClause for this collection of grouping sets. We keep the
2618 * original form for later use, though.
2619 */
2620 rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
2622 gd->tleref_to_colnum_map);
2623 rollup->gsets_data = current_sets;
2624
2625 gd->rollups = lappend(gd->rollups, rollup);
2626 }
2627
2628 if (gd->unsortable_sets)
2629 {
2630 /*
2631 * We have not yet pinned down a groupclause for this, but we will
2632 * need index-based lists for estimation purposes. Construct
2633 * hash_sets_idx based on the entire original groupclause for now.
2634 */
2635 gd->hash_sets_idx = remap_to_groupclause_idx(parse->groupClause,
2636 gd->unsortable_sets,
2637 gd->tleref_to_colnum_map);
2638 gd->any_hashable = true;
2639 }
2640
2641 return gd;
2642}
2643
2644/*
2645 * Given a groupclause and a list of GroupingSetData, return equivalent sets
2646 * (without annotation) mapped to indexes into the given groupclause.
2647 */
2648static List *
2650 List *gsets,
2651 int *tleref_to_colnum_map)
2652{
2653 int ref = 0;
2654 List *result = NIL;
2655 ListCell *lc;
2656
2657 foreach(lc, groupClause)
2658 {
2660
2661 tleref_to_colnum_map[gc->tleSortGroupRef] = ref++;
2662 }
2663
2664 foreach(lc, gsets)
2665 {
2666 List *set = NIL;
2667 ListCell *lc2;
2669
2670 foreach(lc2, gs->set)
2671 {
2672 set = lappend_int(set, tleref_to_colnum_map[lfirst_int(lc2)]);
2673 }
2674
2675 result = lappend(result, set);
2676 }
2677
2678 return result;
2679}
2680
2681
2682/*
2683 * preprocess_rowmarks - set up PlanRowMarks if needed
2684 */
2685static void
2687{
2688 Query *parse = root->parse;
2689 Bitmapset *rels;
2690 List *prowmarks;
2691 ListCell *l;
2692 int i;
2693
2694 if (parse->rowMarks)
2695 {
2696 /*
2697 * We've got trouble if FOR [KEY] UPDATE/SHARE appears inside
2698 * grouping, since grouping renders a reference to individual tuple
2699 * CTIDs invalid. This is also checked at parse time, but that's
2700 * insufficient because of rule substitution, query pullup, etc.
2701 */
2703 parse->rowMarks)->strength);
2704 }
2705 else
2706 {
2707 /*
2708 * We only need rowmarks for UPDATE, DELETE, MERGE, or FOR [KEY]
2709 * UPDATE/SHARE.
2710 */
2711 if (parse->commandType != CMD_UPDATE &&
2712 parse->commandType != CMD_DELETE &&
2713 parse->commandType != CMD_MERGE)
2714 return;
2715 }
2716
2717 /*
2718 * We need to have rowmarks for all base relations except the target. We
2719 * make a bitmapset of all base rels and then remove the items we don't
2720 * need or have FOR [KEY] UPDATE/SHARE marks for.
2721 */
2722 rels = get_relids_in_jointree((Node *) parse->jointree, false, false);
2723 if (parse->resultRelation)
2724 rels = bms_del_member(rels, parse->resultRelation);
2725
2726 /*
2727 * Convert RowMarkClauses to PlanRowMark representation.
2728 */
2729 prowmarks = NIL;
2730 foreach(l, parse->rowMarks)
2731 {
2733 RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
2735
2736 /*
2737 * Currently, it is syntactically impossible to have FOR UPDATE et al
2738 * applied to an update/delete target rel. If that ever becomes
2739 * possible, we should drop the target from the PlanRowMark list.
2740 */
2741 Assert(rc->rti != parse->resultRelation);
2742
2743 /*
2744 * Ignore RowMarkClauses for subqueries; they aren't real tables and
2745 * can't support true locking. Subqueries that got flattened into the
2746 * main query should be ignored completely. Any that didn't will get
2747 * ROW_MARK_COPY items in the next loop.
2748 */
2749 if (rte->rtekind != RTE_RELATION)
2750 continue;
2751
2752 rels = bms_del_member(rels, rc->rti);
2753
2755 newrc->rti = newrc->prti = rc->rti;
2756 newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2757 newrc->markType = select_rowmark_type(rte, rc->strength);
2758 newrc->allMarkTypes = (1 << newrc->markType);
2759 newrc->strength = rc->strength;
2760 newrc->waitPolicy = rc->waitPolicy;
2761 newrc->isParent = false;
2762
2764 }
2765
2766 /*
2767 * Now, add rowmarks for any non-target, non-locked base relations.
2768 */
2769 i = 0;
2770 foreach(l, parse->rtable)
2771 {
2774
2775 i++;
2776 if (!bms_is_member(i, rels))
2777 continue;
2778
2780 newrc->rti = newrc->prti = i;
2781 newrc->rowmarkId = ++(root->glob->lastRowMarkId);
2782 newrc->markType = select_rowmark_type(rte, LCS_NONE);
2783 newrc->allMarkTypes = (1 << newrc->markType);
2784 newrc->strength = LCS_NONE;
2785 newrc->waitPolicy = LockWaitBlock; /* doesn't matter */
2786 newrc->isParent = false;
2787
2789 }
2790
2791 root->rowMarks = prowmarks;
2792}
2793
2794/*
2795 * Select RowMarkType to use for a given table
2796 */
2799{
2800 if (rte->rtekind != RTE_RELATION)
2801 {
2802 /* If it's not a table at all, use ROW_MARK_COPY */
2803 return ROW_MARK_COPY;
2804 }
2805 else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2806 {
2807 /* Let the FDW select the rowmark type, if it wants to */
2808 FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2809
2810 if (fdwroutine->GetForeignRowMarkType != NULL)
2811 return fdwroutine->GetForeignRowMarkType(rte, strength);
2812 /* Otherwise, use ROW_MARK_COPY by default */
2813 return ROW_MARK_COPY;
2814 }
2815 else
2816 {
2817 /* Regular table, apply the appropriate lock type */
2818 switch (strength)
2819 {
2820 case LCS_NONE:
2821
2822 /*
2823 * We don't need a tuple lock, only the ability to re-fetch
2824 * the row.
2825 */
2826 return ROW_MARK_REFERENCE;
2827 break;
2828 case LCS_FORKEYSHARE:
2829 return ROW_MARK_KEYSHARE;
2830 break;
2831 case LCS_FORSHARE:
2832 return ROW_MARK_SHARE;
2833 break;
2834 case LCS_FORNOKEYUPDATE:
2836 break;
2837 case LCS_FORUPDATE:
2838 return ROW_MARK_EXCLUSIVE;
2839 break;
2840 }
2841 elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2842 return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2843 }
2844}
2845
2846/*
2847 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
2848 *
2849 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
2850 * results back in *count_est and *offset_est. These variables are set to
2851 * 0 if the corresponding clause is not present, and -1 if it's present
2852 * but we couldn't estimate the value for it. (The "0" convention is OK
2853 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
2854 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
2855 * usual practice of never estimating less than one row.) These values will
2856 * be passed to create_limit_path, which see if you change this code.
2857 *
2858 * The return value is the suitably adjusted tuple_fraction to use for
2859 * planning the query. This adjustment is not overridable, since it reflects
2860 * plan actions that grouping_planner() will certainly take, not assumptions
2861 * about context.
2862 */
2863static double
2864preprocess_limit(PlannerInfo *root, double tuple_fraction,
2865 int64 *offset_est, int64 *count_est)
2866{
2867 Query *parse = root->parse;
2868 Node *est;
2869 double limit_fraction;
2870
2871 /* Should not be called unless LIMIT or OFFSET */
2872 Assert(parse->limitCount || parse->limitOffset);
2873
2874 /*
2875 * Try to obtain the clause values. We use estimate_expression_value
2876 * primarily because it can sometimes do something useful with Params.
2877 */
2878 if (parse->limitCount)
2879 {
2880 est = estimate_expression_value(root, parse->limitCount);
2881 if (est && IsA(est, Const))
2882 {
2883 if (((Const *) est)->constisnull)
2884 {
2885 /* NULL indicates LIMIT ALL, ie, no limit */
2886 *count_est = 0; /* treat as not present */
2887 }
2888 else
2889 {
2890 *count_est = DatumGetInt64(((Const *) est)->constvalue);
2891 if (*count_est <= 0)
2892 *count_est = 1; /* force to at least 1 */
2893 }
2894 }
2895 else
2896 *count_est = -1; /* can't estimate */
2897 }
2898 else
2899 *count_est = 0; /* not present */
2900
2901 if (parse->limitOffset)
2902 {
2903 est = estimate_expression_value(root, parse->limitOffset);
2904 if (est && IsA(est, Const))
2905 {
2906 if (((Const *) est)->constisnull)
2907 {
2908 /* Treat NULL as no offset; the executor will too */
2909 *offset_est = 0; /* treat as not present */
2910 }
2911 else
2912 {
2913 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
2914 if (*offset_est < 0)
2915 *offset_est = 0; /* treat as not present */
2916 }
2917 }
2918 else
2919 *offset_est = -1; /* can't estimate */
2920 }
2921 else
2922 *offset_est = 0; /* not present */
2923
2924 if (*count_est != 0)
2925 {
2926 /*
2927 * A LIMIT clause limits the absolute number of tuples returned.
2928 * However, if it's not a constant LIMIT then we have to guess; for
2929 * lack of a better idea, assume 10% of the plan's result is wanted.
2930 */
2931 if (*count_est < 0 || *offset_est < 0)
2932 {
2933 /* LIMIT or OFFSET is an expression ... punt ... */
2934 limit_fraction = 0.10;
2935 }
2936 else
2937 {
2938 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
2939 limit_fraction = (double) *count_est + (double) *offset_est;
2940 }
2941
2942 /*
2943 * If we have absolute limits from both caller and LIMIT, use the
2944 * smaller value; likewise if they are both fractional. If one is
2945 * fractional and the other absolute, we can't easily determine which
2946 * is smaller, but we use the heuristic that the absolute will usually
2947 * be smaller.
2948 */
2949 if (tuple_fraction >= 1.0)
2950 {
2951 if (limit_fraction >= 1.0)
2952 {
2953 /* both absolute */
2954 tuple_fraction = Min(tuple_fraction, limit_fraction);
2955 }
2956 else
2957 {
2958 /* caller absolute, limit fractional; use caller's value */
2959 }
2960 }
2961 else if (tuple_fraction > 0.0)
2962 {
2963 if (limit_fraction >= 1.0)
2964 {
2965 /* caller fractional, limit absolute; use limit */
2966 tuple_fraction = limit_fraction;
2967 }
2968 else
2969 {
2970 /* both fractional */
2971 tuple_fraction = Min(tuple_fraction, limit_fraction);
2972 }
2973 }
2974 else
2975 {
2976 /* no info from caller, just use limit */
2977 tuple_fraction = limit_fraction;
2978 }
2979 }
2980 else if (*offset_est != 0 && tuple_fraction > 0.0)
2981 {
2982 /*
2983 * We have an OFFSET but no LIMIT. This acts entirely differently
2984 * from the LIMIT case: here, we need to increase rather than decrease
2985 * the caller's tuple_fraction, because the OFFSET acts to cause more
2986 * tuples to be fetched instead of fewer. This only matters if we got
2987 * a tuple_fraction > 0, however.
2988 *
2989 * As above, use 10% if OFFSET is present but unestimatable.
2990 */
2991 if (*offset_est < 0)
2992 limit_fraction = 0.10;
2993 else
2994 limit_fraction = (double) *offset_est;
2995
2996 /*
2997 * If we have absolute counts from both caller and OFFSET, add them
2998 * together; likewise if they are both fractional. If one is
2999 * fractional and the other absolute, we want to take the larger, and
3000 * we heuristically assume that's the fractional one.
3001 */
3002 if (tuple_fraction >= 1.0)
3003 {
3004 if (limit_fraction >= 1.0)
3005 {
3006 /* both absolute, so add them together */
3007 tuple_fraction += limit_fraction;
3008 }
3009 else
3010 {
3011 /* caller absolute, limit fractional; use limit */
3012 tuple_fraction = limit_fraction;
3013 }
3014 }
3015 else
3016 {
3017 if (limit_fraction >= 1.0)
3018 {
3019 /* caller fractional, limit absolute; use caller's value */
3020 }
3021 else
3022 {
3023 /* both fractional, so add them together */
3024 tuple_fraction += limit_fraction;
3025 if (tuple_fraction >= 1.0)
3026 tuple_fraction = 0.0; /* assume fetch all */
3027 }
3028 }
3029 }
3030
3031 return tuple_fraction;
3032}
3033
3034/*
3035 * limit_needed - do we actually need a Limit plan node?
3036 *
3037 * If we have constant-zero OFFSET and constant-null LIMIT, we can skip adding
3038 * a Limit node. This is worth checking for because "OFFSET 0" is a common
3039 * locution for an optimization fence. (Because other places in the planner
3040 * merely check whether parse->limitOffset isn't NULL, it will still work as
3041 * an optimization fence --- we're just suppressing unnecessary run-time
3042 * overhead.)
3043 *
3044 * This might look like it could be merged into preprocess_limit, but there's
3045 * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas
3046 * in preprocess_limit it's good enough to consider estimated values.
3047 */
3048bool
3050{
3051 Node *node;
3052
3053 node = parse->limitCount;
3054 if (node)
3055 {
3056 if (IsA(node, Const))
3057 {
3058 /* NULL indicates LIMIT ALL, ie, no limit */
3059 if (!((Const *) node)->constisnull)
3060 return true; /* LIMIT with a constant value */
3061 }
3062 else
3063 return true; /* non-constant LIMIT */
3064 }
3065
3066 node = parse->limitOffset;
3067 if (node)
3068 {
3069 if (IsA(node, Const))
3070 {
3071 /* Treat NULL as no offset; the executor would too */
3072 if (!((Const *) node)->constisnull)
3073 {
3074 int64 offset = DatumGetInt64(((Const *) node)->constvalue);
3075
3076 if (offset != 0)
3077 return true; /* OFFSET with a nonzero value */
3078 }
3079 }
3080 else
3081 return true; /* non-constant OFFSET */
3082 }
3083
3084 return false; /* don't need a Limit plan node */
3085}
3086
3087/*
3088 * preprocess_groupclause - do preparatory work on GROUP BY clause
3089 *
3090 * The idea here is to adjust the ordering of the GROUP BY elements
3091 * (which in itself is semantically insignificant) to match ORDER BY,
3092 * thereby allowing a single sort operation to both implement the ORDER BY
3093 * requirement and set up for a Unique step that implements GROUP BY.
3094 * We also consider partial match between GROUP BY and ORDER BY elements,
3095 * which could allow to implement ORDER BY using the incremental sort.
3096 *
3097 * We also consider other orderings of the GROUP BY elements, which could
3098 * match the sort ordering of other possible plans (eg an indexscan) and
3099 * thereby reduce cost. This is implemented during the generation of grouping
3100 * paths. See get_useful_group_keys_orderings() for details.
3101 *
3102 * Note: we need no comparable processing of the distinctClause because
3103 * the parser already enforced that that matches ORDER BY.
3104 *
3105 * Note: we return a fresh List, but its elements are the same
3106 * SortGroupClauses appearing in parse->groupClause. This is important
3107 * because later processing may modify the processed_groupClause list.
3108 *
3109 * For grouping sets, the order of items is instead forced to agree with that
3110 * of the grouping set (and items not in the grouping set are skipped). The
3111 * work of sorting the order of grouping set elements to match the ORDER BY if
3112 * possible is done elsewhere.
3113 */
3114static List *
3116{
3117 Query *parse = root->parse;
3119 ListCell *sl;
3120 ListCell *gl;
3121
3122 /* For grouping sets, we need to force the ordering */
3123 if (force)
3124 {
3125 foreach(sl, force)
3126 {
3129
3131 }
3132
3133 return new_groupclause;
3134 }
3135
3136 /* If no ORDER BY, nothing useful to do here */
3137 if (parse->sortClause == NIL)
3138 return list_copy(parse->groupClause);
3139
3140 /*
3141 * Scan the ORDER BY clause and construct a list of matching GROUP BY
3142 * items, but only as far as we can make a matching prefix.
3143 *
3144 * This code assumes that the sortClause contains no duplicate items.
3145 */
3146 foreach(sl, parse->sortClause)
3147 {
3149
3150 foreach(gl, parse->groupClause)
3151 {
3153
3154 if (equal(gc, sc))
3155 {
3157 break;
3158 }
3159 }
3160 if (gl == NULL)
3161 break; /* no match, so stop scanning */
3162 }
3163
3164
3165 /* If no match at all, no point in reordering GROUP BY */
3166 if (new_groupclause == NIL)
3167 return list_copy(parse->groupClause);
3168
3169 /*
3170 * Add any remaining GROUP BY items to the new list. We don't require a
3171 * complete match, because even partial match allows ORDER BY to be
3172 * implemented using incremental sort. Also, give up if there are any
3173 * non-sortable GROUP BY items, since then there's no hope anyway.
3174 */
3175 foreach(gl, parse->groupClause)
3176 {
3178
3180 continue; /* it matched an ORDER BY item */
3181 if (!OidIsValid(gc->sortop)) /* give up, GROUP BY can't be sorted */
3182 return list_copy(parse->groupClause);
3184 }
3185
3186 /* Success --- install the rearranged GROUP BY list */
3188 return new_groupclause;
3189}
3190
3191/*
3192 * Extract lists of grouping sets that can be implemented using a single
3193 * rollup-type aggregate pass each. Returns a list of lists of grouping sets.
3194 *
3195 * Input must be sorted with smallest sets first. Result has each sublist
3196 * sorted with smallest sets first.
3197 *
3198 * We want to produce the absolute minimum possible number of lists here to
3199 * avoid excess sorts. Fortunately, there is an algorithm for this; the problem
3200 * of finding the minimal partition of a partially-ordered set into chains
3201 * (which is what we need, taking the list of grouping sets as a poset ordered
3202 * by set inclusion) can be mapped to the problem of finding the maximum
3203 * cardinality matching on a bipartite graph, which is solvable in polynomial
3204 * time with a worst case of no worse than O(n^2.5) and usually much
3205 * better. Since our N is at most 4096, we don't need to consider fallbacks to
3206 * heuristic or approximate methods. (Planning time for a 12-d cube is under
3207 * half a second on my modest system even with optimization off and assertions
3208 * on.)
3209 */
3210static List *
3212{
3213 int num_sets_raw = list_length(groupingSets);
3214 int num_empty = 0;
3215 int num_sets = 0; /* distinct sets */
3216 int num_chains = 0;
3217 List *result = NIL;
3218 List **results;
3219 List **orig_sets;
3221 int *chains;
3222 short **adjacency;
3223 short *adjacency_buf;
3225 int i;
3226 int j;
3227 int j_size;
3228 ListCell *lc1 = list_head(groupingSets);
3229 ListCell *lc;
3230
3231 /*
3232 * Start by stripping out empty sets. The algorithm doesn't require this,
3233 * but the planner currently needs all empty sets to be returned in the
3234 * first list, so we strip them here and add them back after.
3235 */
3236 while (lc1 && lfirst(lc1) == NIL)
3237 {
3238 ++num_empty;
3239 lc1 = lnext(groupingSets, lc1);
3240 }
3241
3242 /* bail out now if it turns out that all we had were empty sets. */
3243 if (!lc1)
3244 return list_make1(groupingSets);
3245
3246 /*----------
3247 * We don't strictly need to remove duplicate sets here, but if we don't,
3248 * they tend to become scattered through the result, which is a bit
3249 * confusing (and irritating if we ever decide to optimize them out).
3250 * So we remove them here and add them back after.
3251 *
3252 * For each non-duplicate set, we fill in the following:
3253 *
3254 * orig_sets[i] = list of the original set lists
3255 * set_masks[i] = bitmapset for testing inclusion
3256 * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3257 *
3258 * chains[i] will be the result group this set is assigned to.
3259 *
3260 * We index all of these from 1 rather than 0 because it is convenient
3261 * to leave 0 free for the NIL node in the graph algorithm.
3262 *----------
3263 */
3264 orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
3265 set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3266 adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3267 adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3268
3269 j_size = 0;
3270 j = 0;
3271 i = 1;
3272
3273 for_each_cell(lc, groupingSets, lc1)
3274 {
3275 List *candidate = (List *) lfirst(lc);
3277 ListCell *lc2;
3278 int dup_of = 0;
3279
3280 foreach(lc2, candidate)
3281 {
3283 }
3284
3285 /* we can only be a dup if we're the same length as a previous set */
3287 {
3288 int k;
3289
3290 for (k = j; k < i; ++k)
3291 {
3293 {
3294 dup_of = k;
3295 break;
3296 }
3297 }
3298 }
3299 else if (j_size < list_length(candidate))
3300 {
3302 j = i;
3303 }
3304
3305 if (dup_of > 0)
3306 {
3309 }
3310 else
3311 {
3312 int k;
3313 int n_adj = 0;
3314
3317
3318 /* fill in adjacency list; no need to compare equal-size sets */
3319
3320 for (k = j - 1; k > 0; --k)
3321 {
3323 adjacency_buf[++n_adj] = k;
3324 }
3325
3326 if (n_adj > 0)
3327 {
3328 adjacency_buf[0] = n_adj;
3329 adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3330 memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3331 }
3332 else
3333 adjacency[i] = NULL;
3334
3335 ++i;
3336 }
3337 }
3338
3339 num_sets = i - 1;
3340
3341 /*
3342 * Apply the graph matching algorithm to do the work.
3343 */
3344 state = BipartiteMatch(num_sets, num_sets, adjacency);
3345
3346 /*
3347 * Now, the state->pair* fields have the info we need to assign sets to
3348 * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3349 * pair_vu[v] = u (both will be true, but we check both so that we can do
3350 * it in one pass)
3351 */
3352 chains = palloc0((num_sets + 1) * sizeof(int));
3353
3354 for (i = 1; i <= num_sets; ++i)
3355 {
3356 int u = state->pair_vu[i];
3357 int v = state->pair_uv[i];
3358
3359 if (u > 0 && u < i)
3360 chains[i] = chains[u];
3361 else if (v > 0 && v < i)
3362 chains[i] = chains[v];
3363 else
3364 chains[i] = ++num_chains;
3365 }
3366
3367 /* build result lists. */
3368 results = palloc0((num_chains + 1) * sizeof(List *));
3369
3370 for (i = 1; i <= num_sets; ++i)
3371 {
3372 int c = chains[i];
3373
3374 Assert(c > 0);
3375
3376 results[c] = list_concat(results[c], orig_sets[i]);
3377 }
3378
3379 /* push any empty sets back on the first list. */
3380 while (num_empty-- > 0)
3381 results[1] = lcons(NIL, results[1]);
3382
3383 /* make result list */
3384 for (i = 1; i <= num_chains; ++i)
3385 result = lappend(result, results[i]);
3386
3387 /*
3388 * Free all the things.
3389 *
3390 * (This is over-fussy for small sets but for large sets we could have
3391 * tied up a nontrivial amount of memory.)
3392 */
3394 pfree(results);
3395 pfree(chains);
3396 for (i = 1; i <= num_sets; ++i)
3397 if (adjacency[i])
3398 pfree(adjacency[i]);
3399 pfree(adjacency);
3402 for (i = 1; i <= num_sets; ++i)
3405
3406 return result;
3407}
3408
3409/*
3410 * Reorder the elements of a list of grouping sets such that they have correct
3411 * prefix relationships. Also inserts the GroupingSetData annotations.
3412 *
3413 * The input must be ordered with smallest sets first; the result is returned
3414 * with largest sets first. Note that the result shares no list substructure
3415 * with the input, so it's safe for the caller to modify it later.
3416 *
3417 * If we're passed in a sortclause, we follow its order of columns to the
3418 * extent possible, to minimize the chance that we add unnecessary sorts.
3419 * (We're trying here to ensure that GROUPING SETS ((a,b,c),(c)) ORDER BY c,b,a
3420 * gets implemented in one pass.)
3421 */
3422static List *
3424{
3425 ListCell *lc;
3426 List *previous = NIL;
3427 List *result = NIL;
3428
3429 foreach(lc, groupingSets)
3430 {
3431 List *candidate = (List *) lfirst(lc);
3434
3435 while (list_length(sortclause) > list_length(previous) &&
3436 new_elems != NIL)
3437 {
3439 int ref = sc->tleSortGroupRef;
3440
3442 {
3443 previous = lappend_int(previous, ref);
3445 }
3446 else
3447 {
3448 /* diverged from the sortclause; give up on it */
3449 sortclause = NIL;
3450 break;
3451 }
3452 }
3453
3454 previous = list_concat(previous, new_elems);
3455
3456 gs->set = list_copy(previous);
3457 result = lcons(gs, result);
3458 }
3459
3460 list_free(previous);
3461
3462 return result;
3463}
3464
3465/*
3466 * has_volatile_pathkey
3467 * Returns true if any PathKey in 'keys' has an EquivalenceClass
3468 * containing a volatile function. Otherwise returns false.
3469 */
3470static bool
3472{
3473 ListCell *lc;
3474
3475 foreach(lc, keys)
3476 {
3478
3479 if (pathkey->pk_eclass->ec_has_volatile)
3480 return true;
3481 }
3482
3483 return false;
3484}
3485
3486/*
3487 * adjust_group_pathkeys_for_groupagg
3488 * Add pathkeys to root->group_pathkeys to reflect the best set of
3489 * pre-ordered input for ordered aggregates.
3490 *
3491 * We define "best" as the pathkeys that suit the largest number of
3492 * aggregate functions. We find these by looking at the first ORDER BY /
3493 * DISTINCT aggregate and take the pathkeys for that before searching for
3494 * other aggregates that require the same or a more strict variation of the
3495 * same pathkeys. We then repeat that process for any remaining aggregates
3496 * with different pathkeys and if we find another set of pathkeys that suits a
3497 * larger number of aggregates then we select those pathkeys instead.
3498 *
3499 * When the best pathkeys are found we also mark each Aggref that can use
3500 * those pathkeys as aggpresorted = true.
3501 *
3502 * Note: When an aggregate function's ORDER BY / DISTINCT clause contains any
3503 * volatile functions, we never make use of these pathkeys. We want to ensure
3504 * that sorts using volatile functions are done independently in each Aggref
3505 * rather than once at the query level. If we were to allow this then Aggrefs
3506 * with compatible sort orders would all transition their rows in the same
3507 * order if those pathkeys were deemed to be the best pathkeys to sort on.
3508 * Whereas, if some other set of Aggref's pathkeys happened to be deemed
3509 * better pathkeys to sort on, then the volatile function Aggrefs would be
3510 * left to perform their sorts individually. To avoid this inconsistent
3511 * behavior which could make Aggref results depend on what other Aggrefs the
3512 * query contains, we always force Aggrefs with volatile functions to perform
3513 * their own sorts.
3514 */
3515static void
3517{
3518 List *grouppathkeys = root->group_pathkeys;
3522 ListCell *lc;
3523 int i;
3524
3525 /* Shouldn't be here if there are grouping sets */
3526 Assert(root->parse->groupingSets == NIL);
3527 /* Shouldn't be here unless there are some ordered aggregates */
3528 Assert(root->numOrderedAggs > 0);
3529
3530 /* Do nothing if disabled */
3532 return;
3533
3534 /*
3535 * Make a first pass over all AggInfos to collect a Bitmapset containing
3536 * the indexes of all AggInfos to be processed below.
3537 */
3539 foreach(lc, root->agginfos)
3540 {
3542 Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3543
3544 if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
3545 continue;
3546
3547 /* Skip unless there's a DISTINCT or ORDER BY clause */
3548 if (aggref->aggdistinct == NIL && aggref->aggorder == NIL)
3549 continue;
3550
3551 /* Additional safety checks are needed if there's a FILTER clause */
3552 if (aggref->aggfilter != NULL)
3553 {
3554 ListCell *lc2;
3555 bool allow_presort = true;
3556
3557 /*
3558 * When the Aggref has a FILTER clause, it's possible that the
3559 * filter removes rows that cannot be sorted because the
3560 * expression to sort by results in an error during its
3561 * evaluation. This is a problem for presorting as that happens
3562 * before the FILTER, whereas without presorting, the Aggregate
3563 * node will apply the FILTER *before* sorting. So that we never
3564 * try to sort anything that might error, here we aim to skip over
3565 * any Aggrefs with arguments with expressions which, when
3566 * evaluated, could cause an ERROR. Vars and Consts are ok. There
3567 * may be more cases that should be allowed, but more thought
3568 * needs to be given. Err on the side of caution.
3569 */
3570 foreach(lc2, aggref->args)
3571 {
3573 Expr *expr = tle->expr;
3574
3575 while (IsA(expr, RelabelType))
3576 expr = (Expr *) (castNode(RelabelType, expr))->arg;
3577
3578 /* Common case, Vars and Consts are ok */
3579 if (IsA(expr, Var) || IsA(expr, Const))
3580 continue;
3581
3582 /* Unsupported. Don't try to presort for this Aggref */
3583 allow_presort = false;
3584 break;
3585 }
3586
3587 /* Skip unsupported Aggrefs */
3588 if (!allow_presort)
3589 continue;
3590 }
3591
3594 }
3595
3596 /*
3597 * Now process all the unprocessed_aggs to find the best set of pathkeys
3598 * for the given set of aggregates.
3599 *
3600 * On the first outer loop here 'bestaggs' will be empty. We'll populate
3601 * this during the first loop using the pathkeys for the very first
3602 * AggInfo then taking any stronger pathkeys from any other AggInfos with
3603 * a more strict set of compatible pathkeys. Once the outer loop is
3604 * complete, we mark off all the aggregates with compatible pathkeys then
3605 * remove those from the unprocessed_aggs and repeat the process to try to
3606 * find another set of pathkeys that are suitable for a larger number of
3607 * aggregates. The outer loop will stop when there are not enough
3608 * unprocessed aggregates for it to be possible to find a set of pathkeys
3609 * to suit a larger number of aggregates.
3610 */
3611 bestpathkeys = NIL;
3612 bestaggs = NULL;
3614 {
3617
3618 i = -1;
3619 while ((i = bms_next_member(unprocessed_aggs, i)) >= 0)
3620 {
3621 AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3622 Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3623 List *sortlist;
3624 List *pathkeys;
3625
3626 if (aggref->aggdistinct != NIL)
3627 sortlist = aggref->aggdistinct;
3628 else
3629 sortlist = aggref->aggorder;
3630
3632 aggref->args);
3633
3634 /*
3635 * Ignore Aggrefs which have volatile functions in their ORDER BY
3636 * or DISTINCT clause.
3637 */
3638 if (has_volatile_pathkey(pathkeys))
3639 {
3641 continue;
3642 }
3643
3644 /*
3645 * When not set yet, take the pathkeys from the first unprocessed
3646 * aggregate.
3647 */
3648 if (currpathkeys == NIL)
3649 {
3650 currpathkeys = pathkeys;
3651
3652 /* include the GROUP BY pathkeys, if they exist */
3653 if (grouppathkeys != NIL)
3655 currpathkeys);
3656
3657 /* record that we found pathkeys for this aggregate */
3659 }
3660 else
3661 {
3662 /* now look for a stronger set of matching pathkeys */
3663
3664 /* include the GROUP BY pathkeys, if they exist */
3665 if (grouppathkeys != NIL)
3667 pathkeys);
3668
3669 /* are 'pathkeys' compatible or better than 'currpathkeys'? */
3670 switch (compare_pathkeys(currpathkeys, pathkeys))
3671 {
3672 case PATHKEYS_BETTER2:
3673 /* 'pathkeys' are stronger, use these ones instead */
3674 currpathkeys = pathkeys;
3676
3677 case PATHKEYS_BETTER1:
3678 /* 'pathkeys' are less strict */
3680
3681 case PATHKEYS_EQUAL:
3682 /* mark this aggregate as covered by 'currpathkeys' */
3684 break;
3685
3686 case PATHKEYS_DIFFERENT:
3687 break;
3688 }
3689 }
3690 }
3691
3692 /* remove the aggregates that we've just processed */
3694
3695 /*
3696 * If this pass included more aggregates than the previous best then
3697 * use these ones as the best set.
3698 */
3700 {
3703 }
3704 }
3705
3706 /*
3707 * If we found any ordered aggregates, update root->group_pathkeys to add
3708 * the best set of aggregate pathkeys. Note that bestpathkeys includes
3709 * the original GROUP BY pathkeys already.
3710 */
3711 if (bestpathkeys != NIL)
3712 root->group_pathkeys = bestpathkeys;
3713
3714 /*
3715 * Now that we've found the best set of aggregates we can set the
3716 * presorted flag to indicate to the executor that it needn't bother
3717 * performing a sort for these Aggrefs. We're able to do this now as
3718 * there's no chance of a Hash Aggregate plan as create_grouping_paths
3719 * will not mark the GROUP BY as GROUPING_CAN_USE_HASH due to the presence
3720 * of ordered aggregates.
3721 */
3722 i = -1;
3723 while ((i = bms_next_member(bestaggs, i)) >= 0)
3724 {
3725 AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3726
3727 foreach(lc, agginfo->aggrefs)
3728 {
3729 Aggref *aggref = lfirst_node(Aggref, lc);
3730
3731 aggref->aggpresorted = true;
3732 }
3733 }
3734}
3735
3736/*
3737 * Compute query_pathkeys and other pathkeys during plan generation
3738 */
3739static void
3741{
3742 Query *parse = root->parse;
3744 List *tlist = root->processed_tlist;
3745 List *activeWindows = qp_extra->activeWindows;
3746
3747 /*
3748 * Calculate pathkeys that represent grouping/ordering and/or ordered
3749 * aggregate requirements.
3750 */
3751 if (qp_extra->gset_data)
3752 {
3753 /*
3754 * With grouping sets, just use the first RollupData's groupClause. We
3755 * don't make any effort to optimize grouping clauses when there are
3756 * grouping sets, nor can we combine aggregate ordering keys with
3757 * grouping.
3758 */
3759 List *rollups = qp_extra->gset_data->rollups;
3760 List *groupClause = (rollups ? linitial_node(RollupData, rollups)->groupClause : NIL);
3761
3762 if (grouping_is_sortable(groupClause))
3763 {
3764 bool sortable;
3765
3766 /*
3767 * The groupClause is logically below the grouping step. So if
3768 * there is an RTE entry for the grouping step, we need to remove
3769 * its RT index from the sort expressions before we make PathKeys
3770 * for them.
3771 */
3772 root->group_pathkeys =
3774 &groupClause,
3775 tlist,
3776 false,
3777 parse->hasGroupRTE,
3778 &sortable,
3779 false);
3781 root->num_groupby_pathkeys = list_length(root->group_pathkeys);
3782 }
3783 else
3784 {
3785 root->group_pathkeys = NIL;
3786 root->num_groupby_pathkeys = 0;
3787 }
3788 }
3789 else if (parse->groupClause || root->numOrderedAggs > 0)
3790 {
3791 /*
3792 * With a plain GROUP BY list, we can remove any grouping items that
3793 * are proven redundant by EquivalenceClass processing. For example,
3794 * we can remove y given "WHERE x = y GROUP BY x, y". These aren't
3795 * especially common cases, but they're nearly free to detect. Note
3796 * that we remove redundant items from processed_groupClause but not
3797 * the original parse->groupClause.
3798 */
3799 bool sortable;
3800
3801 /*
3802 * Convert group clauses into pathkeys. Set the ec_sortref field of
3803 * EquivalenceClass'es if it's not set yet.
3804 */
3805 root->group_pathkeys =
3807 &root->processed_groupClause,
3808 tlist,
3809 true,
3810 false,
3811 &sortable,
3812 true);
3813 if (!sortable)
3814 {
3815 /* Can't sort; no point in considering aggregate ordering either */
3816 root->group_pathkeys = NIL;
3817 root->num_groupby_pathkeys = 0;
3818 }
3819 else
3820 {
3821 root->num_groupby_pathkeys = list_length(root->group_pathkeys);
3822 /* If we have ordered aggs, consider adding onto group_pathkeys */
3823 if (root->numOrderedAggs > 0)
3825 }
3826 }
3827 else
3828 {
3829 root->group_pathkeys = NIL;
3830 root->num_groupby_pathkeys = 0;
3831 }
3832
3833 /* We consider only the first (bottom) window in pathkeys logic */
3834 if (activeWindows != NIL)
3835 {
3836 WindowClause *wc = linitial_node(WindowClause, activeWindows);
3837
3838 root->window_pathkeys = make_pathkeys_for_window(root,
3839 wc,
3840 tlist);
3841 }
3842 else
3843 root->window_pathkeys = NIL;
3844
3845 /*
3846 * As with GROUP BY, we can discard any DISTINCT items that are proven
3847 * redundant by EquivalenceClass processing. The non-redundant list is
3848 * kept in root->processed_distinctClause, leaving the original
3849 * parse->distinctClause alone.
3850 */
3851 if (parse->distinctClause)
3852 {
3853 bool sortable;
3854
3855 /* Make a copy since pathkey processing can modify the list */
3856 root->processed_distinctClause = list_copy(parse->distinctClause);
3857 root->distinct_pathkeys =
3859 &root->processed_distinctClause,
3860 tlist,
3861 true,
3862 false,
3863 &sortable,
3864 false);
3865 if (!sortable)
3866 root->distinct_pathkeys = NIL;
3867 }
3868 else
3869 root->distinct_pathkeys = NIL;
3870
3871 root->sort_pathkeys =
3873 parse->sortClause,
3874 tlist);
3875
3876 /* setting setop_pathkeys might be useful to the union planner */
3877 if (qp_extra->setop != NULL)
3878 {
3879 List *groupClauses;
3880 bool sortable;
3881
3882 groupClauses = generate_setop_child_grouplist(qp_extra->setop, tlist);
3883
3884 root->setop_pathkeys =
3886 &groupClauses,
3887 tlist,
3888 false,
3889 false,
3890 &sortable,
3891 false);
3892 if (!sortable)
3893 root->setop_pathkeys = NIL;
3894 }
3895 else
3896 root->setop_pathkeys = NIL;
3897
3898 /*
3899 * Figure out whether we want a sorted result from query_planner.
3900 *
3901 * If we have a sortable GROUP BY clause, then we want a result sorted
3902 * properly for grouping. Otherwise, if we have window functions to
3903 * evaluate, we try to sort for the first window. Otherwise, if there's a
3904 * sortable DISTINCT clause that's more rigorous than the ORDER BY clause,
3905 * we try to produce output that's sufficiently well sorted for the
3906 * DISTINCT. Otherwise, if there is an ORDER BY clause, we want to sort
3907 * by the ORDER BY clause. Otherwise, if we're a subquery being planned
3908 * for a set operation which can benefit from presorted results and have a
3909 * sortable targetlist, we want to sort by the target list.
3910 *
3911 * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a superset
3912 * of GROUP BY, it would be tempting to request sort by ORDER BY --- but
3913 * that might just leave us failing to exploit an available sort order at
3914 * all. Needs more thought. The choice for DISTINCT versus ORDER BY is
3915 * much easier, since we know that the parser ensured that one is a
3916 * superset of the other.
3917 */
3918 if (root->group_pathkeys)
3919 root->query_pathkeys = root->group_pathkeys;
3920 else if (root->window_pathkeys)
3921 root->query_pathkeys = root->window_pathkeys;
3922 else if (list_length(root->distinct_pathkeys) >
3923 list_length(root->sort_pathkeys))
3924 root->query_pathkeys = root->distinct_pathkeys;
3925 else if (root->sort_pathkeys)
3926 root->query_pathkeys = root->sort_pathkeys;
3927 else if (root->setop_pathkeys != NIL)
3928 root->query_pathkeys = root->setop_pathkeys;
3929 else
3930 root->query_pathkeys = NIL;
3931}
3932
3933/*
3934 * Estimate number of groups produced by grouping clauses (1 if not grouping)
3935 *
3936 * path_rows: number of output rows from scan/join step
3937 * gd: grouping sets data including list of grouping sets and their clauses
3938 * target_list: target list containing group clause references
3939 *
3940 * If doing grouping sets, we also annotate the gsets data with the estimates
3941 * for each set and each individual rollup list, with a view to later
3942 * determining whether some combination of them could be hashed instead.
3943 */
3944static double
3946 double path_rows,
3949{
3950 Query *parse = root->parse;
3951 double dNumGroups;
3952
3953 if (parse->groupClause)
3954 {
3956
3957 if (parse->groupingSets)
3958 {
3959 /* Add up the estimates for each grouping set */
3960 ListCell *lc;
3961
3962 Assert(gd); /* keep Coverity happy */
3963
3964 dNumGroups = 0;
3965
3966 foreach(lc, gd->rollups)
3967 {
3969 ListCell *lc2;
3970 ListCell *lc3;
3971
3973 target_list);
3974
3975 rollup->numGroups = 0.0;
3976
3977 forboth(lc2, rollup->gsets, lc3, rollup->gsets_data)
3978 {
3979 List *gset = (List *) lfirst(lc2);
3981 double numGroups = estimate_num_groups(root,
3982 groupExprs,
3983 path_rows,
3984 &gset,
3985 NULL);
3986
3987 gs->numGroups = numGroups;
3988 rollup->numGroups += numGroups;
3989 }
3990
3991 dNumGroups += rollup->numGroups;
3992 }
3993
3994 if (gd->hash_sets_idx)
3995 {
3996 ListCell *lc2;
3997
3998 gd->dNumHashGroups = 0;
3999
4001 target_list);
4002
4003 forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
4004 {
4005 List *gset = (List *) lfirst(lc);
4007 double numGroups = estimate_num_groups(root,
4008 groupExprs,
4009 path_rows,
4010 &gset,
4011 NULL);
4012
4013 gs->numGroups = numGroups;
4014 gd->dNumHashGroups += numGroups;
4015 }
4016
4017 dNumGroups += gd->dNumHashGroups;
4018 }
4019 }
4020 else
4021 {
4022 /* Plain GROUP BY -- estimate based on optimized groupClause */
4023 groupExprs = get_sortgrouplist_exprs(root->processed_groupClause,
4024 target_list);
4025
4027 NULL, NULL);
4028 }
4029 }
4030 else if (parse->groupingSets)
4031 {
4032 /* Empty grouping sets ... one result row for each one */
4033 dNumGroups = list_length(parse->groupingSets);
4034 }
4035 else if (parse->hasAggs || root->hasHavingQual)
4036 {
4037 /* Plain aggregation, one result row */
4038 dNumGroups = 1;
4039 }
4040 else
4041 {
4042 /* Not grouping */
4043 dNumGroups = 1;
4044 }
4045
4046 return dNumGroups;
4047}
4048
4049/*
4050 * create_grouping_paths
4051 *
4052 * Build a new upperrel containing Paths for grouping and/or aggregation.
4053 * Along the way, we also build an upperrel for Paths which are partially
4054 * grouped and/or aggregated. A partially grouped and/or aggregated path
4055 * needs a FinalizeAggregate node to complete the aggregation. Currently,
4056 * the only partially grouped paths we build are also partial paths; that
4057 * is, they need a Gather and then a FinalizeAggregate.
4058 *
4059 * input_rel: contains the source-data Paths
4060 * target: the pathtarget for the result Paths to compute
4061 * gd: grouping sets data including list of grouping sets and their clauses
4062 *
4063 * Note: all Paths in input_rel are expected to return the target computed
4064 * by make_group_input_target.
4065 */
4066static RelOptInfo *
4069 PathTarget *target,
4070 bool target_parallel_safe,
4072{
4073 Query *parse = root->parse;
4074 RelOptInfo *grouped_rel;
4077
4078 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
4080
4081 /*
4082 * Create grouping relation to hold fully aggregated grouping and/or
4083 * aggregation paths.
4084 */
4085 grouped_rel = make_grouping_rel(root, input_rel, target,
4086 target_parallel_safe, parse->havingQual);
4087
4088 /*
4089 * Create either paths for a degenerate grouping or paths for ordinary
4090 * grouping, as appropriate.
4091 */
4094 else
4095 {
4096 int flags = 0;
4097 GroupPathExtraData extra;
4098
4099 /*
4100 * Determine whether it's possible to perform sort-based
4101 * implementations of grouping. (Note that if processed_groupClause
4102 * is empty, grouping_is_sortable() is trivially true, and all the
4103 * pathkeys_contained_in() tests will succeed too, so that we'll
4104 * consider every surviving input path.)
4105 *
4106 * If we have grouping sets, we might be able to sort some but not all
4107 * of them; in this case, we need can_sort to be true as long as we
4108 * must consider any sorted-input plan.
4109 */
4110 if ((gd && gd->rollups != NIL)
4111 || grouping_is_sortable(root->processed_groupClause))
4112 flags |= GROUPING_CAN_USE_SORT;
4113
4114 /*
4115 * Determine whether we should consider hash-based implementations of
4116 * grouping.
4117 *
4118 * Hashed aggregation only applies if we're grouping. If we have
4119 * grouping sets, some groups might be hashable but others not; in
4120 * this case we set can_hash true as long as there is nothing globally
4121 * preventing us from hashing (and we should therefore consider plans
4122 * with hashes).
4123 *
4124 * Executor doesn't support hashed aggregation with DISTINCT or ORDER
4125 * BY aggregates. (Doing so would imply storing *all* the input
4126 * values in the hash table, and/or running many sorts in parallel,
4127 * either of which seems like a certain loser.) We similarly don't
4128 * support ordered-set aggregates in hashed aggregation, but that case
4129 * is also included in the numOrderedAggs count.
4130 *
4131 * Note: grouping_is_hashable() is much more expensive to check than
4132 * the other gating conditions, so we want to do it last.
4133 */
4134 if ((parse->groupClause != NIL &&
4135 root->numOrderedAggs == 0 &&
4136 (gd ? gd->any_hashable : grouping_is_hashable(root->processed_groupClause))))
4137 flags |= GROUPING_CAN_USE_HASH;
4138
4139 /*
4140 * Determine whether partial aggregation is possible.
4141 */
4142 if (can_partial_agg(root))
4143 flags |= GROUPING_CAN_PARTIAL_AGG;
4144
4145 extra.flags = flags;
4146 extra.target_parallel_safe = target_parallel_safe;
4147 extra.havingQual = parse->havingQual;
4148 extra.targetList = parse->targetList;
4149 extra.partial_costs_set = false;
4150
4151 /*
4152 * Determine whether partitionwise aggregation is in theory possible.
4153 * It can be disabled by the user, and for now, we don't try to
4154 * support grouping sets. create_ordinary_grouping_paths() will check
4155 * additional conditions, such as whether input_rel is partitioned.
4156 */
4157 if (enable_partitionwise_aggregate && !parse->groupingSets)
4159 else
4161
4163 &agg_costs, gd, &extra,
4165 }
4166
4167 set_cheapest(grouped_rel);
4168 return grouped_rel;
4169}
4170
4171/*
4172 * make_grouping_rel
4173 *
4174 * Create a new grouping rel and set basic properties.
4175 *
4176 * input_rel represents the underlying scan/join relation.
4177 * target is the output expected from the grouping relation.
4178 */
4179static RelOptInfo *
4181 PathTarget *target, bool target_parallel_safe,
4182 Node *havingQual)
4183{
4184 RelOptInfo *grouped_rel;
4185
4187 {
4189 input_rel->relids);
4190 grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
4191 }
4192 else
4193 {
4194 /*
4195 * By tradition, the relids set for the main grouping relation is
4196 * NULL. (This could be changed, but might require adjustments
4197 * elsewhere.)
4198 */
4200 }
4201
4202 /* Set target. */
4203 grouped_rel->reltarget = target;
4204
4205 /*
4206 * If the input relation is not parallel-safe, then the grouped relation
4207 * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4208 * target list and HAVING quals are parallel-safe.
4209 */
4210 if (input_rel->consider_parallel && target_parallel_safe &&
4211 is_parallel_safe(root, havingQual))
4212 grouped_rel->consider_parallel = true;
4213
4214 /* Assume that the same path generation strategies are allowed */
4215 grouped_rel->pgs_mask = input_rel->pgs_mask;
4216
4217 /*
4218 * If the input rel belongs to a single FDW, so does the grouped rel.
4219 */
4220 grouped_rel->serverid = input_rel->serverid;
4221 grouped_rel->userid = input_rel->userid;
4222 grouped_rel->useridiscurrent = input_rel->useridiscurrent;
4223 grouped_rel->fdwroutine = input_rel->fdwroutine;
4224
4225 return grouped_rel;
4226}
4227
4228/*
4229 * is_degenerate_grouping
4230 *
4231 * A degenerate grouping is one in which the query has a HAVING qual and/or
4232 * grouping sets, but no aggregates and no GROUP BY (which implies that the
4233 * grouping sets are all empty).
4234 */
4235static bool
4237{
4238 Query *parse = root->parse;
4239
4240 return (root->hasHavingQual || parse->groupingSets) &&
4241 !parse->hasAggs && parse->groupClause == NIL;
4242}
4243
4244/*
4245 * create_degenerate_grouping_paths
4246 *
4247 * When the grouping is degenerate (see is_degenerate_grouping), we are
4248 * supposed to emit either zero or one row for each grouping set depending on
4249 * whether HAVING succeeds. Furthermore, there cannot be any variables in
4250 * either HAVING or the targetlist, so we actually do not need the FROM table
4251 * at all! We can just throw away the plan-so-far and generate a Result node.
4252 * This is a sufficiently unusual corner case that it's not worth contorting
4253 * the structure of this module to avoid having to generate the earlier paths
4254 * in the first place.
4255 */
4256static void
4258 RelOptInfo *grouped_rel)
4259{
4260 Query *parse = root->parse;
4261 int nrows;
4262 Path *path;
4263
4264 nrows = list_length(parse->groupingSets);
4265 if (nrows > 1)
4266 {
4267 /*
4268 * Doesn't seem worthwhile writing code to cons up a generate_series
4269 * or a values scan to emit multiple rows. Instead just make N clones
4270 * and append them. (With a volatile HAVING clause, this means you
4271 * might get between 0 and N output rows. Offhand I think that's
4272 * desired.)
4273 */
4274 AppendPathInput append = {0};
4275
4276 while (--nrows >= 0)
4277 {
4278 path = (Path *)
4279 create_group_result_path(root, grouped_rel,
4280 grouped_rel->reltarget,
4281 (List *) parse->havingQual);
4282 append.subpaths = lappend(append.subpaths, path);
4283 }
4284 path = (Path *)
4286 grouped_rel,
4287 append,
4288 NIL,
4289 NULL,
4290 0,
4291 false,
4292 -1);
4293 }
4294 else
4295 {
4296 /* No grouping sets, or just one, so one output row */
4297 path = (Path *)
4298 create_group_result_path(root, grouped_rel,
4299 grouped_rel->reltarget,
4300 (List *) parse->havingQual);
4301 }
4302
4303 add_path(grouped_rel, path);
4304}
4305
4306/*
4307 * create_ordinary_grouping_paths
4308 *
4309 * Create grouping paths for the ordinary (that is, non-degenerate) case.
4310 *
4311 * We need to consider sorted and hashed aggregation in the same function,
4312 * because otherwise (1) it would be harder to throw an appropriate error
4313 * message if neither way works, and (2) we should not allow hashtable size
4314 * considerations to dissuade us from using hashing if sorting is not possible.
4315 *
4316 * *partially_grouped_rel_p will be set to the partially grouped rel which this
4317 * function creates, or to NULL if it doesn't create one.
4318 */
4319static void
4321 RelOptInfo *grouped_rel,
4324 GroupPathExtraData *extra,
4326{
4329
4330 /*
4331 * If this is the topmost grouping relation or if the parent relation is
4332 * doing some form of partitionwise aggregation, then we may be able to do
4333 * it at this level also. However, if the input relation is not
4334 * partitioned, partitionwise aggregate is impossible.
4335 */
4336 if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
4338 {
4339 /*
4340 * If this is the topmost relation or if the parent relation is doing
4341 * full partitionwise aggregation, then we can do full partitionwise
4342 * aggregation provided that the GROUP BY clause contains all of the
4343 * partitioning columns at this level and the collation used by GROUP
4344 * BY matches the partitioning collation. Otherwise, we can do at
4345 * most partial partitionwise aggregation. But if partial aggregation
4346 * is not supported in general then we can't use it for partitionwise
4347 * aggregation either.
4348 *
4349 * Check parse->groupClause not processed_groupClause, because it's
4350 * okay if some of the partitioning columns were proved redundant.
4351 */
4352 if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
4354 root->parse->groupClause))
4356 else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4358 else
4360 }
4361
4362 /*
4363 * Before generating paths for grouped_rel, we first generate any possible
4364 * partially grouped paths; that way, later code can easily consider both
4365 * parallel and non-parallel approaches to grouping.
4366 */
4367 if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4368 {
4369 bool force_rel_creation;
4370
4371 /*
4372 * If we're doing partitionwise aggregation at this level, force
4373 * creation of a partially_grouped_rel so we can add partitionwise
4374 * paths to it.
4375 */
4377
4380 grouped_rel,
4381 input_rel,
4382 gd,
4383 extra,
4385 }
4386
4387 /* Set out parameter. */
4389
4390 /* Apply partitionwise aggregation technique, if possible. */
4391 if (patype != PARTITIONWISE_AGGREGATE_NONE)
4394 gd, patype, extra);
4395
4396 /* If we are doing partial aggregation only, return. */
4398 {
4400
4401 if (partially_grouped_rel->pathlist)
4403
4404 return;
4405 }
4406
4407 /* Gather any partially grouped partial paths. */
4408 if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
4410
4411 /* Now choose the best path(s) for partially_grouped_rel. */
4414
4415 /* Build final grouping paths */
4418 extra);
4419
4420 /* Give a helpful error if we failed to find any implementation */
4421 if (grouped_rel->pathlist == NIL)
4422 ereport(ERROR,
4424 errmsg("could not implement GROUP BY"),
4425 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4426
4427 /*
4428 * If there is an FDW that's responsible for all baserels of the query,
4429 * let it consider adding ForeignPaths.
4430 */
4431 if (grouped_rel->fdwroutine &&
4432 grouped_rel->fdwroutine->GetForeignUpperPaths)
4433 grouped_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG,
4434 input_rel, grouped_rel,
4435 extra);
4436
4437 /* Let extensions possibly add some more paths */
4439 (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4440 input_rel, grouped_rel,
4441 extra);
4442}
4443
4444/*
4445 * For a given input path, consider the possible ways of doing grouping sets on
4446 * it, by combinations of hashing and sorting. This can be called multiple
4447 * times, so it's important that it not scribble on input. No result is
4448 * returned, but any generated paths are added to grouped_rel.
4449 */
4450static void
4452 RelOptInfo *grouped_rel,
4453 Path *path,
4454 bool is_sorted,
4455 bool can_hash,
4458 double dNumGroups)
4459{
4460 Query *parse = root->parse;
4461 Size hash_mem_limit = get_hash_memory_limit();
4462
4463 /*
4464 * If we're not being offered sorted input, then only consider plans that
4465 * can be done entirely by hashing.
4466 *
4467 * We can hash everything if it looks like it'll fit in hash_mem. But if
4468 * the input is actually sorted despite not being advertised as such, we
4469 * prefer to make use of that in order to use less memory.
4470 *
4471 * If none of the grouping sets are sortable, then ignore the hash_mem
4472 * limit and generate a path anyway, since otherwise we'll just fail.
4473 */
4474 if (!is_sorted)
4475 {
4476 List *new_rollups = NIL;
4478 List *sets_data;
4480 List *empty_sets = NIL;
4481 ListCell *lc;
4482 ListCell *l_start = list_head(gd->rollups);
4484 double hashsize;
4485 double exclude_groups = 0.0;
4486
4488
4489 /*
4490 * If the input is coincidentally sorted usefully (which can happen
4491 * even if is_sorted is false, since that only means that our caller
4492 * has set up the sorting for us), then save some hashtable space by
4493 * making use of that. But we need to watch out for degenerate cases:
4494 *
4495 * 1) If there are any empty grouping sets, then group_pathkeys might
4496 * be NIL if all non-empty grouping sets are unsortable. In this case,
4497 * there will be a rollup containing only empty groups, and the
4498 * pathkeys_contained_in test is vacuously true; this is ok.
4499 *
4500 * XXX: the above relies on the fact that group_pathkeys is generated
4501 * from the first rollup. If we add the ability to consider multiple
4502 * sort orders for grouping input, this assumption might fail.
4503 *
4504 * 2) If there are no empty sets and only unsortable sets, then the
4505 * rollups list will be empty (and thus l_start == NULL), and
4506 * group_pathkeys will be NIL; we must ensure that the vacuously-true
4507 * pathkeys_contained_in test doesn't cause us to crash.
4508 */
4509 if (l_start != NULL &&
4510 pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
4511 {
4513 exclude_groups = unhashed_rollup->numGroups;
4514 l_start = lnext(gd->rollups, l_start);
4515 }
4516
4518 path,
4519 agg_costs,
4521
4522 /*
4523 * gd->rollups is empty if we have only unsortable columns to work
4524 * with. Override hash_mem in that case; otherwise, we'll rely on the
4525 * sorted-input case to generate usable mixed paths.
4526 */
4527 if (hashsize > hash_mem_limit && gd->rollups)
4528 return; /* nope, won't fit */
4529
4530 /*
4531 * We need to burst the existing rollups list into individual grouping
4532 * sets and recompute a groupClause for each set.
4533 */
4534 sets_data = list_copy(gd->unsortable_sets);
4535
4536 for_each_cell(lc, gd->rollups, l_start)
4537 {
4539
4540 /*
4541 * If we find an unhashable rollup that's not been skipped by the
4542 * "actually sorted" check above, we can't cope; we'd need sorted
4543 * input (with a different sort order) but we can't get that here.
4544 * So bail out; we'll get a valid path from the is_sorted case
4545 * instead.
4546 *
4547 * The mere presence of empty grouping sets doesn't make a rollup
4548 * unhashable (see preprocess_grouping_sets), we handle those
4549 * specially below.
4550 */
4551 if (!rollup->hashable)
4552 return;
4553
4554 sets_data = list_concat(sets_data, rollup->gsets_data);
4555 }
4556 foreach(lc, sets_data)
4557 {
4559 List *gset = gs->set;
4561
4562 if (gset == NIL)
4563 {
4564 /* Empty grouping sets can't be hashed. */
4567 }
4568 else
4569 {
4571
4572 rollup->groupClause = preprocess_groupclause(root, gset);
4573 rollup->gsets_data = list_make1(gs);
4574 rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4575 rollup->gsets_data,
4576 gd->tleref_to_colnum_map);
4577 rollup->numGroups = gs->numGroups;
4578 rollup->hashable = true;
4579 rollup->is_hashed = true;
4581 }
4582 }
4583
4584 /*
4585 * If we didn't find anything nonempty to hash, then bail. We'll
4586 * generate a path from the is_sorted case.
4587 */
4588 if (new_rollups == NIL)
4589 return;
4590
4591 /*
4592 * If there were empty grouping sets they should have been in the
4593 * first rollup.
4594 */
4596
4597 if (unhashed_rollup)
4598 {
4600 strat = AGG_MIXED;
4601 }
4602 else if (empty_sets)
4603 {
4605
4606 rollup->groupClause = NIL;
4607 rollup->gsets_data = empty_sets_data;
4608 rollup->gsets = empty_sets;
4609 rollup->numGroups = list_length(empty_sets);
4610 rollup->hashable = false;
4611 rollup->is_hashed = false;
4613 strat = AGG_MIXED;
4614 }
4615
4616 add_path(grouped_rel, (Path *)
4618 grouped_rel,
4619 path,
4620 (List *) parse->havingQual,
4621 strat,
4623 agg_costs));
4624 return;
4625 }
4626
4627 /*
4628 * If we have sorted input but nothing we can do with it, bail.
4629 */
4630 if (gd->rollups == NIL)
4631 return;
4632
4633 /*
4634 * Given sorted input, we try and make two paths: one sorted and one mixed
4635 * sort/hash. (We need to try both because hashagg might be disabled, or
4636 * some columns might not be sortable.)
4637 *
4638 * can_hash is passed in as false if some obstacle elsewhere (such as
4639 * ordered aggs) means that we shouldn't consider hashing at all.
4640 */
4641 if (can_hash && gd->any_hashable)
4642 {
4643 List *rollups = NIL;
4644 List *hash_sets = list_copy(gd->unsortable_sets);
4645 double availspace = hash_mem_limit;
4646 ListCell *lc;
4647
4648 /*
4649 * Account first for space needed for groups we can't sort at all.
4650 */
4652 path,
4653 agg_costs,
4654 gd->dNumHashGroups);
4655
4656 if (availspace > 0 && list_length(gd->rollups) > 1)
4657 {
4658 double scale;
4659 int num_rollups = list_length(gd->rollups);
4660 int k_capacity;
4661 int *k_weights = palloc(num_rollups * sizeof(int));
4663 int i;
4664
4665 /*
4666 * We treat this as a knapsack problem: the knapsack capacity
4667 * represents hash_mem, the item weights are the estimated memory
4668 * usage of the hashtables needed to implement a single rollup,
4669 * and we really ought to use the cost saving as the item value;
4670 * however, currently the costs assigned to sort nodes don't
4671 * reflect the comparison costs well, and so we treat all items as
4672 * of equal value (each rollup we hash instead saves us one sort).
4673 *
4674 * To use the discrete knapsack, we need to scale the values to a
4675 * reasonably small bounded range. We choose to allow a 5% error
4676 * margin; we have no more than 4096 rollups in the worst possible
4677 * case, which with a 5% error margin will require a bit over 42MB
4678 * of workspace. (Anyone wanting to plan queries that complex had
4679 * better have the memory for it. In more reasonable cases, with
4680 * no more than a couple of dozen rollups, the memory usage will
4681 * be negligible.)
4682 *
4683 * k_capacity is naturally bounded, but we clamp the values for
4684 * scale and weight (below) to avoid overflows or underflows (or
4685 * uselessly trying to use a scale factor less than 1 byte).
4686 */
4687 scale = Max(availspace / (20.0 * num_rollups), 1.0);
4689
4690 /*
4691 * We leave the first rollup out of consideration since it's the
4692 * one that matches the input sort order. We assign indexes "i"
4693 * to only those entries considered for hashing; the second loop,
4694 * below, must use the same condition.
4695 */
4696 i = 0;
4697 for_each_from(lc, gd->rollups, 1)
4698 {
4700
4701 if (rollup->hashable)
4702 {
4704 path,
4705 agg_costs,
4706 rollup->numGroups);
4707
4708 /*
4709 * If sz is enormous, but hash_mem (and hence scale) is
4710 * small, avoid integer overflow here.
4711 */
4712 k_weights[i] = (int) Min(floor(sz / scale),
4713 k_capacity + 1.0);
4714 ++i;
4715 }
4716 }
4717
4718 /*
4719 * Apply knapsack algorithm; compute the set of items which
4720 * maximizes the value stored (in this case the number of sorts
4721 * saved) while keeping the total size (approximately) within
4722 * capacity.
4723 */
4724 if (i > 0)
4726
4728 {
4729 rollups = list_make1(linitial(gd->rollups));
4730
4731 i = 0;
4732 for_each_from(lc, gd->rollups, 1)
4733 {
4735
4736 if (rollup->hashable)
4737 {
4740 rollup->gsets_data);
4741 else
4742 rollups = lappend(rollups, rollup);
4743 ++i;
4744 }
4745 else
4746 rollups = lappend(rollups, rollup);
4747 }
4748 }
4749 }
4750
4751 if (!rollups && hash_sets)
4752 rollups = list_copy(gd->rollups);
4753
4754 foreach(lc, hash_sets)
4755 {
4758
4759 Assert(gs->set != NIL);
4760
4761 rollup->groupClause = preprocess_groupclause(root, gs->set);
4762 rollup->gsets_data = list_make1(gs);
4763 rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4764 rollup->gsets_data,
4765 gd->tleref_to_colnum_map);
4766 rollup->numGroups = gs->numGroups;
4767 rollup->hashable = true;
4768 rollup->is_hashed = true;
4769 rollups = lcons(rollup, rollups);
4770 }
4771
4772 if (rollups)
4773 {
4774 add_path(grouped_rel, (Path *)
4776 grouped_rel,
4777 path,
4778 (List *) parse->havingQual,
4779 AGG_MIXED,
4780 rollups,
4781 agg_costs));
4782 }
4783 }
4784
4785 /*
4786 * Now try the simple sorted case.
4787 */
4788 if (!gd->unsortable_sets)
4789 add_path(grouped_rel, (Path *)
4791 grouped_rel,
4792 path,
4793 (List *) parse->havingQual,
4794 AGG_SORTED,
4795 gd->rollups,
4796 agg_costs));
4797}
4798
4799/*
4800 * create_window_paths
4801 *
4802 * Build a new upperrel containing Paths for window-function evaluation.
4803 *
4804 * input_rel: contains the source-data Paths
4805 * input_target: result of make_window_input_target
4806 * output_target: what the topmost WindowAggPath should return
4807 * wflists: result of find_window_functions
4808 * activeWindows: result of select_active_windows
4809 *
4810 * Note: all Paths in input_rel are expected to return input_target.
4811 */
4812static RelOptInfo *
4819 List *activeWindows)
4820{
4822 ListCell *lc;
4823
4824 /* For now, do all work in the (WINDOW, NULL) upperrel */
4826
4827 /*
4828 * If the input relation is not parallel-safe, then the window relation
4829 * can't be parallel-safe, either. Otherwise, we need to examine the
4830 * target list and active windows for non-parallel-safe constructs.
4831 */
4832 if (input_rel->consider_parallel && output_target_parallel_safe &&
4833 is_parallel_safe(root, (Node *) activeWindows))
4834 window_rel->consider_parallel = true;
4835
4836 /*
4837 * If the input rel belongs to a single FDW, so does the window rel.
4838 */
4839 window_rel->serverid = input_rel->serverid;
4840 window_rel->userid = input_rel->userid;
4841 window_rel->useridiscurrent = input_rel->useridiscurrent;
4842 window_rel->fdwroutine = input_rel->fdwroutine;
4843
4844 /*
4845 * Consider computing window functions starting from the existing
4846 * cheapest-total path (which will likely require a sort) as well as any
4847 * existing paths that satisfy or partially satisfy root->window_pathkeys.
4848 */
4849 foreach(lc, input_rel->pathlist)
4850 {
4851 Path *path = (Path *) lfirst(lc);
4852 int presorted_keys;
4853
4854 if (path == input_rel->cheapest_total_path ||
4855 pathkeys_count_contained_in(root->window_pathkeys, path->pathkeys,
4856 &presorted_keys) ||
4857 presorted_keys > 0)
4859 window_rel,
4860 path,
4863 wflists,
4864 activeWindows);
4865 }
4866
4867 /*
4868 * If there is an FDW that's responsible for all baserels of the query,
4869 * let it consider adding ForeignPaths.
4870 */
4871 if (window_rel->fdwroutine &&
4872 window_rel->fdwroutine->GetForeignUpperPaths)
4873 window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4875 NULL);
4876
4877 /* Let extensions possibly add some more paths */
4879 (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4881
4882 /* Now choose the best path(s) */
4884
4885 return window_rel;
4886}
4887
4888/*
4889 * Stack window-function implementation steps atop the given Path, and
4890 * add the result to window_rel.
4891 *
4892 * window_rel: upperrel to contain result
4893 * path: input Path to use (must return input_target)
4894 * input_target: result of make_window_input_target
4895 * output_target: what the topmost WindowAggPath should return
4896 * wflists: result of find_window_functions
4897 * activeWindows: result of select_active_windows
4898 */
4899static void
4902 Path *path,
4906 List *activeWindows)
4907{
4909 ListCell *l;
4910 List *topqual = NIL;
4911
4912 /*
4913 * Since each window clause could require a different sort order, we stack
4914 * up a WindowAgg node for each clause, with sort steps between them as
4915 * needed. (We assume that select_active_windows chose a good order for
4916 * executing the clauses in.)
4917 *
4918 * input_target should contain all Vars and Aggs needed for the result.
4919 * (In some cases we wouldn't need to propagate all of these all the way
4920 * to the top, since they might only be needed as inputs to WindowFuncs.
4921 * It's probably not worth trying to optimize that though.) It must also
4922 * contain all window partitioning and sorting expressions, to ensure
4923 * they're computed only once at the bottom of the stack (that's critical
4924 * for volatile functions). As we climb up the stack, we'll add outputs
4925 * for the WindowFuncs computed at each level.
4926 */
4928
4929 foreach(l, activeWindows)
4930 {
4932 List *window_pathkeys;
4933 List *runcondition = NIL;
4934 int presorted_keys;
4935 bool is_sorted;
4936 bool topwindow;
4937 ListCell *lc2;
4938
4939 window_pathkeys = make_pathkeys_for_window(root,
4940 wc,
4941 root->processed_tlist);
4942
4943 is_sorted = pathkeys_count_contained_in(window_pathkeys,
4944 path->pathkeys,
4945 &presorted_keys);
4946
4947 /* Sort if necessary */
4948 if (!is_sorted)
4949 {
4950 /*
4951 * No presorted keys or incremental sort disabled, just perform a
4952 * complete sort.
4953 */
4954 if (presorted_keys == 0 || !enable_incremental_sort)
4956 path,
4957 window_pathkeys,
4958 -1.0);
4959 else
4960 {
4961 /*
4962 * Since we have presorted keys and incremental sort is
4963 * enabled, just use incremental sort.
4964 */
4966 window_rel,
4967 path,
4968 window_pathkeys,
4969 presorted_keys,
4970 -1.0);
4971 }
4972 }
4973
4974 if (lnext(activeWindows, l))
4975 {
4976 /*
4977 * Add the current WindowFuncs to the output target for this
4978 * intermediate WindowAggPath. We must copy window_target to
4979 * avoid changing the previous path's target.
4980 *
4981 * Note: a WindowFunc adds nothing to the target's eval costs; but
4982 * we do need to account for the increase in tlist width.
4983 */
4985
4987 foreach(lc2, wflists->windowFuncs[wc->winref])
4988 {
4990
4992 tuple_width += get_typavgwidth(wfunc->wintype, -1);
4993 }
4995 }
4996 else
4997 {
4998 /* Install the goal target in the topmost WindowAgg */
5000 }
5001
5002 /* mark the final item in the list as the top-level window */
5003 topwindow = foreach_current_index(l) == list_length(activeWindows) - 1;
5004
5005 /*
5006 * Collect the WindowFuncRunConditions from each WindowFunc and
5007 * convert them into OpExprs
5008 */
5009 foreach(lc2, wflists->windowFuncs[wc->winref])
5010 {
5011 ListCell *lc3;
5013
5014 foreach(lc3, wfunc->runCondition)
5015 {
5018 Expr *opexpr;
5019 Expr *leftop;
5020 Expr *rightop;
5021
5022 if (wfuncrc->wfunc_left)
5023 {
5024 leftop = (Expr *) copyObject(wfunc);
5025 rightop = copyObject(wfuncrc->arg);
5026 }
5027 else
5028 {
5029 leftop = copyObject(wfuncrc->arg);
5030 rightop = (Expr *) copyObject(wfunc);
5031 }
5032
5033 opexpr = make_opclause(wfuncrc->opno,
5034 BOOLOID,
5035 false,
5036 leftop,
5037 rightop,
5038 InvalidOid,
5039 wfuncrc->inputcollid);
5040
5041 runcondition = lappend(runcondition, opexpr);
5042
5043 if (!topwindow)
5044 topqual = lappend(topqual, opexpr);
5045 }
5046 }
5047
5048 path = (Path *)
5050 wflists->windowFuncs[wc->winref],
5051 runcondition, wc,
5052 topwindow ? topqual : NIL, topwindow);
5053 }
5054
5055 add_path(window_rel, path);
5056}
5057
5058/*
5059 * create_distinct_paths
5060 *
5061 * Build a new upperrel containing Paths for SELECT DISTINCT evaluation.
5062 *
5063 * input_rel: contains the source-data Paths
5064 * target: the pathtarget for the result Paths to compute
5065 *
5066 * Note: input paths should already compute the desired pathtarget, since
5067 * Sort/Unique won't project anything.
5068 */
5069static RelOptInfo *
5071 PathTarget *target)
5072{
5074
5075 /* For now, do all work in the (DISTINCT, NULL) upperrel */
5077
5078 /*
5079 * We don't compute anything at this level, so distinct_rel will be
5080 * parallel-safe if the input rel is parallel-safe. In particular, if
5081 * there is a DISTINCT ON (...) clause, any path for the input_rel will
5082 * output those expressions, and will not be parallel-safe unless those
5083 * expressions are parallel-safe.
5084 */
5085 distinct_rel->consider_parallel = input_rel->consider_parallel;
5086
5087 /*
5088 * If the input rel belongs to a single FDW, so does the distinct_rel.
5089 */
5090 distinct_rel->serverid = input_rel->serverid;
5091 distinct_rel->userid = input_rel->userid;
5092 distinct_rel->useridiscurrent = input_rel->useridiscurrent;
5093 distinct_rel->fdwroutine = input_rel->fdwroutine;
5094
5095 /* build distinct paths based on input_rel's pathlist */
5097
5098 /* now build distinct paths based on input_rel's partial_pathlist */
5100
5101 /* Give a helpful error if we failed to create any paths */
5102 if (distinct_rel->pathlist == NIL)
5103 ereport(ERROR,
5105 errmsg("could not implement DISTINCT"),
5106 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
5107
5108 /*
5109 * If there is an FDW that's responsible for all baserels of the query,
5110 * let it consider adding ForeignPaths.
5111 */
5112 if (distinct_rel->fdwroutine &&
5113 distinct_rel->fdwroutine->GetForeignUpperPaths)
5114 distinct_rel->fdwroutine->GetForeignUpperPaths(root,
5116 input_rel,
5118 NULL);
5119
5120 /* Let extensions possibly add some more paths */
5122 (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
5124
5125 /* Now choose the best path(s) */
5127
5128 return distinct_rel;
5129}
5130
5131/*
5132 * create_partial_distinct_paths
5133 *
5134 * Process 'input_rel' partial paths and add unique/aggregate paths to the
5135 * UPPERREL_PARTIAL_DISTINCT rel. For paths created, add Gather/GatherMerge
5136 * paths on top and add a final unique/aggregate path to remove any duplicate
5137 * produced from combining rows from parallel workers.
5138 */
5139static void
5142 PathTarget *target)
5143{
5145 Query *parse;
5147 double numDistinctRows;
5149 ListCell *lc;
5150
5151 /* nothing to do when there are no partial paths in the input rel */
5152 if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
5153 return;
5154
5155 parse = root->parse;
5156
5157 /* can't do parallel DISTINCT ON */
5158 if (parse->hasDistinctOn)
5159 return;
5160
5162 NULL);
5163 partial_distinct_rel->reltarget = target;
5164 partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
5165
5166 /*
5167 * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
5168 */
5169 partial_distinct_rel->serverid = input_rel->serverid;
5170 partial_distinct_rel->userid = input_rel->userid;
5171 partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
5172 partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
5173
5174 cheapest_partial_path = linitial(input_rel->partial_pathlist);
5175
5176 distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
5177 parse->targetList);
5178
5179 /* estimate how many distinct rows we'll get from each worker */
5182 NULL, NULL);
5183
5184 /*
5185 * Try sorting the cheapest path and incrementally sorting any paths with
5186 * presorted keys and put a unique paths atop of those. We'll also
5187 * attempt to reorder the required pathkeys to match the input path's
5188 * pathkeys as much as possible, in hopes of avoiding a possible need to
5189 * re-sort.
5190 */
5191 if (grouping_is_sortable(root->processed_distinctClause))
5192 {
5193 foreach(lc, input_rel->partial_pathlist)
5194 {
5195 Path *input_path = (Path *) lfirst(lc);
5198
5201 root->distinct_pathkeys,
5202 input_path->pathkeys);
5204
5206 {
5209 input_path,
5212 -1.0);
5213
5214 if (sorted_path == NULL)
5215 continue;
5216
5217 /*
5218 * An empty distinct_pathkeys means all tuples have the same
5219 * value for the DISTINCT clause. See
5220 * create_final_distinct_paths()
5221 */
5222 if (root->distinct_pathkeys == NIL)
5223 {
5224 Node *limitCount;
5225
5226 limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5227 sizeof(int64),
5228 Int64GetDatum(1), false,
5229 true);
5230
5231 /*
5232 * Apply a LimitPath onto the partial path to restrict the
5233 * tuples from each worker to 1.
5234 * create_final_distinct_paths will need to apply an
5235 * additional LimitPath to restrict this to a single row
5236 * after the Gather node. If the query already has a
5237 * LIMIT clause, then we could end up with three Limit
5238 * nodes in the final plan. Consolidating the top two of
5239 * these could be done, but does not seem worth troubling
5240 * over.
5241 */
5245 NULL,
5246 limitCount,
5248 0, 1));
5249 }
5250 else
5251 {
5255 list_length(root->distinct_pathkeys),
5257 }
5258 }
5259 }
5260 }
5261
5262 /*
5263 * Now try hash aggregate paths, if enabled and hashing is possible. Since
5264 * we're not on the hook to ensure we do our best to create at least one
5265 * path here, we treat enable_hashagg as a hard off-switch rather than the
5266 * slightly softer variant in create_final_distinct_paths.
5267 */
5268 if (enable_hashagg && grouping_is_hashable(root->processed_distinctClause))
5269 {
5274 cheapest_partial_path->pathtarget,
5275 AGG_HASHED,
5277 root->processed_distinctClause,
5278 NIL,
5279 NULL,
5281 }
5282
5283 /*
5284 * If there is an FDW that's responsible for all baserels of the query,
5285 * let it consider adding ForeignPaths.
5286 */
5287 if (partial_distinct_rel->fdwroutine &&
5288 partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
5289 partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
5291 input_rel,
5293 NULL);
5294
5295 /* Let extensions possibly add some more partial paths */
5297 (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
5299
5300 if (partial_distinct_rel->partial_pathlist != NIL)
5301 {
5304
5305 /*
5306 * Finally, create paths to distinctify the final result. This step
5307 * is needed to remove any duplicates due to combining rows from
5308 * parallel workers.
5309 */
5312 }
5313}
5314
5315/*
5316 * create_final_distinct_paths
5317 * Create distinct paths in 'distinct_rel' based on 'input_rel' pathlist
5318 *
5319 * input_rel: contains the source-data paths
5320 * distinct_rel: destination relation for storing created paths
5321 */
5322static RelOptInfo *
5325{
5326 Query *parse = root->parse;
5327 Path *cheapest_input_path = input_rel->cheapest_total_path;
5328 double numDistinctRows;
5329 bool allow_hash;
5330
5331 /* Estimate number of distinct rows there will be */
5332 if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
5333 root->hasHavingQual)
5334 {
5335 /*
5336 * If there was grouping or aggregation, use the number of input rows
5337 * as the estimated number of DISTINCT rows (ie, assume the input is
5338 * already mostly unique).
5339 */
5341 }
5342 else
5343 {
5344 /*
5345 * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
5346 */
5348
5349 distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
5350 parse->targetList);
5352 cheapest_input_path->rows,
5353 NULL, NULL);
5354 }
5355
5356 /*
5357 * Consider sort-based implementations of DISTINCT, if possible.
5358 */
5359 if (grouping_is_sortable(root->processed_distinctClause))
5360 {
5361 /*
5362 * Firstly, if we have any adequately-presorted paths, just stick a
5363 * Unique node on those. We also, consider doing an explicit sort of
5364 * the cheapest input path and Unique'ing that. If any paths have
5365 * presorted keys then we'll create an incremental sort atop of those
5366 * before adding a unique node on the top. We'll also attempt to
5367 * reorder the required pathkeys to match the input path's pathkeys as
5368 * much as possible, in hopes of avoiding a possible need to re-sort.
5369 *
5370 * When we have DISTINCT ON, we must sort by the more rigorous of
5371 * DISTINCT and ORDER BY, else it won't have the desired behavior.
5372 * Also, if we do have to do an explicit sort, we might as well use
5373 * the more rigorous ordering to avoid a second sort later. (Note
5374 * that the parser will have ensured that one clause is a prefix of
5375 * the other.)
5376 */
5378 ListCell *lc;
5379 double limittuples = root->distinct_pathkeys == NIL ? 1.0 : -1.0;
5380
5381 if (parse->hasDistinctOn &&
5382 list_length(root->distinct_pathkeys) <
5383 list_length(root->sort_pathkeys))
5384 needed_pathkeys = root->sort_pathkeys;
5385 else
5386 needed_pathkeys = root->distinct_pathkeys;
5387
5388 foreach(lc, input_rel->pathlist)
5389 {
5390 Path *input_path = (Path *) lfirst(lc);
5393
5397 input_path->pathkeys);
5399
5401 {
5404 input_path,
5407 limittuples);
5408
5409 if (sorted_path == NULL)
5410 continue;
5411
5412 /*
5413 * distinct_pathkeys may have become empty if all of the
5414 * pathkeys were determined to be redundant. If all of the
5415 * pathkeys are redundant then each DISTINCT target must only
5416 * allow a single value, therefore all resulting tuples must
5417 * be identical (or at least indistinguishable by an equality
5418 * check). We can uniquify these tuples simply by just taking
5419 * the first tuple. All we do here is add a path to do "LIMIT
5420 * 1" atop of 'sorted_path'. When doing a DISTINCT ON we may
5421 * still have a non-NIL sort_pathkeys list, so we must still
5422 * only do this with paths which are correctly sorted by
5423 * sort_pathkeys.
5424 */
5425 if (root->distinct_pathkeys == NIL)
5426 {
5427 Node *limitCount;
5428
5429 limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5430 sizeof(int64),
5431 Int64GetDatum(1), false,
5432 true);
5433
5434 /*
5435 * If the query already has a LIMIT clause, then we could
5436 * end up with a duplicate LimitPath in the final plan.
5437 * That does not seem worth troubling over too much.
5438 */
5441 NULL, limitCount,
5442 LIMIT_OPTION_COUNT, 0, 1));
5443 }
5444 else
5445 {
5449 list_length(root->distinct_pathkeys),
5451 }
5452 }
5453 }
5454 }
5455
5456 /*
5457 * Consider hash-based implementations of DISTINCT, if possible.
5458 *
5459 * If we were not able to make any other types of path, we *must* hash or
5460 * die trying. If we do have other choices, there are two things that
5461 * should prevent selection of hashing: if the query uses DISTINCT ON
5462 * (because it won't really have the expected behavior if we hash), or if
5463 * enable_hashagg is off.
5464 *
5465 * Note: grouping_is_hashable() is much more expensive to check than the
5466 * other gating conditions, so we want to do it last.
5467 */
5468 if (distinct_rel->pathlist == NIL)
5469 allow_hash = true; /* we have no alternatives */
5470 else if (parse->hasDistinctOn || !enable_hashagg)
5471 allow_hash = false; /* policy-based decision not to hash */
5472 else
5473 allow_hash = true; /* default */
5474
5475 if (allow_hash && grouping_is_hashable(root->processed_distinctClause))
5476 {
5477 /* Generate hashed aggregate path --- no sort needed */
5482 cheapest_input_path->pathtarget,
5483 AGG_HASHED,
5485 root->processed_distinctClause,
5486 NIL,
5487 NULL,
5489 }
5490
5491 return distinct_rel;
5492}
5493
5494/*
5495 * get_useful_pathkeys_for_distinct
5496 * Get useful orderings of pathkeys for distinctClause by reordering
5497 * 'needed_pathkeys' to match the given 'path_pathkeys' as much as possible.
5498 *
5499 * This returns a list of pathkeys that can be useful for DISTINCT or DISTINCT
5500 * ON clause. For convenience, it always includes the given 'needed_pathkeys'.
5501 */
5502static List *
5505{
5508
5509 /* always include the given 'needed_pathkeys' */
5512
5514 return useful_pathkeys_list;
5515
5516 /*
5517 * Scan the given 'path_pathkeys' and construct a list of PathKey nodes
5518 * that match 'needed_pathkeys', but only up to the longest matching
5519 * prefix.
5520 *
5521 * When we have DISTINCT ON, we must ensure that the resulting pathkey
5522 * list matches initial distinctClause pathkeys; otherwise, it won't have
5523 * the desired behavior.
5524 */
5526 {
5527 /*
5528 * The PathKey nodes are canonical, so they can be checked for
5529 * equality by simple pointer comparison.
5530 */
5532 break;
5533 if (root->parse->hasDistinctOn &&
5534 !list_member_ptr(root->distinct_pathkeys, pathkey))
5535 break;
5536
5538 }
5539
5540 /* If no match at all, no point in reordering needed_pathkeys */
5541 if (useful_pathkeys == NIL)
5542 return useful_pathkeys_list;
5543
5544 /*
5545 * If not full match, the resulting pathkey list is not useful without
5546 * incremental sort.
5547 */
5550 return useful_pathkeys_list;
5551
5552 /* Append the remaining PathKey nodes in needed_pathkeys */
5555
5556 /*
5557 * If the resulting pathkey list is the same as the 'needed_pathkeys',
5558 * just drop it.
5559 */
5562 return useful_pathkeys_list;
5563
5566
5567 return useful_pathkeys_list;
5568}
5569
5570/*
5571 * create_ordered_paths
5572 *
5573 * Build a new upperrel containing Paths for ORDER BY evaluation.
5574 *
5575 * All paths in the result must satisfy the ORDER BY ordering.
5576 * The only new paths we need consider are an explicit full sort
5577 * and incremental sort on the cheapest-total existing path.
5578 *
5579 * input_rel: contains the source-data Paths
5580 * target: the output tlist the result Paths must emit
5581 * limit_tuples: estimated bound on the number of output tuples,
5582 * or -1 if no LIMIT or couldn't estimate
5583 *
5584 * XXX This only looks at sort_pathkeys. I wonder if it needs to look at the
5585 * other pathkeys (grouping, ...) like generate_useful_gather_paths.
5586 */
5587static RelOptInfo *
5590 PathTarget *target,
5591 bool target_parallel_safe,
5592 double limit_tuples)
5593{
5594 Path *cheapest_input_path = input_rel->cheapest_total_path;
5596 ListCell *lc;
5597
5598 /* For now, do all work in the (ORDERED, NULL) upperrel */
5600
5601 /*
5602 * If the input relation is not parallel-safe, then the ordered relation
5603 * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
5604 * target list is parallel-safe.
5605 */
5606 if (input_rel->consider_parallel && target_parallel_safe)
5607 ordered_rel->consider_parallel = true;
5608
5609 /* Assume that the same path generation strategies are allowed. */
5610 ordered_rel->pgs_mask = input_rel->pgs_mask;
5611
5612 /*
5613 * If the input rel belongs to a single FDW, so does the ordered_rel.
5614 */
5615 ordered_rel->serverid = input_rel->serverid;
5616 ordered_rel->userid = input_rel->userid;
5617 ordered_rel->useridiscurrent = input_rel->useridiscurrent;
5618 ordered_rel->fdwroutine = input_rel->fdwroutine;
5619
5620 foreach(lc, input_rel->pathlist)
5621 {
5622 Path *input_path = (Path *) lfirst(lc);
5624 bool is_sorted;
5625 int presorted_keys;
5626
5628 input_path->pathkeys, &presorted_keys);
5629
5630 if (is_sorted)
5632 else
5633 {
5634 /*
5635 * Try at least sorting the cheapest path and also try
5636 * incrementally sorting any path which is partially sorted
5637 * already (no need to deal with paths which have presorted keys
5638 * when incremental sort is disabled unless it's the cheapest
5639 * input path).
5640 */
5642 (presorted_keys == 0 || !enable_incremental_sort))
5643 continue;
5644
5645 /*
5646 * We've no need to consider both a sort and incremental sort.
5647 * We'll just do a sort if there are no presorted keys and an
5648 * incremental sort when there are presorted keys.
5649 */
5650 if (presorted_keys == 0 || !enable_incremental_sort)
5653 input_path,
5654 root->sort_pathkeys,
5655 limit_tuples);
5656 else
5659 input_path,
5660 root->sort_pathkeys,
5661 presorted_keys,
5662 limit_tuples);
5663 }
5664
5665 /*
5666 * If the pathtarget of the result path has different expressions from
5667 * the target to be applied, a projection step is needed.
5668 */
5669 if (!equal(sorted_path->pathtarget->exprs, target->exprs))
5671 sorted_path, target);
5672
5674 }
5675
5676 /*
5677 * generate_gather_paths() will have already generated a simple Gather
5678 * path for the best parallel path, if any, and the loop above will have
5679 * considered sorting it. Similarly, generate_gather_paths() will also
5680 * have generated order-preserving Gather Merge plans which can be used
5681 * without sorting if they happen to match the sort_pathkeys, and the loop
5682 * above will have handled those as well. However, there's one more
5683 * possibility: it may make sense to sort the cheapest partial path or
5684 * incrementally sort any partial path that is partially sorted according
5685 * to the required output order and then use Gather Merge.
5686 */
5687 if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5688 input_rel->partial_pathlist != NIL)
5689 {
5691
5692 cheapest_partial_path = linitial(input_rel->partial_pathlist);
5693
5694 foreach(lc, input_rel->partial_pathlist)
5695 {
5696 Path *input_path = (Path *) lfirst(lc);
5698 bool is_sorted;
5699 int presorted_keys;
5700 double total_groups;
5701
5703 input_path->pathkeys,
5704 &presorted_keys);
5705
5706 if (is_sorted)
5707 continue;
5708
5709 /*
5710 * Try at least sorting the cheapest path and also try
5711 * incrementally sorting any path which is partially sorted
5712 * already (no need to deal with paths which have presorted keys
5713 * when incremental sort is disabled unless it's the cheapest
5714 * partial path).
5715 */
5717 (presorted_keys == 0 || !enable_incremental_sort))
5718 continue;
5719
5720 /*
5721 * We've no need to consider both a sort and incremental sort.
5722 * We'll just do a sort if there are no presorted keys and an
5723 * incremental sort when there are presorted keys.
5724 */
5725 if (presorted_keys == 0 || !enable_incremental_sort)
5728 input_path,
5729 root->sort_pathkeys,
5730 limit_tuples);
5731 else
5734 input_path,
5735 root->sort_pathkeys,
5736 presorted_keys,
5737 limit_tuples);
5739 sorted_path = (Path *)
5742 sorted_path->pathtarget,
5743 root->sort_pathkeys, NULL,
5744 &total_groups);
5745
5746 /*
5747 * If the pathtarget of the result path has different expressions
5748 * from the target to be applied, a projection step is needed.
5749 */
5750 if (!equal(sorted_path->pathtarget->exprs, target->exprs))
5752 sorted_path, target);
5753
5755 }
5756 }
5757
5758 /*
5759 * If there is an FDW that's responsible for all baserels of the query,
5760 * let it consider adding ForeignPaths.
5761 */
5762 if (ordered_rel->fdwroutine &&
5763 ordered_rel->fdwroutine->GetForeignUpperPaths)
5764 ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5766 NULL);
5767
5768 /* Let extensions possibly add some more paths */
5770 (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5772
5773 /*
5774 * No need to bother with set_cheapest here; grouping_planner does not
5775 * need us to do it.
5776 */
5777 Assert(ordered_rel->pathlist != NIL);
5778
5779 return ordered_rel;
5780}
5781
5782
5783/*
5784 * make_group_input_target
5785 * Generate appropriate PathTarget for initial input to grouping nodes.
5786 *
5787 * If there is grouping or aggregation, the scan/join subplan cannot emit
5788 * the query's final targetlist; for example, it certainly can't emit any
5789 * aggregate function calls. This routine generates the correct target
5790 * for the scan/join subplan.
5791 *
5792 * The query target list passed from the parser already contains entries
5793 * for all ORDER BY and GROUP BY expressions, but it will not have entries
5794 * for variables used only in HAVING clauses; so we need to add those
5795 * variables to the subplan target list. Also, we flatten all expressions
5796 * except GROUP BY items into their component variables; other expressions
5797 * will be computed by the upper plan nodes rather than by the subplan.
5798 * For example, given a query like
5799 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
5800 * we want to pass this targetlist to the subplan:
5801 * a+b,c,d
5802 * where the a+b target will be used by the Sort/Group steps, and the
5803 * other targets will be used for computing the final results.
5804 *
5805 * 'final_target' is the query's final target list (in PathTarget form)
5806 *
5807 * The result is the PathTarget to be computed by the Paths returned from
5808 * query_planner().
5809 */
5810static PathTarget *
5812{
5813 Query *parse = root->parse;
5817 int i;
5818 ListCell *lc;
5819
5820 /*
5821 * We must build a target containing all grouping columns, plus any other
5822 * Vars mentioned in the query's targetlist and HAVING qual.
5823 */
5826
5827 i = 0;
5828 foreach(lc, final_target->exprs)
5829 {
5830 Expr *expr = (Expr *) lfirst(lc);
5832
5833 if (sgref && root->processed_groupClause &&
5835 root->processed_groupClause) != NULL)
5836 {
5837 /*
5838 * It's a grouping column, so add it to the input target as-is.
5839 *
5840 * Note that the target is logically below the grouping step. So
5841 * with grouping sets we need to remove the RT index of the
5842 * grouping step if there is any from the target expression.
5843 */
5844 if (parse->hasGroupRTE && parse->groupingSets != NIL)
5845 {
5846 Assert(root->group_rtindex > 0);
5847 expr = (Expr *)
5848 remove_nulling_relids((Node *) expr,
5849 bms_make_singleton(root->group_rtindex),
5850 NULL);
5851 }
5853 }
5854 else
5855 {
5856 /*
5857 * Non-grouping column, so just remember the expression for later
5858 * call to pull_var_clause.
5859 */
5861 }
5862
5863 i++;
5864 }
5865
5866 /*
5867 * If there's a HAVING clause, we'll need the Vars it uses, too.
5868 */
5869 if (parse->havingQual)
5871
5872 /*
5873 * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5874 * add them to the input target if not already present. (A Var used
5875 * directly as a GROUP BY item will be present already.) Note this
5876 * includes Vars used in resjunk items, so we are covering the needs of
5877 * ORDER BY and window specifications. Vars used within Aggrefs and
5878 * WindowFuncs will be pulled out here, too.
5879 *
5880 * Note that the target is logically below the grouping step. So with
5881 * grouping sets we need to remove the RT index of the grouping step if
5882 * there is any from the non-group Vars.
5883 */
5888 if (parse->hasGroupRTE && parse->groupingSets != NIL)
5889 {
5890 Assert(root->group_rtindex > 0);
5891 non_group_vars = (List *)
5893 bms_make_singleton(root->group_rtindex),
5894 NULL);
5895 }
5897
5898 /* clean up cruft */
5901
5902 /* XXX this causes some redundant cost calculation ... */
5904}
5905
5906/*
5907 * make_partial_grouping_target
5908 * Generate appropriate PathTarget for output of partial aggregate
5909 * (or partial grouping, if there are no aggregates) nodes.
5910 *
5911 * A partial aggregation node needs to emit all the same aggregates that
5912 * a regular aggregation node would, plus any aggregates used in HAVING;
5913 * except that the Aggref nodes should be marked as partial aggregates.
5914 *
5915 * In addition, we'd better emit any Vars and PlaceHolderVars that are
5916 * used outside of Aggrefs in the aggregation tlist and HAVING. (Presumably,
5917 * these would be Vars that are grouped by or used in grouping expressions.)
5918 *
5919 * grouping_target is the tlist to be emitted by the topmost aggregation step.
5920 * havingQual represents the HAVING clause.
5921 */
5922static PathTarget *
5925 Node *havingQual)
5926{
5930 int i;
5931 ListCell *lc;
5932
5935
5936 i = 0;
5937 foreach(lc, grouping_target->exprs)
5938 {
5939 Expr *expr = (Expr *) lfirst(lc);
5941
5942 if (sgref && root->processed_groupClause &&
5944 root->processed_groupClause) != NULL)
5945 {
5946 /*
5947 * It's a grouping column, so add it to the partial_target as-is.
5948 * (This allows the upper agg step to repeat the grouping calcs.)
5949 */
5951 }
5952 else
5953 {
5954 /*
5955 * Non-grouping column, so just remember the expression for later
5956 * call to pull_var_clause.
5957 */
5959 }
5960
5961 i++;
5962 }
5963
5964 /*
5965 * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
5966 */
5967 if (havingQual)
5968 non_group_cols = lappend(non_group_cols, havingQual);
5969
5970 /*
5971 * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
5972 * non-group cols (plus HAVING), and add them to the partial_target if not
5973 * already present. (An expression used directly as a GROUP BY item will
5974 * be present already.) Note this includes Vars used in resjunk items, so
5975 * we are covering the needs of ORDER BY and window specifications.
5976 */
5981
5983
5984 /*
5985 * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
5986 * are at the top level of the target list, so we can just scan the list
5987 * rather than recursing through the expression trees.
5988 */
5989 foreach(lc, partial_target->exprs)
5990 {
5991 Aggref *aggref = (Aggref *) lfirst(lc);
5992
5993 if (IsA(aggref, Aggref))
5994 {
5996
5997 /*
5998 * We shouldn't need to copy the substructure of the Aggref node,
5999 * but flat-copy the node itself to avoid damaging other trees.
6000 */
6002 memcpy(newaggref, aggref, sizeof(Aggref));
6003
6004 /* For now, assume serialization is required */
6006
6007 lfirst(lc) = newaggref;
6008 }
6009 }
6010
6011 /* clean up cruft */
6014
6015 /* XXX this causes some redundant cost calculation ... */
6017}
6018
6019/*
6020 * mark_partial_aggref
6021 * Adjust an Aggref to make it represent a partial-aggregation step.
6022 *
6023 * The Aggref node is modified in-place; caller must do any copying required.
6024 */
6025void
6027{
6028 /* aggtranstype should be computed by this point */
6029 Assert(OidIsValid(agg->aggtranstype));
6030 /* ... but aggsplit should still be as the parser left it */
6031 Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
6032
6033 /* Mark the Aggref with the intended partial-aggregation mode */
6034 agg->aggsplit = aggsplit;
6035
6036 /*
6037 * Adjust result type if needed. Normally, a partial aggregate returns
6038 * the aggregate's transition type; but if that's INTERNAL and we're
6039 * serializing, it returns BYTEA instead.
6040 */
6041 if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
6042 {
6043 if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
6044 agg->aggtype = BYTEAOID;
6045 else
6046 agg->aggtype = agg->aggtranstype;
6047 }
6048}
6049
6050/*
6051 * postprocess_setop_tlist
6052 * Fix up targetlist returned by plan_set_operations().
6053 *
6054 * We need to transpose sort key info from the orig_tlist into new_tlist.
6055 * NOTE: this would not be good enough if we supported resjunk sort keys
6056 * for results of set operations --- then, we'd need to project a whole
6057 * new tlist to evaluate the resjunk columns. For now, just ereport if we
6058 * find any resjunk columns in orig_tlist.
6059 */
6060static List *
6062{
6063 ListCell *l;
6065
6066 foreach(l, new_tlist)
6067 {
6070
6071 /* ignore resjunk columns in setop result */
6072 if (new_tle->resjunk)
6073 continue;
6074
6078 if (orig_tle->resjunk) /* should not happen */
6079 elog(ERROR, "resjunk output columns are not implemented");
6080 Assert(new_tle->resno == orig_tle->resno);
6081 new_tle->ressortgroupref = orig_tle->ressortgroupref;
6082 }
6083 if (orig_tlist_item != NULL)
6084 elog(ERROR, "resjunk output columns are not implemented");
6085 return new_tlist;
6086}
6087
6088/*
6089 * optimize_window_clauses
6090 * Call each WindowFunc's prosupport function to see if we're able to
6091 * make any adjustments to any of the WindowClause's so that the executor
6092 * can execute the window functions in a more optimal way.
6093 *
6094 * Currently we only allow adjustments to the WindowClause's frameOptions. We
6095 * may allow more things to be done here in the future.
6096 */
6097static void
6099{
6100 List *windowClause = root->parse->windowClause;
6101 ListCell *lc;
6102
6103 foreach(lc, windowClause)
6104 {
6106 ListCell *lc2;
6107 int optimizedFrameOptions = 0;
6108
6109 Assert(wc->winref <= wflists->maxWinRef);
6110
6111 /* skip any WindowClauses that have no WindowFuncs */
6112 if (wflists->windowFuncs[wc->winref] == NIL)
6113 continue;
6114
6115 foreach(lc2, wflists->windowFuncs[wc->winref])
6116 {
6121
6123
6124 /* Check if there's a support function for 'wfunc' */
6125 if (!OidIsValid(prosupport))
6126 break; /* can't optimize this WindowClause */
6127
6129 req.window_clause = wc;
6130 req.window_func = wfunc;
6131 req.frameOptions = wc->frameOptions;
6132
6133 /* call the support function */
6136 PointerGetDatum(&req)));
6137
6138 /*
6139 * Skip to next WindowClause if the support function does not
6140 * support this request type.
6141 */
6142 if (res == NULL)
6143 break;
6144
6145 /*
6146 * Save these frameOptions for the first WindowFunc for this
6147 * WindowClause.
6148 */
6149 if (foreach_current_index(lc2) == 0)
6151
6152 /*
6153 * On subsequent WindowFuncs, if the frameOptions are not the same
6154 * then we're unable to optimize the frameOptions for this
6155 * WindowClause.
6156 */
6157 else if (optimizedFrameOptions != res->frameOptions)
6158 break; /* skip to the next WindowClause, if any */
6159 }
6160
6161 /* adjust the frameOptions if all WindowFunc's agree that it's ok */
6162 if (lc2 == NULL && wc->frameOptions != optimizedFrameOptions)
6163 {
6164 ListCell *lc3;
6165
6166 /* apply the new frame options */
6168
6169 /*
6170 * We now check to see if changing the frameOptions has caused
6171 * this WindowClause to be a duplicate of some other WindowClause.
6172 * This can only happen if we have multiple WindowClauses, so
6173 * don't bother if there's only 1.
6174 */
6175 if (list_length(windowClause) == 1)
6176 continue;
6177
6178 /*
6179 * Do the duplicate check and reuse the existing WindowClause if
6180 * we find a duplicate.
6181 */
6182 foreach(lc3, windowClause)
6183 {
6185
6186 /* skip over the WindowClause we're currently editing */
6187 if (existing_wc == wc)
6188 continue;
6189
6190 /*
6191 * Perform the same duplicate check that is done in
6192 * transformWindowFuncCall.
6193 */
6194 if (equal(wc->partitionClause, existing_wc->partitionClause) &&
6195 equal(wc->orderClause, existing_wc->orderClause) &&
6196 wc->frameOptions == existing_wc->frameOptions &&
6197 equal(wc->startOffset, existing_wc->startOffset) &&
6198 equal(wc->endOffset, existing_wc->endOffset))
6199 {
6200 ListCell *lc4;
6201
6202 /*
6203 * Now move each WindowFunc in 'wc' into 'existing_wc'.
6204 * This required adjusting each WindowFunc's winref and
6205 * moving the WindowFuncs in 'wc' to the list of
6206 * WindowFuncs in 'existing_wc'.
6207 */
6208 foreach(lc4, wflists->windowFuncs[wc->winref])
6209 {
6211
6212 wfunc->winref = existing_wc->winref;
6213 }
6214
6215 /* move list items */
6216 wflists->windowFuncs[existing_wc->winref] = list_concat(wflists->windowFuncs[existing_wc->winref],
6217 wflists->windowFuncs[wc->winref]);
6218 wflists->windowFuncs[wc->winref] = NIL;
6219
6220 /*
6221 * transformWindowFuncCall() should have made sure there
6222 * are no other duplicates, so we needn't bother looking
6223 * any further.
6224 */
6225 break;
6226 }
6227 }
6228 }
6229 }
6230}
6231
6232/*
6233 * select_active_windows
6234 * Create a list of the "active" window clauses (ie, those referenced
6235 * by non-deleted WindowFuncs) in the order they are to be executed.
6236 */
6237static List *
6239{
6240 List *windowClause = root->parse->windowClause;
6241 List *result = NIL;
6242 ListCell *lc;
6243 int nActive = 0;
6245 list_length(windowClause));
6246
6247 /* First, construct an array of the active windows */
6248 foreach(lc, windowClause)
6249 {
6251
6252 /* It's only active if wflists shows some related WindowFuncs */
6253 Assert(wc->winref <= wflists->maxWinRef);
6254 if (wflists->windowFuncs[wc->winref] == NIL)
6255 continue;
6256
6257 actives[nActive].wc = wc; /* original clause */
6258
6259 /*
6260 * For sorting, we want the list of partition keys followed by the
6261 * list of sort keys. But pathkeys construction will remove duplicates
6262 * between the two, so we can as well (even though we can't detect all
6263 * of the duplicates, since some may come from ECs - that might mean
6264 * we miss optimization chances here). We must, however, ensure that
6265 * the order of entries is preserved with respect to the ones we do
6266 * keep.
6267 *
6268 * partitionClause and orderClause had their own duplicates removed in
6269 * parse analysis, so we're only concerned here with removing
6270 * orderClause entries that also appear in partitionClause.
6271 */
6272 actives[nActive].uniqueOrder =
6274 wc->orderClause);
6275 nActive++;
6276 }
6277
6278 /*
6279 * Sort active windows by their partitioning/ordering clauses, ignoring
6280 * any framing clauses, so that the windows that need the same sorting are
6281 * adjacent in the list. When we come to generate paths, this will avoid
6282 * inserting additional Sort nodes.
6283 *
6284 * This is how we implement a specific requirement from the SQL standard,
6285 * which says that when two or more windows are order-equivalent (i.e.
6286 * have matching partition and order clauses, even if their names or
6287 * framing clauses differ), then all peer rows must be presented in the
6288 * same order in all of them. If we allowed multiple sort nodes for such
6289 * cases, we'd risk having the peer rows end up in different orders in
6290 * equivalent windows due to sort instability. (See General Rule 4 of
6291 * <window clause> in SQL2008 - SQL2016.)
6292 *
6293 * Additionally, if the entire list of clauses of one window is a prefix
6294 * of another, put first the window with stronger sorting requirements.
6295 * This way we will first sort for stronger window, and won't have to sort
6296 * again for the weaker one.
6297 */
6299
6300 /* build ordered list of the original WindowClause nodes */
6301 for (int i = 0; i < nActive; i++)
6302 result = lappend(result, actives[i].wc);
6303
6304 pfree(actives);
6305
6306 return result;
6307}
6308
6309/*
6310 * name_active_windows
6311 * Ensure all active windows have unique names.
6312 *
6313 * The parser will have checked that user-assigned window names are unique
6314 * within the Query. Here we assign made-up names to any unnamed
6315 * WindowClauses for the benefit of EXPLAIN. (We don't want to do this
6316 * at parse time, because it'd mess up decompilation of views.)
6317 *
6318 * activeWindows: result of select_active_windows
6319 */
6320static void
6322{
6323 int next_n = 1;
6324 char newname[16];
6325 ListCell *lc;
6326
6327 foreach(lc, activeWindows)
6328 {
6330
6331 /* Nothing to do if it has a name already. */
6332 if (wc->name)
6333 continue;
6334
6335 /* Select a name not currently present in the list. */
6336 for (;;)
6337 {
6338 ListCell *lc2;
6339
6340 snprintf(newname, sizeof(newname), "w%d", next_n++);
6341 foreach(lc2, activeWindows)
6342 {
6344
6345 if (wc2->name && strcmp(wc2->name, newname) == 0)
6346 break; /* matched */
6347 }
6348 if (lc2 == NULL)
6349 break; /* reached the end with no match */
6350 }
6351 wc->name = pstrdup(newname);
6352 }
6353}
6354
6355/*
6356 * common_prefix_cmp
6357 * QSort comparison function for WindowClauseSortData
6358 *
6359 * Sort the windows by the required sorting clauses. First, compare the sort
6360 * clauses themselves. Second, if one window's clauses are a prefix of another
6361 * one's clauses, put the window with more sort clauses first.
6362 *
6363 * We purposefully sort by the highest tleSortGroupRef first. Since
6364 * tleSortGroupRefs are assigned for the query's DISTINCT and ORDER BY first
6365 * and because here we sort the lowest tleSortGroupRefs last, if a
6366 * WindowClause is sharing a tleSortGroupRef with the query's DISTINCT or
6367 * ORDER BY clause, this makes it more likely that the final WindowAgg will
6368 * provide presorted input for the query's DISTINCT or ORDER BY clause, thus
6369 * reducing the total number of sorts required for the query.
6370 */
6371static int
6372common_prefix_cmp(const void *a, const void *b)
6373{
6374 const WindowClauseSortData *wcsa = a;
6375 const WindowClauseSortData *wcsb = b;
6378
6379 forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
6380 {
6383
6384 if (sca->tleSortGroupRef > scb->tleSortGroupRef)
6385 return -1;
6386 else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
6387 return 1;
6388 else if (sca->sortop > scb->sortop)
6389 return -1;
6390 else if (sca->sortop < scb->sortop)
6391 return 1;
6392 else if (sca->nulls_first && !scb->nulls_first)
6393 return -1;
6394 else if (!sca->nulls_first && scb->nulls_first)
6395 return 1;
6396 /* no need to compare eqop, since it is fully determined by sortop */
6397 }
6398
6399 if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
6400 return -1;
6401 else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
6402 return 1;
6403
6404 return 0;
6405}
6406
6407/*
6408 * make_window_input_target
6409 * Generate appropriate PathTarget for initial input to WindowAgg nodes.
6410 *
6411 * When the query has window functions, this function computes the desired
6412 * target to be computed by the node just below the first WindowAgg.
6413 * This tlist must contain all values needed to evaluate the window functions,
6414 * compute the final target list, and perform any required final sort step.
6415 * If multiple WindowAggs are needed, each intermediate one adds its window
6416 * function results onto this base tlist; only the topmost WindowAgg computes
6417 * the actual desired target list.
6418 *
6419 * This function is much like make_group_input_target, though not quite enough
6420 * like it to share code. As in that function, we flatten most expressions
6421 * into their component variables. But we do not want to flatten window
6422 * PARTITION BY/ORDER BY clauses, since that might result in multiple
6423 * evaluations of them, which would be bad (possibly even resulting in
6424 * inconsistent answers, if they contain volatile functions).
6425 * Also, we must not flatten GROUP BY clauses that were left unflattened by
6426 * make_group_input_target, because we may no longer have access to the
6427 * individual Vars in them.
6428 *
6429 * Another key difference from make_group_input_target is that we don't
6430 * flatten Aggref expressions, since those are to be computed below the
6431 * window functions and just referenced like Vars above that.
6432 *
6433 * 'final_target' is the query's final target list (in PathTarget form)
6434 * 'activeWindows' is the list of active windows previously identified by
6435 * select_active_windows.
6436 *
6437 * The result is the PathTarget to be computed by the plan node immediately
6438 * below the first WindowAgg node.
6439 */
6440static PathTarget *
6443 List *activeWindows)
6444{
6449 int i;
6450 ListCell *lc;
6451
6452 Assert(root->parse->hasWindowFuncs);
6453
6454 /*
6455 * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
6456 * into a bitmapset for convenient reference below.
6457 */
6458 sgrefs = NULL;
6459 foreach(lc, activeWindows)
6460 {
6462 ListCell *lc2;
6463
6464 foreach(lc2, wc->partitionClause)
6465 {
6467
6468 sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
6469 }
6470 foreach(lc2, wc->orderClause)
6471 {
6473
6474 sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
6475 }
6476 }
6477
6478 /* Add in sortgroupref numbers of GROUP BY clauses, too */
6479 foreach(lc, root->processed_groupClause)
6480 {
6482
6483 sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
6484 }
6485
6486 /*
6487 * Construct a target containing all the non-flattenable targetlist items,
6488 * and save aside the others for a moment.
6489 */
6492
6493 i = 0;
6494 foreach(lc, final_target->exprs)
6495 {
6496 Expr *expr = (Expr *) lfirst(lc);
6498
6499 /*
6500 * Don't want to deconstruct window clauses or GROUP BY items. (Note
6501 * that such items can't contain window functions, so it's okay to
6502 * compute them below the WindowAgg nodes.)
6503 */
6504 if (sgref != 0 && bms_is_member(sgref, sgrefs))
6505 {
6506 /*
6507 * Don't want to deconstruct this value, so add it to the input
6508 * target as-is.
6509 */
6511 }
6512 else
6513 {
6514 /*
6515 * Column is to be flattened, so just remember the expression for
6516 * later call to pull_var_clause.
6517 */
6519 }
6520
6521 i++;
6522 }
6523
6524 /*
6525 * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
6526 * add them to the input target if not already present. (Some might be
6527 * there already because they're used directly as window/group clauses.)
6528 *
6529 * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
6530 * Aggrefs are placed in the Agg node's tlist and not left to be computed
6531 * at higher levels. On the other hand, we should recurse into
6532 * WindowFuncs to make sure their input expressions are available.
6533 */
6539
6540 /* clean up cruft */
6543
6544 /* XXX this causes some redundant cost calculation ... */
6546}
6547
6548/*
6549 * make_pathkeys_for_window
6550 * Create a pathkeys list describing the required input ordering
6551 * for the given WindowClause.
6552 *
6553 * Modifies wc's partitionClause to remove any clauses which are deemed
6554 * redundant by the pathkey logic.
6555 *
6556 * The required ordering is first the PARTITION keys, then the ORDER keys.
6557 * In the future we might try to implement windowing using hashing, in which
6558 * case the ordering could be relaxed, but for now we always sort.
6559 */
6560static List *
6562 List *tlist)
6563{
6564 List *window_pathkeys = NIL;
6565
6566 /* Throw error if can't sort */
6568 ereport(ERROR,
6570 errmsg("could not implement window PARTITION BY"),
6571 errdetail("Window partitioning columns must be of sortable datatypes.")));
6573 ereport(ERROR,
6575 errmsg("could not implement window ORDER BY"),
6576 errdetail("Window ordering columns must be of sortable datatypes.")));
6577
6578 /*
6579 * First fetch the pathkeys for the PARTITION BY clause. We can safely
6580 * remove any clauses from the wc->partitionClause for redundant pathkeys.
6581 */
6582 if (wc->partitionClause != NIL)
6583 {
6584 bool sortable;
6585
6587 &wc->partitionClause,
6588 tlist,
6589 true,
6590 false,
6591 &sortable,
6592 false);
6593
6595 }
6596
6597 /*
6598 * In principle, we could also consider removing redundant ORDER BY items
6599 * too as doing so does not alter the result of peer row checks done by
6600 * the executor. However, we must *not* remove the ordering column for
6601 * RANGE OFFSET cases, as the executor needs that for in_range tests even
6602 * if it's known to be equal to some partitioning column.
6603 */
6604 if (wc->orderClause != NIL)
6605 {
6607
6609 wc->orderClause,
6610 tlist);
6611
6612 /* Okay, make the combined pathkeys */
6613 if (window_pathkeys != NIL)
6614 window_pathkeys = append_pathkeys(window_pathkeys, orderby_pathkeys);
6615 else
6616 window_pathkeys = orderby_pathkeys;
6617 }
6618
6619 return window_pathkeys;
6620}
6621
6622/*
6623 * make_sort_input_target
6624 * Generate appropriate PathTarget for initial input to Sort step.
6625 *
6626 * If the query has ORDER BY, this function chooses the target to be computed
6627 * by the node just below the Sort (and DISTINCT, if any, since Unique can't
6628 * project) steps. This might or might not be identical to the query's final
6629 * output target.
6630 *
6631 * The main argument for keeping the sort-input tlist the same as the final
6632 * is that we avoid a separate projection node (which will be needed if
6633 * they're different, because Sort can't project). However, there are also
6634 * advantages to postponing tlist evaluation till after the Sort: it ensures
6635 * a consistent order of evaluation for any volatile functions in the tlist,
6636 * and if there's also a LIMIT, we can stop the query without ever computing
6637 * tlist functions for later rows, which is beneficial for both volatile and
6638 * expensive functions.
6639 *
6640 * Our current policy is to postpone volatile expressions till after the sort
6641 * unconditionally (assuming that that's possible, ie they are in plain tlist
6642 * columns and not ORDER BY/GROUP BY/DISTINCT columns). We also prefer to
6643 * postpone set-returning expressions, because running them beforehand would
6644 * bloat the sort dataset, and because it might cause unexpected output order
6645 * if the sort isn't stable. However there's a constraint on that: all SRFs
6646 * in the tlist should be evaluated at the same plan step, so that they can
6647 * run in sync in nodeProjectSet. So if any SRFs are in sort columns, we
6648 * mustn't postpone any SRFs. (Note that in principle that policy should
6649 * probably get applied to the group/window input targetlists too, but we
6650 * have not done that historically.) Lastly, expensive expressions are
6651 * postponed if there is a LIMIT, or if root->tuple_fraction shows that
6652 * partial evaluation of the query is possible (if neither is true, we expect
6653 * to have to evaluate the expressions for every row anyway), or if there are
6654 * any volatile or set-returning expressions (since once we've put in a
6655 * projection at all, it won't cost any more to postpone more stuff).
6656 *
6657 * Another issue that could potentially be considered here is that
6658 * evaluating tlist expressions could result in data that's either wider
6659 * or narrower than the input Vars, thus changing the volume of data that
6660 * has to go through the Sort. However, we usually have only a very bad
6661 * idea of the output width of any expression more complex than a Var,
6662 * so for now it seems too risky to try to optimize on that basis.
6663 *
6664 * Note that if we do produce a modified sort-input target, and then the
6665 * query ends up not using an explicit Sort, no particular harm is done:
6666 * we'll initially use the modified target for the preceding path nodes,
6667 * but then change them to the final target with apply_projection_to_path.
6668 * Moreover, in such a case the guarantees about evaluation order of
6669 * volatile functions still hold, since the rows are sorted already.
6670 *
6671 * This function has some things in common with make_group_input_target and
6672 * make_window_input_target, though the detailed rules for what to do are
6673 * different. We never flatten/postpone any grouping or ordering columns;
6674 * those are needed before the sort. If we do flatten a particular
6675 * expression, we leave Aggref and WindowFunc nodes alone, since those were
6676 * computed earlier.
6677 *
6678 * 'final_target' is the query's final target list (in PathTarget form)
6679 * 'have_postponed_srfs' is an output argument, see below
6680 *
6681 * The result is the PathTarget to be computed by the plan node immediately
6682 * below the Sort step (and the Distinct step, if any). This will be
6683 * exactly final_target if we decide a projection step wouldn't be helpful.
6684 *
6685 * In addition, *have_postponed_srfs is set to true if we choose to postpone
6686 * any set-returning functions to after the Sort.
6687 */
6688static PathTarget *
6691 bool *have_postponed_srfs)
6692{
6693 Query *parse = root->parse;
6695 int ncols;
6696 bool *col_is_srf;
6697 bool *postpone_col;
6698 bool have_srf;
6699 bool have_volatile;
6700 bool have_expensive;
6701 bool have_srf_sortcols;
6702 bool postpone_srfs;
6705 int i;
6706 ListCell *lc;
6707
6708 /* Shouldn't get here unless query has ORDER BY */
6709 Assert(parse->sortClause);
6710
6711 *have_postponed_srfs = false; /* default result */
6712
6713 /* Inspect tlist and collect per-column information */
6714 ncols = list_length(final_target->exprs);
6715 col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
6716 postpone_col = (bool *) palloc0(ncols * sizeof(bool));
6718
6719 i = 0;
6720 foreach(lc, final_target->exprs)
6721 {
6722 Expr *expr = (Expr *) lfirst(lc);
6723
6724 /*
6725 * If the column has a sortgroupref, assume it has to be evaluated
6726 * before sorting. Generally such columns would be ORDER BY, GROUP
6727 * BY, etc targets. One exception is columns that were removed from
6728 * GROUP BY by remove_useless_groupby_columns() ... but those would
6729 * only be Vars anyway. There don't seem to be any cases where it
6730 * would be worth the trouble to double-check.
6731 */
6733 {
6734 /*
6735 * Check for SRF or volatile functions. Check the SRF case first
6736 * because we must know whether we have any postponed SRFs.
6737 */
6738 if (parse->hasTargetSRFs &&
6739 expression_returns_set((Node *) expr))
6740 {
6741 /* We'll decide below whether these are postponable */
6742 col_is_srf[i] = true;
6743 have_srf = true;
6744 }
6745 else if (contain_volatile_functions((Node *) expr))
6746 {
6747 /* Unconditionally postpone */
6748 postpone_col[i] = true;
6749 have_volatile = true;
6750 }
6751 else
6752 {
6753 /*
6754 * Else check the cost. XXX it's annoying to have to do this
6755 * when set_pathtarget_cost_width() just did it. Refactor to
6756 * allow sharing the work?
6757 */
6758 QualCost cost;
6759
6760 cost_qual_eval_node(&cost, (Node *) expr, root);
6761
6762 /*
6763 * We arbitrarily define "expensive" as "more than 10X
6764 * cpu_operator_cost". Note this will take in any PL function
6765 * with default cost.
6766 */
6767 if (cost.per_tuple > 10 * cpu_operator_cost)
6768 {
6769 postpone_col[i] = true;
6770 have_expensive = true;
6771 }
6772 }
6773 }
6774 else
6775 {
6776 /* For sortgroupref cols, just check if any contain SRFs */
6777 if (!have_srf_sortcols &&
6778 parse->hasTargetSRFs &&
6779 expression_returns_set((Node *) expr))
6780 have_srf_sortcols = true;
6781 }
6782
6783 i++;
6784 }
6785
6786 /*
6787 * We can postpone SRFs if we have some but none are in sortgroupref cols.
6788 */
6790
6791 /*
6792 * If we don't need a post-sort projection, just return final_target.
6793 */
6794 if (!(postpone_srfs || have_volatile ||
6795 (have_expensive &&
6796 (parse->limitCount || root->tuple_fraction > 0))))
6797 return final_target;
6798
6799 /*
6800 * Report whether the post-sort projection will contain set-returning
6801 * functions. This is important because it affects whether the Sort can
6802 * rely on the query's LIMIT (if any) to bound the number of rows it needs
6803 * to return.
6804 */
6806
6807 /*
6808 * Construct the sort-input target, taking all non-postponable columns and
6809 * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
6810 * the postponable ones.
6811 */
6814
6815 i = 0;
6816 foreach(lc, final_target->exprs)
6817 {
6818 Expr *expr = (Expr *) lfirst(lc);
6819
6820 if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
6822 else
6825
6826 i++;
6827 }
6828
6829 /*
6830 * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
6831 * postponable columns, and add them to the sort-input target if not
6832 * already present. (Some might be there already.) We mustn't
6833 * deconstruct Aggrefs or WindowFuncs here, since the projection node
6834 * would be unable to recompute them.
6835 */
6841
6842 /* clean up cruft */
6845
6846 /* XXX this represents even more redundant cost calculation ... */
6848}
6849
6850/*
6851 * get_cheapest_fractional_path
6852 * Find the cheapest path for retrieving a specified fraction of all
6853 * the tuples expected to be returned by the given relation.
6854 *
6855 * Do not consider parameterized paths. If the caller needs a path for upper
6856 * rel, it can't have parameterized paths. If the caller needs an append
6857 * subpath, it could become limited by the treatment of similar
6858 * parameterization of all the subpaths.
6859 *
6860 * We interpret tuple_fraction the same way as grouping_planner.
6861 *
6862 * We assume set_cheapest() has been run on the given rel.
6863 */
6864Path *
6865get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
6866{
6868 ListCell *l;
6869
6870 /* If all tuples will be retrieved, just return the cheapest-total path */
6871 if (tuple_fraction <= 0.0)
6872 return best_path;
6873
6874 /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
6875 if (tuple_fraction >= 1.0 && best_path->rows > 0)
6876 tuple_fraction /= best_path->rows;
6877
6878 foreach(l, rel->pathlist)
6879 {
6880 Path *path = (Path *) lfirst(l);
6881
6882 if (path->param_info)
6883 continue;
6884
6885 if (path == rel->cheapest_total_path ||
6886 compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
6887 continue;
6888
6889 best_path = path;
6890 }
6891
6892 return best_path;
6893}
6894
6895/*
6896 * adjust_paths_for_srfs
6897 * Fix up the Paths of the given upperrel to handle tSRFs properly.
6898 *
6899 * The executor can only handle set-returning functions that appear at the
6900 * top level of the targetlist of a ProjectSet plan node. If we have any SRFs
6901 * that are not at top level, we need to split up the evaluation into multiple
6902 * plan levels in which each level satisfies this constraint. This function
6903 * modifies each Path of an upperrel that (might) compute any SRFs in its
6904 * output tlist to insert appropriate projection steps.
6905 *
6906 * The given targets and targets_contain_srfs lists are from
6907 * split_pathtarget_at_srfs(). We assume the existing Paths emit the first
6908 * target in targets.
6909 */
6910static void
6912 List *targets, List *targets_contain_srfs)
6913{
6914 ListCell *lc;
6915
6918
6919 /* If no SRFs appear at this plan level, nothing to do */
6920 if (list_length(targets) == 1)
6921 return;
6922
6923 /*
6924 * Stack SRF-evaluation nodes atop each path for the rel.
6925 *
6926 * In principle we should re-run set_cheapest() here to identify the
6927 * cheapest path, but it seems unlikely that adding the same tlist eval
6928 * costs to all the paths would change that, so we don't bother. Instead,
6929 * just assume that the cheapest-startup and cheapest-total paths remain
6930 * so. (There should be no parameterized paths anymore, so we needn't
6931 * worry about updating cheapest_parameterized_paths.)
6932 */
6933 foreach(lc, rel->pathlist)
6934 {
6935 Path *subpath = (Path *) lfirst(lc);
6936 Path *newpath = subpath;
6937 ListCell *lc1,
6938 *lc2;
6939
6940 Assert(subpath->param_info == NULL);
6942 {
6944 bool contains_srfs = (bool) lfirst_int(lc2);
6945
6946 /* If this level doesn't contain SRFs, do regular projection */
6947 if (contains_srfs)
6949 rel,
6950 newpath,
6951 thistarget);
6952 else
6954 rel,
6955 newpath,
6956 thistarget);
6957 }
6958 lfirst(lc) = newpath;
6959 if (subpath == rel->cheapest_startup_path)
6961 if (subpath == rel->cheapest_total_path)
6963 }
6964
6965 /* Likewise for partial paths, if any */
6966 foreach(lc, rel->partial_pathlist)
6967 {
6968 Path *subpath = (Path *) lfirst(lc);
6969 Path *newpath = subpath;
6970 ListCell *lc1,
6971 *lc2;
6972
6973 Assert(subpath->param_info == NULL);
6975 {
6977 bool contains_srfs = (bool) lfirst_int(lc2);
6978
6979 /* If this level doesn't contain SRFs, do regular projection */
6980 if (contains_srfs)
6982 rel,
6983 newpath,
6984 thistarget);
6985 else
6986 {
6987 /* avoid apply_projection_to_path, in case of multiple refs */
6989 rel,
6990 newpath,
6991 thistarget);
6992 }
6993 }
6994 lfirst(lc) = newpath;
6995 }
6996}
6997
6998/*
6999 * expression_planner
7000 * Perform planner's transformations on a standalone expression.
7001 *
7002 * Various utility commands need to evaluate expressions that are not part
7003 * of a plannable query. They can do so using the executor's regular
7004 * expression-execution machinery, but first the expression has to be fed
7005 * through here to transform it from parser output to something executable.
7006 *
7007 * Currently, we disallow sublinks in standalone expressions, so there's no
7008 * real "planning" involved here. (That might not always be true though.)
7009 * What we must do is run eval_const_expressions to ensure that any function
7010 * calls are converted to positional notation and function default arguments
7011 * get inserted. The fact that constant subexpressions get simplified is a
7012 * side-effect that is useful when the expression will get evaluated more than
7013 * once. Also, we must fix operator function IDs.
7014 *
7015 * This does not return any information about dependencies of the expression.
7016 * Hence callers should use the results only for the duration of the current
7017 * query. Callers that would like to cache the results for longer should use
7018 * expression_planner_with_deps, probably via the plancache.
7019 *
7020 * Note: this must not make any damaging changes to the passed-in expression
7021 * tree. (It would actually be okay to apply fix_opfuncids to it, but since
7022 * we first do an expression_tree_mutator-based walk, what is returned will
7023 * be a new node tree.) The result is constructed in the current memory
7024 * context; beware that this can leak a lot of additional stuff there, too.
7025 */
7026Expr *
7028{
7029 Node *result;
7030
7031 /*
7032 * Convert named-argument function calls, insert default arguments and
7033 * simplify constant subexprs
7034 */
7036
7037 /* Fill in opfuncid values if missing */
7039
7040 return (Expr *) result;
7041}
7042
7043/*
7044 * expression_planner_with_deps
7045 * Perform planner's transformations on a standalone expression,
7046 * returning expression dependency information along with the result.
7047 *
7048 * This is identical to expression_planner() except that it also returns
7049 * information about possible dependencies of the expression, ie identities of
7050 * objects whose definitions affect the result. As in a PlannedStmt, these
7051 * are expressed as a list of relation Oids and a list of PlanInvalItems.
7052 */
7053Expr *
7055 List **relationOids,
7056 List **invalItems)
7057{
7058 Node *result;
7059 PlannerGlobal glob;
7061
7062 /* Make up dummy planner state so we can use setrefs machinery */
7063 MemSet(&glob, 0, sizeof(glob));
7064 glob.type = T_PlannerGlobal;
7065 glob.relationOids = NIL;
7066 glob.invalItems = NIL;
7067
7068 MemSet(&root, 0, sizeof(root));
7069 root.type = T_PlannerInfo;
7070 root.glob = &glob;
7071
7072 /*
7073 * Convert named-argument function calls, insert default arguments and
7074 * simplify constant subexprs. Collect identities of inlined functions
7075 * and elided domains, too.
7076 */
7077 result = eval_const_expressions(&root, (Node *) expr);
7078
7079 /* Fill in opfuncid values if missing */
7081
7082 /*
7083 * Now walk the finished expression to find anything else we ought to
7084 * record as an expression dependency.
7085 */
7087
7088 *relationOids = glob.relationOids;
7089 *invalItems = glob.invalItems;
7090
7091 return (Expr *) result;
7092}
7093
7094
7095/*
7096 * plan_cluster_use_sort
7097 * Use the planner to decide how CLUSTER should implement sorting
7098 *
7099 * tableOid is the OID of a table to be clustered on its index indexOid
7100 * (which is already known to be a btree index). Decide whether it's
7101 * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
7102 * Return true to use sorting, false to use an indexscan.
7103 *
7104 * Note: caller had better already hold some type of lock on the table.
7105 */
7106bool
7107plan_cluster_use_sort(Oid tableOid, Oid indexOid)
7108{
7110 Query *query;
7111 PlannerGlobal *glob;
7113 RelOptInfo *rel;
7114 IndexOptInfo *indexInfo;
7120 ListCell *lc;
7121
7122 /* We can short-circuit the cost comparison if indexscans are disabled */
7123 if (!enable_indexscan)
7124 return true; /* use sort */
7125
7126 /* Set up mostly-dummy planner state */
7127 query = makeNode(Query);
7128 query->commandType = CMD_SELECT;
7129
7130 glob = makeNode(PlannerGlobal);
7131
7133 root->parse = query;
7134 root->glob = glob;
7135 root->query_level = 1;
7136 root->planner_cxt = CurrentMemoryContext;
7137 root->wt_param_id = -1;
7138 root->join_domains = list_make1(makeNode(JoinDomain));
7139
7140 /* Build a minimal RTE for the rel */
7142 rte->rtekind = RTE_RELATION;
7143 rte->relid = tableOid;
7144 rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
7145 rte->rellockmode = AccessShareLock;
7146 rte->lateral = false;
7147 rte->inh = false;
7148 rte->inFromCl = true;
7149 query->rtable = list_make1(rte);
7150 addRTEPermissionInfo(&query->rteperminfos, rte);
7151
7152 /* Set up RTE/RelOptInfo arrays */
7154
7155 /* Build RelOptInfo */
7156 rel = build_simple_rel(root, 1, NULL);
7157
7158 /* Locate IndexOptInfo for the target index */
7159 indexInfo = NULL;
7160 foreach(lc, rel->indexlist)
7161 {
7162 indexInfo = lfirst_node(IndexOptInfo, lc);
7163 if (indexInfo->indexoid == indexOid)
7164 break;
7165 }
7166
7167 /*
7168 * It's possible that get_relation_info did not generate an IndexOptInfo
7169 * for the desired index; this could happen if it's not yet reached its
7170 * indcheckxmin usability horizon, or if it's a system index and we're
7171 * ignoring system indexes. In such cases we should tell CLUSTER to not
7172 * trust the index contents but use seqscan-and-sort.
7173 */
7174 if (lc == NULL) /* not in the list? */
7175 return true; /* use sort */
7176
7177 /*
7178 * Rather than doing all the pushups that would be needed to use
7179 * set_baserel_size_estimates, just do a quick hack for rows and width.
7180 */
7181 rel->rows = rel->tuples;
7182 rel->reltarget->width = get_relation_data_width(tableOid, NULL);
7183
7184 root->total_table_pages = rel->pages;
7185
7186 /*
7187 * Determine eval cost of the index expressions, if any. We need to
7188 * charge twice that amount for each tuple comparison that happens during
7189 * the sort, since tuplesort.c will have to re-evaluate the index
7190 * expressions each time. (XXX that's pretty inefficient...)
7191 */
7192 cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
7193 comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
7194
7195 /* Estimate the cost of seq scan + sort */
7198 seqScanPath->disabled_nodes,
7199 seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
7201
7202 /* Estimate the cost of index scan */
7204 NIL, NIL, NIL, NIL,
7205 ForwardScanDirection, false,
7206 NULL, 1.0, false);
7207
7208 return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
7209}
7210
7211/*
7212 * plan_create_index_workers
7213 * Use the planner to decide how many parallel worker processes
7214 * CREATE INDEX should request for use
7215 *
7216 * tableOid is the table on which the index is to be built. indexOid is the
7217 * OID of an index to be created or reindexed (which must be an index with
7218 * support for parallel builds - currently btree, GIN, or BRIN).
7219 *
7220 * Return value is the number of parallel worker processes to request. It
7221 * may be unsafe to proceed if this is 0. Note that this does not include the
7222 * leader participating as a worker (value is always a number of parallel
7223 * worker processes).
7224 *
7225 * Note: caller had better already hold some type of lock on the table and
7226 * index.
7227 */
7228int
7230{
7232 Query *query;
7233 PlannerGlobal *glob;
7235 Relation heap;
7237 RelOptInfo *rel;
7238 int parallel_workers;
7240 double reltuples;
7241 double allvisfrac;
7242
7243 /*
7244 * We don't allow performing parallel operation in standalone backend or
7245 * when parallelism is disabled.
7246 */
7248 return 0;
7249
7250 /* Set up largely-dummy planner state */
7251 query = makeNode(Query);
7252 query->commandType = CMD_SELECT;
7253
7254 glob = makeNode(PlannerGlobal);
7255
7257 root->parse = query;
7258 root->glob = glob;
7259 root->query_level = 1;
7260 root->planner_cxt = CurrentMemoryContext;
7261 root->wt_param_id = -1;
7262 root->join_domains = list_make1(makeNode(JoinDomain));
7263
7264 /*
7265 * Build a minimal RTE.
7266 *
7267 * Mark the RTE with inh = true. This is a kludge to prevent
7268 * get_relation_info() from fetching index info, which is necessary
7269 * because it does not expect that any IndexOptInfo is currently
7270 * undergoing REINDEX.
7271 */
7273 rte->rtekind = RTE_RELATION;
7274 rte->relid = tableOid;
7275 rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
7276 rte->rellockmode = AccessShareLock;
7277 rte->lateral = false;
7278 rte->inh = true;
7279 rte->inFromCl = true;
7280 query->rtable = list_make1(rte);
7281 addRTEPermissionInfo(&query->rteperminfos, rte);
7282
7283 /* Set up RTE/RelOptInfo arrays */
7285
7286 /* Build RelOptInfo */
7287 rel = build_simple_rel(root, 1, NULL);
7288
7289 /* Rels are assumed already locked by the caller */
7290 heap = table_open(tableOid, NoLock);
7291 index = index_open(indexOid, NoLock);
7292
7293 /*
7294 * Determine if it's safe to proceed.
7295 *
7296 * Currently, parallel workers can't access the leader's temporary tables.
7297 * Furthermore, any index predicate or index expressions must be parallel
7298 * safe.
7299 */
7300 if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
7303 {
7304 parallel_workers = 0;
7305 goto done;
7306 }
7307
7308 /*
7309 * If parallel_workers storage parameter is set for the table, accept that
7310 * as the number of parallel worker processes to launch (though still cap
7311 * at max_parallel_maintenance_workers). Note that we deliberately do not
7312 * consider any other factor when parallel_workers is set. (e.g., memory
7313 * use by workers.)
7314 */
7315 if (rel->rel_parallel_workers != -1)
7316 {
7317 parallel_workers = Min(rel->rel_parallel_workers,
7319 goto done;
7320 }
7321
7322 /*
7323 * Estimate heap relation size ourselves, since rel->pages cannot be
7324 * trusted (heap RTE was marked as inheritance parent)
7325 */
7326 estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
7327
7328 /*
7329 * Determine number of workers to scan the heap relation using generic
7330 * model
7331 */
7332 parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
7334
7335 /*
7336 * Cap workers based on available maintenance_work_mem as needed.
7337 *
7338 * Note that each tuplesort participant receives an even share of the
7339 * total maintenance_work_mem budget. Aim to leave participants
7340 * (including the leader as a participant) with no less than 32MB of
7341 * memory. This leaves cases where maintenance_work_mem is set to 64MB
7342 * immediately past the threshold of being capable of launching a single
7343 * parallel worker to sort.
7344 */
7345 while (parallel_workers > 0 &&
7346 maintenance_work_mem / (parallel_workers + 1) < 32 * 1024)
7347 parallel_workers--;
7348
7349done:
7351 table_close(heap, NoLock);
7352
7353 return parallel_workers;
7354}
7355
7356/*
7357 * add_paths_to_grouping_rel
7358 *
7359 * Add non-partial paths to grouping relation.
7360 */
7361static void
7363 RelOptInfo *grouped_rel,
7367 GroupPathExtraData *extra)
7368{
7369 Query *parse = root->parse;
7370 Path *cheapest_path = input_rel->cheapest_total_path;
7372 ListCell *lc;
7373 bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7374 bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7375 List *havingQual = (List *) extra->havingQual;
7376 AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7377 double dNumGroups = 0;
7378 double dNumFinalGroups = 0;
7379
7380 /*
7381 * Estimate number of groups for non-split aggregation.
7382 */
7384 cheapest_path->rows,
7385 gd,
7386 extra->targetList);
7387
7389 {
7391 partially_grouped_rel->cheapest_total_path;
7392
7393 /*
7394 * Estimate number of groups for final phase of partial aggregation.
7395 */
7399 gd,
7400 extra->targetList);
7401 }
7402
7403 if (can_sort)
7404 {
7405 /*
7406 * Use any available suitably-sorted path as input, and also consider
7407 * sorting the cheapest-total path and incremental sort on any paths
7408 * with presorted keys.
7409 */
7410 foreach(lc, input_rel->pathlist)
7411 {
7412 ListCell *lc2;
7413 Path *path = (Path *) lfirst(lc);
7414 Path *path_save = path;
7416
7417 /* generate alternative group orderings that might be useful */
7419
7421
7422 foreach(lc2, pathkey_orderings)
7423 {
7425
7426 /* restore the path (we replace it in the loop) */
7427 path = path_save;
7428
7429 path = make_ordered_path(root,
7430 grouped_rel,
7431 path,
7433 info->pathkeys,
7434 -1.0);
7435 if (path == NULL)
7436 continue;
7437
7438 /* Now decide what to stick atop it */
7439 if (parse->groupingSets)
7440 {
7441 consider_groupingsets_paths(root, grouped_rel,
7442 path, true, can_hash,
7444 }
7445 else if (parse->hasAggs)
7446 {
7447 /*
7448 * We have aggregation, possibly with plain GROUP BY. Make
7449 * an AggPath.
7450 */
7451 add_path(grouped_rel, (Path *)
7453 grouped_rel,
7454 path,
7455 grouped_rel->reltarget,
7456 parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7458 info->clauses,
7459 havingQual,
7460 agg_costs,
7461 dNumGroups));
7462 }
7463 else if (parse->groupClause)
7464 {
7465 /*
7466 * We have GROUP BY without aggregation or grouping sets.
7467 * Make a GroupPath.
7468 */
7469 add_path(grouped_rel, (Path *)
7471 grouped_rel,
7472 path,
7473 info->clauses,
7474 havingQual,
7475 dNumGroups));
7476 }
7477 else
7478 {
7479 /* Other cases should have been handled above */
7480 Assert(false);
7481 }
7482 }
7483 }
7484
7485 /*
7486 * Instead of operating directly on the input relation, we can
7487 * consider finalizing a partially aggregated path.
7488 */
7490 {
7491 foreach(lc, partially_grouped_rel->pathlist)
7492 {
7493 ListCell *lc2;
7494 Path *path = (Path *) lfirst(lc);
7495 Path *path_save = path;
7497
7498 /* generate alternative group orderings that might be useful */
7500
7502
7503 /* process all potentially interesting grouping reorderings */
7504 foreach(lc2, pathkey_orderings)
7505 {
7507
7508 /* restore the path (we replace it in the loop) */
7509 path = path_save;
7510
7511 path = make_ordered_path(root,
7512 grouped_rel,
7513 path,
7515 info->pathkeys,
7516 -1.0);
7517
7518 if (path == NULL)
7519 continue;
7520
7521 if (parse->hasAggs)
7522 add_path(grouped_rel, (Path *)
7524 grouped_rel,
7525 path,
7526 grouped_rel->reltarget,
7527 parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7529 info->clauses,
7530 havingQual,
7531 agg_final_costs,
7533 else
7534 add_path(grouped_rel, (Path *)
7536 grouped_rel,
7537 path,
7538 info->clauses,
7539 havingQual,
7541
7542 }
7543 }
7544 }
7545 }
7546
7547 if (can_hash)
7548 {
7549 if (parse->groupingSets)
7550 {
7551 /*
7552 * Try for a hash-only groupingsets path over unsorted input.
7553 */
7554 consider_groupingsets_paths(root, grouped_rel,
7555 cheapest_path, false, true,
7557 }
7558 else
7559 {
7560 /*
7561 * Generate a HashAgg Path. We just need an Agg over the
7562 * cheapest-total input path, since input order won't matter.
7563 */
7564 add_path(grouped_rel, (Path *)
7565 create_agg_path(root, grouped_rel,
7567 grouped_rel->reltarget,
7568 AGG_HASHED,
7570 root->processed_groupClause,
7571 havingQual,
7572 agg_costs,
7573 dNumGroups));
7574 }
7575
7576 /*
7577 * Generate a Finalize HashAgg Path atop of the cheapest partially
7578 * grouped path, assuming there is one
7579 */
7581 {
7582 add_path(grouped_rel, (Path *)
7584 grouped_rel,
7586 grouped_rel->reltarget,
7587 AGG_HASHED,
7589 root->processed_groupClause,
7590 havingQual,
7591 agg_final_costs,
7593 }
7594 }
7595
7596 /*
7597 * When partitionwise aggregate is used, we might have fully aggregated
7598 * paths in the partial pathlist, because add_paths_to_append_rel() will
7599 * consider a path for grouped_rel consisting of a Parallel Append of
7600 * non-partial paths from each child.
7601 */
7602 if (grouped_rel->partial_pathlist != NIL)
7603 gather_grouping_paths(root, grouped_rel);
7604}
7605
7606/*
7607 * create_partial_grouping_paths
7608 *
7609 * Create a new upper relation representing the result of partial aggregation
7610 * and populate it with appropriate paths. Note that we don't finalize the
7611 * lists of paths here, so the caller can add additional partial or non-partial
7612 * paths and must afterward call gather_grouping_paths and set_cheapest on
7613 * the returned upper relation.
7614 *
7615 * All paths for this new upper relation -- both partial and non-partial --
7616 * have been partially aggregated but require a subsequent FinalizeAggregate
7617 * step.
7618 *
7619 * NB: This function is allowed to return NULL if it determines that there is
7620 * no real need to create a new RelOptInfo.
7621 */
7622static RelOptInfo *
7624 RelOptInfo *grouped_rel,
7627 GroupPathExtraData *extra,
7628 bool force_rel_creation)
7629{
7630 Query *parse = root->parse;
7633 AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
7634 AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7636 Path *cheapest_total_path = NULL;
7637 double dNumPartialGroups = 0;
7638 double dNumPartialPartialGroups = 0;
7639 ListCell *lc;
7640 bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7641 bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7642
7643 /*
7644 * Check whether any partially aggregated paths have been generated
7645 * through eager aggregation.
7646 */
7647 if (input_rel->grouped_rel &&
7648 !IS_DUMMY_REL(input_rel->grouped_rel) &&
7649 input_rel->grouped_rel->pathlist != NIL)
7650 eager_agg_rel = input_rel->grouped_rel;
7651
7652 /*
7653 * Consider whether we should generate partially aggregated non-partial
7654 * paths. We can only do this if we have a non-partial path, and only if
7655 * the parent of the input rel is performing partial partitionwise
7656 * aggregation. (Note that extra->patype is the type of partitionwise
7657 * aggregation being used at the parent level, not this level.)
7658 */
7659 if (input_rel->pathlist != NIL &&
7661 cheapest_total_path = input_rel->cheapest_total_path;
7662
7663 /*
7664 * If parallelism is possible for grouped_rel, then we should consider
7665 * generating partially-grouped partial paths. However, if the input rel
7666 * has no partial paths, then we can't.
7667 */
7668 if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
7669 cheapest_partial_path = linitial(input_rel->partial_pathlist);
7670
7671 /*
7672 * If we can't partially aggregate partial paths, and we can't partially
7673 * aggregate non-partial paths, and no partially aggregated paths were
7674 * generated by eager aggregation, then don't bother creating the new
7675 * RelOptInfo at all, unless the caller specified force_rel_creation.
7676 */
7677 if (cheapest_total_path == NULL &&
7679 eager_agg_rel == NULL &&
7681 return NULL;
7682
7683 /*
7684 * Build a new upper relation to represent the result of partially
7685 * aggregating the rows from the input relation.
7686 */
7689 grouped_rel->relids);
7690 partially_grouped_rel->consider_parallel =
7691 grouped_rel->consider_parallel;
7692 partially_grouped_rel->pgs_mask = grouped_rel->pgs_mask;
7693 partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
7694 partially_grouped_rel->serverid = grouped_rel->serverid;
7695 partially_grouped_rel->userid = grouped_rel->userid;
7696 partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
7697 partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
7698
7699 /*
7700 * Build target list for partial aggregate paths. These paths cannot just
7701 * emit the same tlist as regular aggregate paths, because (1) we must
7702 * include Vars and Aggrefs needed in HAVING, which might not appear in
7703 * the result tlist, and (2) the Aggrefs must be set in partial mode.
7704 */
7707 extra->havingQual);
7708
7709 if (!extra->partial_costs_set)
7710 {
7711 /*
7712 * Collect statistics about aggregates for estimating costs of
7713 * performing aggregation in parallel.
7714 */
7715 MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
7716 MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
7717 if (parse->hasAggs)
7718 {
7719 /* partial phase */
7721 agg_partial_costs);
7722
7723 /* final phase */
7725 agg_final_costs);
7726 }
7727
7728 extra->partial_costs_set = true;
7729 }
7730
7731 /* Estimate number of partial groups. */
7732 if (cheapest_total_path != NULL)
7735 cheapest_total_path->rows,
7736 gd,
7737 extra->targetList);
7742 gd,
7743 extra->targetList);
7744
7745 if (can_sort && cheapest_total_path != NULL)
7746 {
7747 /* This should have been checked previously */
7748 Assert(parse->hasAggs || parse->groupClause);
7749
7750 /*
7751 * Use any available suitably-sorted path as input, and also consider
7752 * sorting the cheapest partial path.
7753 */
7754 foreach(lc, input_rel->pathlist)
7755 {
7756 ListCell *lc2;
7757 Path *path = (Path *) lfirst(lc);
7758 Path *path_save = path;
7760
7761 /* generate alternative group orderings that might be useful */
7763
7765
7766 /* process all potentially interesting grouping reorderings */
7767 foreach(lc2, pathkey_orderings)
7768 {
7770
7771 /* restore the path (we replace it in the loop) */
7772 path = path_save;
7773
7774 path = make_ordered_path(root,
7776 path,
7777 cheapest_total_path,
7778 info->pathkeys,
7779 -1.0);
7780
7781 if (path == NULL)
7782 continue;
7783
7784 if (parse->hasAggs)
7788 path,
7789 partially_grouped_rel->reltarget,
7790 parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7792 info->clauses,
7793 NIL,
7794 agg_partial_costs,
7796 else
7800 path,
7801 info->clauses,
7802 NIL,
7804 }
7805 }
7806 }
7807
7809 {
7810 /* Similar to above logic, but for partial paths. */
7811 foreach(lc, input_rel->partial_pathlist)
7812 {
7813 ListCell *lc2;
7814 Path *path = (Path *) lfirst(lc);
7815 Path *path_save = path;
7817
7818 /* generate alternative group orderings that might be useful */
7820
7822
7823 /* process all potentially interesting grouping reorderings */
7824 foreach(lc2, pathkey_orderings)
7825 {
7827
7828
7829 /* restore the path (we replace it in the loop) */
7830 path = path_save;
7831
7832 path = make_ordered_path(root,
7834 path,
7836 info->pathkeys,
7837 -1.0);
7838
7839 if (path == NULL)
7840 continue;
7841
7842 if (parse->hasAggs)
7846 path,
7847 partially_grouped_rel->reltarget,
7848 parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7850 info->clauses,
7851 NIL,
7852 agg_partial_costs,
7854 else
7858 path,
7859 info->clauses,
7860 NIL,
7862 }
7863 }
7864 }
7865
7866 /*
7867 * Add a partially-grouped HashAgg Path where possible
7868 */
7869 if (can_hash && cheapest_total_path != NULL)
7870 {
7871 /* Checked above */
7872 Assert(parse->hasAggs || parse->groupClause);
7873
7877 cheapest_total_path,
7878 partially_grouped_rel->reltarget,
7879 AGG_HASHED,
7881 root->processed_groupClause,
7882 NIL,
7883 agg_partial_costs,
7885 }
7886
7887 /*
7888 * Now add a partially-grouped HashAgg partial Path where possible
7889 */
7891 {
7896 partially_grouped_rel->reltarget,
7897 AGG_HASHED,
7899 root->processed_groupClause,
7900 NIL,
7901 agg_partial_costs,
7903 }
7904
7905 /*
7906 * Add any partially aggregated paths generated by eager aggregation to
7907 * the new upper relation after applying projection steps as needed.
7908 */
7909 if (eager_agg_rel)
7910 {
7911 /* Add the paths */
7912 foreach(lc, eager_agg_rel->pathlist)
7913 {
7914 Path *path = (Path *) lfirst(lc);
7915
7916 /* Shouldn't have any parameterized paths anymore */
7917 Assert(path->param_info == NULL);
7918
7919 path = (Path *) create_projection_path(root,
7921 path,
7922 partially_grouped_rel->reltarget);
7923
7925 }
7926
7927 /*
7928 * Likewise add the partial paths, but only if parallelism is possible
7929 * for partially_grouped_rel.
7930 */
7931 if (partially_grouped_rel->consider_parallel)
7932 {
7933 foreach(lc, eager_agg_rel->partial_pathlist)
7934 {
7935 Path *path = (Path *) lfirst(lc);
7936
7937 /* Shouldn't have any parameterized paths anymore */
7938 Assert(path->param_info == NULL);
7939
7940 path = (Path *) create_projection_path(root,
7942 path,
7943 partially_grouped_rel->reltarget);
7944
7946 }
7947 }
7948 }
7949
7950 /*
7951 * If there is an FDW that's responsible for all baserels of the query,
7952 * let it consider adding partially grouped ForeignPaths.
7953 */
7954 if (partially_grouped_rel->fdwroutine &&
7955 partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
7956 {
7957 FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
7958
7959 fdwroutine->GetForeignUpperPaths(root,
7962 extra);
7963 }
7964
7965 return partially_grouped_rel;
7966}
7967
7968/*
7969 * make_ordered_path
7970 * Return a path ordered by 'pathkeys' based on the given 'path'. May
7971 * return NULL if it doesn't make sense to generate an ordered path in
7972 * this case.
7973 */
7974static Path *
7976 Path *cheapest_path, List *pathkeys, double limit_tuples)
7977{
7978 bool is_sorted;
7979 int presorted_keys;
7980
7982 path->pathkeys,
7983 &presorted_keys);
7984
7985 if (!is_sorted)
7986 {
7987 /*
7988 * Try at least sorting the cheapest path and also try incrementally
7989 * sorting any path which is partially sorted already (no need to deal
7990 * with paths which have presorted keys when incremental sort is
7991 * disabled unless it's the cheapest input path).
7992 */
7993 if (path != cheapest_path &&
7994 (presorted_keys == 0 || !enable_incremental_sort))
7995 return NULL;
7996
7997 /*
7998 * We've no need to consider both a sort and incremental sort. We'll
7999 * just do a sort if there are no presorted keys and an incremental
8000 * sort when there are presorted keys.
8001 */
8002 if (presorted_keys == 0 || !enable_incremental_sort)
8003 path = (Path *) create_sort_path(root,
8004 rel,
8005 path,
8006 pathkeys,
8007 limit_tuples);
8008 else
8010 rel,
8011 path,
8012 pathkeys,
8013 presorted_keys,
8014 limit_tuples);
8015 }
8016
8017 return path;
8018}
8019
8020/*
8021 * Generate Gather and Gather Merge paths for a grouping relation or partial
8022 * grouping relation.
8023 *
8024 * generate_useful_gather_paths does most of the work, but we also consider a
8025 * special case: we could try sorting the data by the group_pathkeys and then
8026 * applying Gather Merge.
8027 *
8028 * NB: This function shouldn't be used for anything other than a grouped or
8029 * partially grouped relation not only because of the fact that it explicitly
8030 * references group_pathkeys but we pass "true" as the third argument to
8031 * generate_useful_gather_paths().
8032 */
8033static void
8035{
8036 ListCell *lc;
8039
8040 /*
8041 * This occurs after any partial aggregation has taken place, so trim off
8042 * any pathkeys added for ORDER BY / DISTINCT aggregates.
8043 */
8044 if (list_length(root->group_pathkeys) > root->num_groupby_pathkeys)
8045 groupby_pathkeys = list_copy_head(root->group_pathkeys,
8046 root->num_groupby_pathkeys);
8047 else
8048 groupby_pathkeys = root->group_pathkeys;
8049
8050 /* Try Gather for unordered paths and Gather Merge for ordered ones. */
8052
8054
8055 /* XXX Shouldn't this also consider the group-key-reordering? */
8056 foreach(lc, rel->partial_pathlist)
8057 {
8058 Path *path = (Path *) lfirst(lc);
8059 bool is_sorted;
8060 int presorted_keys;
8061 double total_groups;
8062
8064 path->pathkeys,
8065 &presorted_keys);
8066
8067 if (is_sorted)
8068 continue;
8069
8070 /*
8071 * Try at least sorting the cheapest path and also try incrementally
8072 * sorting any path which is partially sorted already (no need to deal
8073 * with paths which have presorted keys when incremental sort is
8074 * disabled unless it's the cheapest input path).
8075 */
8076 if (path != cheapest_partial_path &&
8077 (presorted_keys == 0 || !enable_incremental_sort))
8078 continue;
8079
8080 /*
8081 * We've no need to consider both a sort and incremental sort. We'll
8082 * just do a sort if there are no presorted keys and an incremental
8083 * sort when there are presorted keys.
8084 */
8085 if (presorted_keys == 0 || !enable_incremental_sort)
8086 path = (Path *) create_sort_path(root, rel, path,
8088 -1.0);
8089 else
8091 rel,
8092 path,
8094 presorted_keys,
8095 -1.0);
8097 path = (Path *)
8099 rel,
8100 path,
8101 rel->reltarget,
8103 NULL,
8104 &total_groups);
8105
8106 add_path(rel, path);
8107 }
8108}
8109
8110/*
8111 * can_partial_agg
8112 *
8113 * Determines whether or not partial grouping and/or aggregation is possible.
8114 * Returns true when possible, false otherwise.
8115 */
8116static bool
8118{
8119 Query *parse = root->parse;
8120
8121 if (!parse->hasAggs && parse->groupClause == NIL)
8122 {
8123 /*
8124 * We don't know how to do parallel aggregation unless we have either
8125 * some aggregates or a grouping clause.
8126 */
8127 return false;
8128 }
8129 else if (parse->groupingSets)
8130 {
8131 /* We don't know how to do grouping sets in parallel. */
8132 return false;
8133 }
8134 else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
8135 {
8136 /* Insufficient support for partial mode. */
8137 return false;
8138 }
8139
8140 /* Everything looks good. */
8141 return true;
8142}
8143
8144/*
8145 * apply_scanjoin_target_to_paths
8146 *
8147 * Adjust the final scan/join relation, and recursively all of its children,
8148 * to generate the final scan/join target. It would be more correct to model
8149 * this as a separate planning step with a new RelOptInfo at the toplevel and
8150 * for each child relation, but doing it this way is noticeably cheaper.
8151 * Maybe that problem can be solved at some point, but for now we do this.
8152 *
8153 * If tlist_same_exprs is true, then the scan/join target to be applied has
8154 * the same expressions as the existing reltarget, so we need only insert the
8155 * appropriate sortgroupref information. By avoiding the creation of
8156 * projection paths we save effort both immediately and at plan creation time.
8157 */
8158static void
8160 RelOptInfo *rel,
8164 bool tlist_same_exprs)
8165{
8168 ListCell *lc;
8169
8170 /* This recurses, so be paranoid. */
8172
8173 /*
8174 * If the rel only has Append and MergeAppend paths, we want to drop its
8175 * existing paths and generate new ones. This function would still be
8176 * correct if we kept the existing paths: we'd modify them to generate the
8177 * correct target above the partitioning Append, and then they'd compete
8178 * on cost with paths generating the target below the Append. However, in
8179 * our current cost model the latter way is always the same or cheaper
8180 * cost, so modifying the existing paths would just be useless work.
8181 * Moreover, when the cost is the same, varying roundoff errors might
8182 * sometimes allow an existing path to be picked, resulting in undesirable
8183 * cross-platform plan variations. So we drop old paths and thereby force
8184 * the work to be done below the Append.
8185 *
8186 * However, there are several cases when this optimization is not safe. If
8187 * the rel isn't partitioned, then none of the paths will be Append or
8188 * MergeAppend paths, so we should definitely not do this. If it is
8189 * partitioned but is a joinrel, it may have Append and MergeAppend paths,
8190 * but it can also have join paths that we can't afford to discard.
8191 *
8192 * Some care is needed, because we have to allow
8193 * generate_useful_gather_paths to see the old partial paths in the next
8194 * stanza. Hence, zap the main pathlist here, then allow
8195 * generate_useful_gather_paths to add path(s) to the main list, and
8196 * finally zap the partial pathlist.
8197 */
8199 rel->pathlist = NIL;
8200
8201 /*
8202 * If the scan/join target is not parallel-safe, partial paths cannot
8203 * generate it.
8204 */
8206 {
8207 /*
8208 * Since we can't generate the final scan/join target in parallel
8209 * workers, this is our last opportunity to use any partial paths that
8210 * exist; so build Gather path(s) that use them and emit whatever the
8211 * current reltarget is. We don't do this in the case where the
8212 * target is parallel-safe, since we will be able to generate superior
8213 * paths by doing it after the final scan/join target has been
8214 * applied.
8215 */
8217
8218 /* Can't use parallel query above this level. */
8219 rel->partial_pathlist = NIL;
8220 rel->consider_parallel = false;
8221 }
8222
8223 /* Finish dropping old paths for a partitioned rel, per comment above */
8225 rel->partial_pathlist = NIL;
8226
8227 /* Extract SRF-free scan/join target. */
8229
8230 /*
8231 * Apply the SRF-free scan/join target to each existing path.
8232 *
8233 * If the tlist exprs are the same, we can just inject the sortgroupref
8234 * information into the existing pathtargets. Otherwise, replace each
8235 * path with a projection path that generates the SRF-free scan/join
8236 * target. This can't change the ordering of paths within rel->pathlist,
8237 * so we just modify the list in place.
8238 */
8239 foreach(lc, rel->pathlist)
8240 {
8241 Path *subpath = (Path *) lfirst(lc);
8242
8243 /* Shouldn't have any parameterized paths anymore */
8244 Assert(subpath->param_info == NULL);
8245
8246 if (tlist_same_exprs)
8247 subpath->pathtarget->sortgrouprefs =
8248 scanjoin_target->sortgrouprefs;
8249 else
8250 {
8251 Path *newpath;
8252
8255 lfirst(lc) = newpath;
8256 }
8257 }
8258
8259 /* Likewise adjust the targets for any partial paths. */
8260 foreach(lc, rel->partial_pathlist)
8261 {
8262 Path *subpath = (Path *) lfirst(lc);
8263
8264 /* Shouldn't have any parameterized paths anymore */
8265 Assert(subpath->param_info == NULL);
8266
8267 if (tlist_same_exprs)
8268 subpath->pathtarget->sortgrouprefs =
8269 scanjoin_target->sortgrouprefs;
8270 else
8271 {
8272 Path *newpath;
8273
8276 lfirst(lc) = newpath;
8277 }
8278 }
8279
8280 /*
8281 * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
8282 * atop each existing path. (Note that this function doesn't look at the
8283 * cheapest-path fields, which is a good thing because they're bogus right
8284 * now.)
8285 */
8286 if (root->parse->hasTargetSRFs)
8290
8291 /*
8292 * Update the rel's target to be the final (with SRFs) scan/join target.
8293 * This now matches the actual output of all the paths, and we might get
8294 * confused in createplan.c if they don't agree. We must do this now so
8295 * that any append paths made in the next part will use the correct
8296 * pathtarget (cf. create_append_path).
8297 *
8298 * Note that this is also necessary if GetForeignUpperPaths() gets called
8299 * on the final scan/join relation or on any of its children, since the
8300 * FDW might look at the rel's target to create ForeignPaths.
8301 */
8303
8304 /*
8305 * If the relation is partitioned, recursively apply the scan/join target
8306 * to all partitions, and generate brand-new Append paths in which the
8307 * scan/join target is computed below the Append rather than above it.
8308 * Since Append is not projection-capable, that might save a separate
8309 * Result node, and it also is important for partitionwise aggregate.
8310 */
8312 {
8314 int i;
8315
8316 /* Adjust each partition. */
8317 i = -1;
8318 while ((i = bms_next_member(rel->live_parts, i)) >= 0)
8319 {
8320 RelOptInfo *child_rel = rel->part_rels[i];
8321 AppendRelInfo **appinfos;
8322 int nappinfos;
8324
8325 Assert(child_rel != NULL);
8326
8327 /* Dummy children can be ignored. */
8329 continue;
8330
8331 /* Translate scan/join targets for this child. */
8332 appinfos = find_appinfos_by_relids(root, child_rel->relids,
8333 &nappinfos);
8334 foreach(lc, scanjoin_targets)
8335 {
8336 PathTarget *target = lfirst_node(PathTarget, lc);
8337
8338 target = copy_pathtarget(target);
8339 target->exprs = (List *)
8341 (Node *) target->exprs,
8342 nappinfos, appinfos);
8344 target);
8345 }
8346 pfree(appinfos);
8347
8348 /* Recursion does the real work. */
8354
8355 /* Save non-dummy children for Append paths. */
8356 if (!IS_DUMMY_REL(child_rel))
8358 }
8359
8360 /* Build new paths for this relation by appending child paths. */
8362 }
8363
8364 /*
8365 * Consider generating Gather or Gather Merge paths. We must only do this
8366 * if the relation is parallel safe, and we don't do it for child rels to
8367 * avoid creating multiple Gather nodes within the same plan. We must do
8368 * this after all paths have been generated and before set_cheapest, since
8369 * one of the generated paths may turn out to be the cheapest one.
8370 */
8371 if (rel->consider_parallel && !IS_OTHER_REL(rel))
8373
8374 /*
8375 * Reassess which paths are the cheapest, now that we've potentially added
8376 * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
8377 * this relation.
8378 */
8379 set_cheapest(rel);
8380}
8381
8382/*
8383 * create_partitionwise_grouping_paths
8384 *
8385 * If the partition keys of input relation are part of the GROUP BY clause, all
8386 * the rows belonging to a given group come from a single partition. This
8387 * allows aggregation/grouping over a partitioned relation to be broken down
8388 * into aggregation/grouping on each partition. This should be no worse, and
8389 * often better, than the normal approach.
8390 *
8391 * However, if the GROUP BY clause does not contain all the partition keys,
8392 * rows from a given group may be spread across multiple partitions. In that
8393 * case, we perform partial aggregation for each group, append the results,
8394 * and then finalize aggregation. This is less certain to win than the
8395 * previous case. It may win if the PartialAggregate stage greatly reduces
8396 * the number of groups, because fewer rows will pass through the Append node.
8397 * It may lose if we have lots of small groups.
8398 */
8399static void
8402 RelOptInfo *grouped_rel,
8407 GroupPathExtraData *extra)
8408{
8411 PathTarget *target = grouped_rel->reltarget;
8412 bool partial_grouping_valid = true;
8413 int i;
8414
8418
8419 /* Add paths for partitionwise aggregation/grouping. */
8420 i = -1;
8421 while ((i = bms_next_member(input_rel->live_parts, i)) >= 0)
8422 {
8423 RelOptInfo *child_input_rel = input_rel->part_rels[i];
8425 AppendRelInfo **appinfos;
8426 int nappinfos;
8430
8432
8433 /* Dummy children can be ignored. */
8435 continue;
8436
8437 child_target = copy_pathtarget(target);
8438
8439 /*
8440 * Copy the given "extra" structure as is and then override the
8441 * members specific to this child.
8442 */
8443 memcpy(&child_extra, extra, sizeof(child_extra));
8444
8445 appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
8446 &nappinfos);
8447
8448 child_target->exprs = (List *)
8450 (Node *) target->exprs,
8451 nappinfos, appinfos);
8452
8453 /* Translate havingQual and targetList. */
8454 child_extra.havingQual = (Node *)
8456 extra->havingQual,
8457 nappinfos, appinfos);
8458 child_extra.targetList = (List *)
8460 (Node *) extra->targetList,
8461 nappinfos, appinfos);
8462
8463 /*
8464 * extra->patype was the value computed for our parent rel; patype is
8465 * the value for this relation. For the child, our value is its
8466 * parent rel's value.
8467 */
8468 child_extra.patype = patype;
8469
8470 /*
8471 * Create grouping relation to hold fully aggregated grouping and/or
8472 * aggregation paths for the child.
8473 */
8476 extra->target_parallel_safe,
8477 child_extra.havingQual);
8478
8479 /* Create grouping paths for this child relation. */
8484
8486 {
8490 }
8491 else
8492 partial_grouping_valid = false;
8493
8494 if (patype == PARTITIONWISE_AGGREGATE_FULL)
8495 {
8499 }
8500
8501 pfree(appinfos);
8502 }
8503
8504 /*
8505 * Try to create append paths for partially grouped children. For full
8506 * partitionwise aggregation, we might have paths in the partial_pathlist
8507 * if parallel aggregation is possible. For partial partitionwise
8508 * aggregation, we may have paths in both pathlist and partial_pathlist.
8509 *
8510 * NB: We must have a partially grouped path for every child in order to
8511 * generate a partially grouped path for this relation.
8512 */
8514 {
8516
8519 }
8520
8521 /* If possible, create append paths for fully grouped children. */
8522 if (patype == PARTITIONWISE_AGGREGATE_FULL)
8523 {
8525
8527 }
8528}
8529
8530/*
8531 * group_by_has_partkey
8532 *
8533 * Returns true if all the partition keys of the given relation are part of
8534 * the GROUP BY clauses, including having matching collation, false otherwise.
8535 */
8536static bool
8538 List *targetList,
8539 List *groupClause)
8540{
8541 List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
8542 int cnt = 0;
8543 int partnatts;
8544
8545 /* Input relation should be partitioned. */
8546 Assert(input_rel->part_scheme);
8547
8548 /* Rule out early, if there are no partition keys present. */
8549 if (!input_rel->partexprs)
8550 return false;
8551
8552 partnatts = input_rel->part_scheme->partnatts;
8553
8554 for (cnt = 0; cnt < partnatts; cnt++)
8555 {
8556 List *partexprs = input_rel->partexprs[cnt];
8557 ListCell *lc;
8558 bool found = false;
8559
8560 foreach(lc, partexprs)
8561 {
8562 ListCell *lg;
8563 Expr *partexpr = lfirst(lc);
8564 Oid partcoll = input_rel->part_scheme->partcollation[cnt];
8565
8566 foreach(lg, groupexprs)
8567 {
8568 Expr *groupexpr = lfirst(lg);
8570
8571 /*
8572 * Note: we can assume there is at most one RelabelType node;
8573 * eval_const_expressions() will have simplified if more than
8574 * one.
8575 */
8577 groupexpr = ((RelabelType *) groupexpr)->arg;
8578
8579 if (equal(groupexpr, partexpr))
8580 {
8581 /*
8582 * Reject a match if the grouping collation does not match
8583 * the partitioning collation.
8584 */
8587 return false;
8588
8589 found = true;
8590 break;
8591 }
8592 }
8593
8594 if (found)
8595 break;
8596 }
8597
8598 /*
8599 * If none of the partition key expressions match with any of the
8600 * GROUP BY expression, return false.
8601 */
8602 if (!found)
8603 return false;
8604 }
8605
8606 return true;
8607}
8608
8609/*
8610 * generate_setop_child_grouplist
8611 * Build a SortGroupClause list defining the sort/grouping properties
8612 * of the child of a set operation.
8613 *
8614 * This is similar to generate_setop_grouplist() but differs as the setop
8615 * child query's targetlist entries may already have a tleSortGroupRef
8616 * assigned for other purposes, such as GROUP BYs. Here we keep the
8617 * SortGroupClause list in the same order as 'op' groupClauses and just adjust
8618 * the tleSortGroupRef to reference the TargetEntry's 'ressortgroupref'. If
8619 * any of the columns in the targetlist don't match to the setop's colTypes
8620 * then we return an empty list. This may leave some TLEs with unreferenced
8621 * ressortgroupref markings, but that's harmless.
8622 */
8623static List *
8625{
8626 List *grouplist = copyObject(op->groupClauses);
8627 ListCell *lg;
8628 ListCell *lt;
8629 ListCell *ct;
8630
8632 ct = list_head(op->colTypes);
8633 foreach(lt, targetlist)
8634 {
8635 TargetEntry *tle = (TargetEntry *) lfirst(lt);
8637 Oid coltype;
8638
8639 /* resjunk columns could have sortgrouprefs. Leave these alone */
8640 if (tle->resjunk)
8641 continue;
8642
8643 /*
8644 * We expect every non-resjunk target to have a SortGroupClause and
8645 * colTypes.
8646 */
8647 Assert(lg != NULL);
8648 Assert(ct != NULL);
8650 coltype = lfirst_oid(ct);
8651
8652 /* reject if target type isn't the same as the setop target type */
8653 if (coltype != exprType((Node *) tle->expr))
8654 return NIL;
8655
8656 lg = lnext(grouplist, lg);
8657 ct = lnext(op->colTypes, ct);
8658
8659 /* assign a tleSortGroupRef, or reuse the existing one */
8660 sgc->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
8661 }
8662
8663 Assert(lg == NULL);
8664 Assert(ct == NULL);
8665
8666 return grouplist;
8667}
8668
8669/*
8670 * create_unique_paths
8671 * Build a new RelOptInfo containing Paths that represent elimination of
8672 * distinct rows from the input data. Distinct-ness is defined according to
8673 * the needs of the semijoin represented by sjinfo. If it is not possible
8674 * to identify how to make the data unique, NULL is returned.
8675 *
8676 * If used at all, this is likely to be called repeatedly on the same rel,
8677 * so we cache the result.
8678 */
8679RelOptInfo *
8681{
8682 RelOptInfo *unique_rel;
8684 List *groupClause = NIL;
8685 MemoryContext oldcontext;
8686
8687 /* Caller made a mistake if SpecialJoinInfo is the wrong one */
8688 Assert(sjinfo->jointype == JOIN_SEMI);
8689 Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
8690
8691 /* If result already cached, return it */
8692 if (rel->unique_rel)
8693 return rel->unique_rel;
8694
8695 /* If it's not possible to unique-ify, return NULL */
8696 if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
8697 return NULL;
8698
8699 /*
8700 * Punt if this is a child relation and we failed to build a unique-ified
8701 * relation for its parent. This can happen if all the RHS columns were
8702 * found to be equated to constants when unique-ifying the parent table,
8703 * leaving no columns to unique-ify.
8704 */
8705 if (IS_OTHER_REL(rel) && rel->top_parent->unique_rel == NULL)
8706 return NULL;
8707
8708 /*
8709 * When called during GEQO join planning, we are in a short-lived memory
8710 * context. We must make sure that the unique rel and any subsidiary data
8711 * structures created for a baserel survive the GEQO cycle, else the
8712 * baserel is trashed for future GEQO cycles. On the other hand, when we
8713 * are creating those for a joinrel during GEQO, we don't want them to
8714 * clutter the main planning context. Upshot is that the best solution is
8715 * to explicitly allocate memory in the same context the given RelOptInfo
8716 * is in.
8717 */
8719
8720 unique_rel = makeNode(RelOptInfo);
8721 memcpy(unique_rel, rel, sizeof(RelOptInfo));
8722
8723 /*
8724 * clear path info
8725 */
8726 unique_rel->pathlist = NIL;
8727 unique_rel->ppilist = NIL;
8728 unique_rel->partial_pathlist = NIL;
8729 unique_rel->cheapest_startup_path = NULL;
8730 unique_rel->cheapest_total_path = NULL;
8731 unique_rel->cheapest_parameterized_paths = NIL;
8732
8733 /*
8734 * Build the target list for the unique rel. We also build the pathkeys
8735 * that represent the ordering requirements for the sort-based
8736 * implementation, and the list of SortGroupClause nodes that represent
8737 * the columns to be grouped on for the hash-based implementation.
8738 *
8739 * For a child rel, we can construct these fields from those of its
8740 * parent.
8741 */
8742 if (IS_OTHER_REL(rel))
8743 {
8746
8747 parent_unique_target = rel->top_parent->unique_rel->reltarget;
8748
8750
8751 /* Translate the target expressions */
8752 child_unique_target->exprs = (List *)
8754 (Node *) parent_unique_target->exprs,
8755 rel,
8756 rel->top_parent);
8757
8758 unique_rel->reltarget = child_unique_target;
8759
8760 sortPathkeys = rel->top_parent->unique_pathkeys;
8761 groupClause = rel->top_parent->unique_groupclause;
8762 }
8763 else
8764 {
8765 List *newtlist;
8766 int nextresno;
8767 List *sortList = NIL;
8768 ListCell *lc1;
8769 ListCell *lc2;
8770
8771 /*
8772 * The values we are supposed to unique-ify may be expressions in the
8773 * variables of the input rel's targetlist. We have to add any such
8774 * expressions to the unique rel's targetlist.
8775 *
8776 * To complicate matters, some of the values to be unique-ified may be
8777 * known redundant by the EquivalenceClass machinery (e.g., because
8778 * they have been equated to constants). There is no need to compare
8779 * such values during unique-ification, and indeed we had better not
8780 * try because the Vars involved may not have propagated as high as
8781 * the semijoin's level. We use make_pathkeys_for_sortclauses to
8782 * detect such cases, which is a tad inefficient but it doesn't seem
8783 * worth building specialized infrastructure for this.
8784 */
8787
8788 forboth(lc1, sjinfo->semi_rhs_exprs, lc2, sjinfo->semi_operators)
8789 {
8790 Expr *uniqexpr = lfirst(lc1);
8792 Oid sortop;
8794 bool made_tle = false;
8795
8797 if (!tle)
8798 {
8800 nextresno,
8801 NULL,
8802 false);
8804 nextresno++;
8805 made_tle = true;
8806 }
8807
8808 /*
8809 * Try to build an ORDER BY list to sort the input compatibly. We
8810 * do this for each sortable clause even when the clauses are not
8811 * all sortable, so that we can detect clauses that are redundant
8812 * according to the pathkey machinery.
8813 */
8815 if (OidIsValid(sortop))
8816 {
8817 Oid eqop;
8819
8820 /*
8821 * The Unique node will need equality operators. Normally
8822 * these are the same as the IN clause operators, but if those
8823 * are cross-type operators then the equality operators are
8824 * the ones for the IN clause operators' RHS datatype.
8825 */
8826 eqop = get_equality_op_for_ordering_op(sortop, NULL);
8827 if (!OidIsValid(eqop)) /* shouldn't happen */
8828 elog(ERROR, "could not find equality operator for ordering operator %u",
8829 sortop);
8830
8832 sortcl->tleSortGroupRef = assignSortGroupRef(tle, newtlist);
8833 sortcl->eqop = eqop;
8834 sortcl->sortop = sortop;
8835 sortcl->reverse_sort = false;
8836 sortcl->nulls_first = false;
8837 sortcl->hashable = false; /* no need to make this accurate */
8839
8840 /*
8841 * At each step, convert the SortGroupClause list to pathkey
8842 * form. If the just-added SortGroupClause is redundant, the
8843 * result will be shorter than the SortGroupClause list.
8844 */
8846 newtlist);
8848 {
8849 /* Drop the redundant SortGroupClause */
8852 /* Undo tlist addition, if we made one */
8853 if (made_tle)
8854 {
8856 nextresno--;
8857 }
8858 /* We need not consider this clause for hashing, either */
8859 continue;
8860 }
8861 }
8862 else if (sjinfo->semi_can_btree) /* shouldn't happen */
8863 elog(ERROR, "could not find ordering operator for equality operator %u",
8864 in_oper);
8865
8866 if (sjinfo->semi_can_hash)
8867 {
8868 /* Create a GROUP BY list for the Agg node to use */
8869 Oid eq_oper;
8871
8872 /*
8873 * Get the hashable equality operators for the Agg node to
8874 * use. Normally these are the same as the IN clause
8875 * operators, but if those are cross-type operators then the
8876 * equality operators are the ones for the IN clause
8877 * operators' RHS datatype.
8878 */
8880 elog(ERROR, "could not find compatible hash operator for operator %u",
8881 in_oper);
8882
8884 groupcl->tleSortGroupRef = assignSortGroupRef(tle, newtlist);
8885 groupcl->eqop = eq_oper;
8886 groupcl->sortop = sortop;
8887 groupcl->reverse_sort = false;
8888 groupcl->nulls_first = false;
8889 groupcl->hashable = true;
8890 groupClause = lappend(groupClause, groupcl);
8891 }
8892 }
8893
8894 /*
8895 * Done building the sortPathkeys and groupClause. But the
8896 * sortPathkeys are bogus if not all the clauses were sortable.
8897 */
8898 if (!sjinfo->semi_can_btree)
8899 sortPathkeys = NIL;
8900
8901 /*
8902 * It can happen that all the RHS columns are equated to constants.
8903 * We'd have to do something special to unique-ify in that case, and
8904 * it's such an unlikely-in-the-real-world case that it's not worth
8905 * the effort. So just punt if we found no columns to unique-ify.
8906 */
8907 if (sortPathkeys == NIL && groupClause == NIL)
8908 {
8909 MemoryContextSwitchTo(oldcontext);
8910 return NULL;
8911 }
8912
8913 /* Convert the required targetlist back to PathTarget form */
8914 unique_rel->reltarget = create_pathtarget(root, newtlist);
8915 }
8916
8917 /* build unique paths based on input rel's pathlist */
8918 create_final_unique_paths(root, rel, sortPathkeys, groupClause,
8919 sjinfo, unique_rel);
8920
8921 /* build unique paths based on input rel's partial_pathlist */
8923 sjinfo, unique_rel);
8924
8925 /* Now choose the best path(s) */
8926 set_cheapest(unique_rel);
8927
8928 /*
8929 * There shouldn't be any partial paths for the unique relation;
8930 * otherwise, we won't be able to properly guarantee uniqueness.
8931 */
8932 Assert(unique_rel->partial_pathlist == NIL);
8933
8934 /* Cache the result */
8935 rel->unique_rel = unique_rel;
8937 rel->unique_groupclause = groupClause;
8938
8939 MemoryContextSwitchTo(oldcontext);
8940
8941 return unique_rel;
8942}
8943
8944/*
8945 * create_final_unique_paths
8946 * Create unique paths in 'unique_rel' based on 'input_rel' pathlist
8947 */
8948static void
8950 List *sortPathkeys, List *groupClause,
8951 SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
8952{
8953 Path *cheapest_input_path = input_rel->cheapest_total_path;
8954
8955 /* Estimate number of output rows */
8956 unique_rel->rows = estimate_num_groups(root,
8957 sjinfo->semi_rhs_exprs,
8958 cheapest_input_path->rows,
8959 NULL,
8960 NULL);
8961
8962 /* Consider sort-based implementations, if possible. */
8963 if (sjinfo->semi_can_btree)
8964 {
8965 ListCell *lc;
8966
8967 /*
8968 * Use any available suitably-sorted path as input, and also consider
8969 * sorting the cheapest-total path and incremental sort on any paths
8970 * with presorted keys.
8971 *
8972 * To save planning time, we ignore parameterized input paths unless
8973 * they are the cheapest-total path.
8974 */
8975 foreach(lc, input_rel->pathlist)
8976 {
8977 Path *input_path = (Path *) lfirst(lc);
8978 Path *path;
8979 bool is_sorted;
8980 int presorted_keys;
8981
8982 /*
8983 * Ignore parameterized paths that are not the cheapest-total
8984 * path.
8985 */
8986 if (input_path->param_info &&
8988 continue;
8989
8991 input_path->pathkeys,
8992 &presorted_keys);
8993
8994 /*
8995 * Ignore paths that are not suitably or partially sorted, unless
8996 * they are the cheapest total path (no need to deal with paths
8997 * which have presorted keys when incremental sort is disabled).
8998 */
9000 (presorted_keys == 0 || !enable_incremental_sort))
9001 continue;
9002
9003 /*
9004 * Make a separate ProjectionPath in case we need a Result node.
9005 */
9006 path = (Path *) create_projection_path(root,
9007 unique_rel,
9008 input_path,
9009 unique_rel->reltarget);
9010
9011 if (!is_sorted)
9012 {
9013 /*
9014 * We've no need to consider both a sort and incremental sort.
9015 * We'll just do a sort if there are no presorted keys and an
9016 * incremental sort when there are presorted keys.
9017 */
9018 if (presorted_keys == 0 || !enable_incremental_sort)
9019 path = (Path *) create_sort_path(root,
9020 unique_rel,
9021 path,
9023 -1.0);
9024 else
9026 unique_rel,
9027 path,
9029 presorted_keys,
9030 -1.0);
9031 }
9032
9033 path = (Path *) create_unique_path(root, unique_rel, path,
9035 unique_rel->rows);
9036
9037 add_path(unique_rel, path);
9038 }
9039 }
9040
9041 /* Consider hash-based implementation, if possible. */
9042 if (sjinfo->semi_can_hash)
9043 {
9044 Path *path;
9045
9046 /*
9047 * Make a separate ProjectionPath in case we need a Result node.
9048 */
9049 path = (Path *) create_projection_path(root,
9050 unique_rel,
9052 unique_rel->reltarget);
9053
9054 path = (Path *) create_agg_path(root,
9055 unique_rel,
9056 path,
9057 cheapest_input_path->pathtarget,
9058 AGG_HASHED,
9060 groupClause,
9061 NIL,
9062 NULL,
9063 unique_rel->rows);
9064
9065 add_path(unique_rel, path);
9066 }
9067}
9068
9069/*
9070 * create_partial_unique_paths
9071 * Create unique paths in 'unique_rel' based on 'input_rel' partial_pathlist
9072 */
9073static void
9075 List *sortPathkeys, List *groupClause,
9076 SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
9077{
9080
9081 /* nothing to do when there are no partial paths in the input rel */
9082 if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
9083 return;
9084
9085 /*
9086 * nothing to do if there's anything in the targetlist that's
9087 * parallel-restricted.
9088 */
9089 if (!is_parallel_safe(root, (Node *) unique_rel->reltarget->exprs))
9090 return;
9091
9092 cheapest_partial_path = linitial(input_rel->partial_pathlist);
9093
9096
9097 /*
9098 * clear path info
9099 */
9100 partial_unique_rel->pathlist = NIL;
9101 partial_unique_rel->ppilist = NIL;
9102 partial_unique_rel->partial_pathlist = NIL;
9103 partial_unique_rel->cheapest_startup_path = NULL;
9104 partial_unique_rel->cheapest_total_path = NULL;
9105 partial_unique_rel->cheapest_parameterized_paths = NIL;
9106
9107 /* Estimate number of output rows */
9109 sjinfo->semi_rhs_exprs,
9111 NULL,
9112 NULL);
9113 partial_unique_rel->reltarget = unique_rel->reltarget;
9114
9115 /* Consider sort-based implementations, if possible. */
9116 if (sjinfo->semi_can_btree)
9117 {
9118 ListCell *lc;
9119
9120 /*
9121 * Use any available suitably-sorted path as input, and also consider
9122 * sorting the cheapest partial path and incremental sort on any paths
9123 * with presorted keys.
9124 */
9125 foreach(lc, input_rel->partial_pathlist)
9126 {
9127 Path *input_path = (Path *) lfirst(lc);
9128 Path *path;
9129 bool is_sorted;
9130 int presorted_keys;
9131
9133 input_path->pathkeys,
9134 &presorted_keys);
9135
9136 /*
9137 * Ignore paths that are not suitably or partially sorted, unless
9138 * they are the cheapest partial path (no need to deal with paths
9139 * which have presorted keys when incremental sort is disabled).
9140 */
9142 (presorted_keys == 0 || !enable_incremental_sort))
9143 continue;
9144
9145 /*
9146 * Make a separate ProjectionPath in case we need a Result node.
9147 */
9148 path = (Path *) create_projection_path(root,
9150 input_path,
9151 partial_unique_rel->reltarget);
9152
9153 if (!is_sorted)
9154 {
9155 /*
9156 * We've no need to consider both a sort and incremental sort.
9157 * We'll just do a sort if there are no presorted keys and an
9158 * incremental sort when there are presorted keys.
9159 */
9160 if (presorted_keys == 0 || !enable_incremental_sort)
9161 path = (Path *) create_sort_path(root,
9163 path,
9165 -1.0);
9166 else
9169 path,
9171 presorted_keys,
9172 -1.0);
9173 }
9174
9178
9180 }
9181 }
9182
9183 /* Consider hash-based implementation, if possible. */
9184 if (sjinfo->semi_can_hash)
9185 {
9186 Path *path;
9187
9188 /*
9189 * Make a separate ProjectionPath in case we need a Result node.
9190 */
9191 path = (Path *) create_projection_path(root,
9194 partial_unique_rel->reltarget);
9195
9196 path = (Path *) create_agg_path(root,
9198 path,
9199 cheapest_partial_path->pathtarget,
9200 AGG_HASHED,
9202 groupClause,
9203 NIL,
9204 NULL,
9205 partial_unique_rel->rows);
9206
9208 }
9209
9210 if (partial_unique_rel->partial_pathlist != NIL)
9211 {
9214
9215 /*
9216 * Finally, create paths to unique-ify the final result. This step is
9217 * needed to remove any duplicates due to combining rows from parallel
9218 * workers.
9219 */
9221 sortPathkeys, groupClause,
9222 sjinfo, unique_rel);
9223 }
9224}
9225
9226/*
9227 * Choose a unique name for some subroot.
9228 *
9229 * Modifies glob->subplanNames to track names already used.
9230 */
9231char *
9233{
9234 unsigned n;
9235
9236 /*
9237 * If a numeric suffix is not required, then search the list of
9238 * previously-assigned names for a match. If none is found, then we can
9239 * use the provided name without modification.
9240 */
9241 if (!always_number)
9242 {
9243 bool found = false;
9244
9245 foreach_ptr(char, subplan_name, glob->subplanNames)
9246 {
9247 if (strcmp(subplan_name, name) == 0)
9248 {
9249 found = true;
9250 break;
9251 }
9252 }
9253
9254 if (!found)
9255 {
9256 /* pstrdup here is just to avoid cast-away-const */
9257 char *chosen_name = pstrdup(name);
9258
9259 glob->subplanNames = lappend(glob->subplanNames, chosen_name);
9260 return chosen_name;
9261 }
9262 }
9263
9264 /*
9265 * If a numeric suffix is required or if the un-suffixed name is already
9266 * in use, then loop until we find a positive integer that produces a
9267 * novel name.
9268 */
9269 for (n = 1; true; ++n)
9270 {
9271 char *proposed_name = psprintf("%s_%u", name, n);
9272 bool found = false;
9273
9274 foreach_ptr(char, subplan_name, glob->subplanNames)
9275 {
9277 {
9278 found = true;
9279 break;
9280 }
9281 }
9282
9283 if (!found)
9284 {
9285 glob->subplanNames = lappend(glob->subplanNames, proposed_name);
9286 return proposed_name;
9287 }
9288
9290 }
9291}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:262
@ ACLCHECK_NO_PRIV
Definition acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition allpaths.c:4794
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition allpaths.c:3388
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition allpaths.c:1416
AppendRelInfo ** find_appinfos_by_relids(PlannerInfo *root, Relids relids, int *nappinfos)
Definition appendinfo.c:809
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition appendinfo.c:201
List * adjust_inherited_attnums_multilevel(PlannerInfo *root, List *attnums, Index child_relid, Index top_parent_relid)
Definition appendinfo.c:738
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, RelOptInfo *childrel, RelOptInfo *parentrel)
Definition appendinfo.c:597
void pprint(const void *obj)
Definition print.c:54
void pgstat_report_plan_id(int64 plan_id, bool force)
BipartiteMatchState * BipartiteMatch(int u_size, int v_size, short **adjacency)
void BipartiteMatchFree(BipartiteMatchState *state)
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:346
Bitmapset * bms_make_singleton(int x)
Definition bitmapset.c:216
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:142
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1290
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1145
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition bitmapset.c:852
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:412
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:744
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
BMS_Membership bms_membership(const Bitmapset *a)
Definition bitmapset.c:765
bool bms_overlap_list(const Bitmapset *a, const List *b)
Definition bitmapset.c:601
#define bms_is_empty(a)
Definition bitmapset.h:118
@ BMS_MULTIPLE
Definition bitmapset.h:73
uint32 BlockNumber
Definition block.h:31
#define Min(x, y)
Definition c.h:1091
#define Max(x, y)
Definition c.h:1085
#define Assert(condition)
Definition c.h:943
int64_t int64
Definition c.h:621
unsigned int Index
Definition c.h:698
#define pg_fallthrough
Definition c.h:161
#define MemSet(start, val, len)
Definition c.h:1107
#define OidIsValid(objectId)
Definition c.h:858
size_t Size
Definition c.h:689
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
bool contain_agg_clause(Node *clause)
Definition clauses.c:194
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition clauses.c:2641
WindowFuncLists * find_window_functions(Node *clause, Index maxWinRef)
Definition clauses.c:244
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition clauses.c:2500
void convert_saop_to_hashed_saop(Node *node)
Definition clauses.c:2533
char max_parallel_hazard(Query *parse)
Definition clauses.c:747
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition clauses.c:766
bool contain_subplans(Node *clause)
Definition clauses.c:343
bool contain_volatile_functions(Node *clause)
Definition clauses.c:551
Oid collid
double cpu_operator_cost
Definition costsize.c:135
bool enable_partitionwise_aggregate
Definition costsize.c:161
bool enable_seqscan
Definition costsize.c:146
int max_parallel_workers_per_gather
Definition costsize.c:144
bool enable_memoize
Definition costsize.c:156
double parallel_setup_cost
Definition costsize.c:137
bool enable_gathermerge
Definition costsize.c:159
double parallel_tuple_cost
Definition costsize.c:136
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:2201
bool enable_indexonlyscan
Definition costsize.c:148
bool enable_tidscan
Definition costsize.c:150
bool enable_material
Definition costsize.c:155
bool enable_hashjoin
Definition costsize.c:158
bool enable_mergejoin
Definition costsize.c:157
double compute_gather_rows(Path *path)
Definition costsize.c:6769
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition costsize.c:4926
PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
Definition costsize.c:6511
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition costsize.c:4900
bool enable_presorted_aggregate
Definition costsize.c:165
bool enable_partitionwise_join
Definition costsize.c:160
bool enable_nestloop
Definition costsize.c:154
bool enable_bitmapscan
Definition costsize.c:149
bool enable_hashagg
Definition costsize.c:153
int32 clamp_width_est(int64 tuple_width)
Definition costsize.c:243
bool enable_indexscan
Definition costsize.c:147
bool enable_incremental_sort
Definition costsize.c:152
Plan * materialize_finished_plan(Plan *subplan)
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition createplan.c:339
Datum arg
Definition elog.c:1323
int errcode(int sqlerrcode)
Definition elog.c:875
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
bool ExecSupportsBackwardScan(Plan *node)
Definition execAmi.c:512
bool ExecCheckOneRelPerms(RTEPermissionInfo *perminfo)
Definition execMain.c:657
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_object(type)
Definition fe_memutils.h:75
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:722
FdwRoutine * GetFdwRoutineByRelId(Oid relid)
Definition foreign.c:451
int max_parallel_maintenance_workers
Definition globals.c:136
bool IsUnderPostmaster
Definition globals.c:122
int maintenance_work_mem
Definition globals.c:135
#define IsParallelWorker()
Definition parallel.h:62
void parse(int)
Definition parse.c:49
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
int b
Definition isn.c:74
int a
Definition isn.c:73
int j
Definition isn.c:78
int i
Definition isn.c:77
double jit_optimize_above_cost
Definition jit.c:42
bool jit_enabled
Definition jit.c:33
bool jit_expressions
Definition jit.c:37
bool jit_tuple_deforming
Definition jit.c:39
double jit_above_cost
Definition jit.c:40
double jit_inline_above_cost
Definition jit.c:41
#define PGJIT_OPT3
Definition jit.h:21
#define PGJIT_NONE
Definition jit.h:19
#define PGJIT_EXPR
Definition jit.h:23
#define PGJIT_DEFORM
Definition jit.h:24
#define PGJIT_INLINE
Definition jit.h:22
#define PGJIT_PERFORM
Definition jit.h:20
Bitmapset * DiscreteKnapsack(int max_weight, int num_items, int *item_weights, double *item_values)
Definition knapsack.c:51
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_difference_int(const List *list1, const List *list2)
Definition list.c:1288
List * list_concat_unique_ptr(List *list1, const List *list2)
Definition list.c:1427
List * list_concat(List *list1, const List *list2)
Definition list.c:561
List * list_copy(const List *oldlist)
Definition list.c:1573
List * lappend_int(List *list, int datum)
Definition list.c:357
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
List * lcons(void *datum, List *list)
Definition list.c:495
List * list_delete_int(List *list, int datum)
Definition list.c:891
List * list_delete_last(List *list)
Definition list.c:957
bool list_member_ptr(const List *list, const void *datum)
Definition list.c:682
void list_free(List *list)
Definition list.c:1546
bool list_member_int(const List *list, int datum)
Definition list.c:702
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
#define NoLock
Definition lockdefs.h:34
#define AccessShareLock
Definition lockdefs.h:36
@ LockWaitBlock
Definition lockoptions.h:40
LockClauseStrength
Definition lockoptions.h:22
@ LCS_FORUPDATE
Definition lockoptions.h:28
@ LCS_NONE
Definition lockoptions.h:23
@ LCS_FORSHARE
Definition lockoptions.h:26
@ LCS_FORKEYSHARE
Definition lockoptions.h:25
@ LCS_FORNOKEYUPDATE
Definition lockoptions.h:27
char * get_rel_name(Oid relid)
Definition lsyscache.c:2121
bool get_compatible_hash_operators(Oid opno, Oid *lhs_opno, Oid *rhs_opno)
Definition lsyscache.c:477
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2051
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition lsyscache.c:326
Oid get_ordering_op_for_equality_op(Oid opno, bool use_lhs_type)
Definition lsyscache.c:364
bool get_collation_isdeterministic(Oid colloid)
Definition lsyscache.c:1173
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition lsyscache.c:2773
Datum subpath(PG_FUNCTION_ARGS)
Definition ltree_op.c:311
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition makefuncs.c:289
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition makefuncs.c:701
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition makefuncs.c:350
List * make_ands_implicit(Expr *clause)
Definition makefuncs.c:810
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
void * palloc(Size size)
Definition mcxt.c:1387
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
MemoryContext GetMemoryChunkContext(void *pointer)
Definition mcxt.c:756
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
Oid exprInputCollation(const Node *expr)
Definition nodeFuncs.c:1092
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
bool expression_returns_set(Node *clause)
Definition nodeFuncs.c:768
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1859
#define expression_tree_walker(n, w, c)
Definition nodeFuncs.h:153
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3680
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition nodes.h:396
#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
@ CMD_MERGE
Definition nodes.h:279
@ CMD_DELETE
Definition nodes.h:278
@ 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_MIXED
Definition nodes.h:367
@ AGG_PLAIN
Definition nodes.h:364
#define DO_AGGSPLIT_SERIALIZE(as)
Definition nodes.h:397
AggSplit
Definition nodes.h:385
@ AGGSPLIT_FINAL_DESERIAL
Definition nodes.h:391
@ AGGSPLIT_SIMPLE
Definition nodes.h:387
@ AGGSPLIT_INITIAL_SERIAL
Definition nodes.h:389
@ LIMIT_OPTION_COUNT
Definition nodes.h:442
#define makeNode(_type_)
Definition nodes.h:161
#define castNode(_type_, nodeptr)
Definition nodes.h:182
@ JOIN_SEMI
Definition nodes.h:317
static char * errmsg
#define PVC_RECURSE_AGGREGATES
Definition optimizer.h:198
#define PVC_RECURSE_WINDOWFUNCS
Definition optimizer.h:200
@ DEBUG_PARALLEL_REGRESS
Definition optimizer.h:98
@ DEBUG_PARALLEL_OFF
Definition optimizer.h:96
#define PVC_INCLUDE_WINDOWFUNCS
Definition optimizer.h:199
#define PVC_INCLUDE_PLACEHOLDERS
Definition optimizer.h:201
#define PVC_INCLUDE_AGGREGATES
Definition optimizer.h:197
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
int assign_special_exec_param(PlannerInfo *root)
List * expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
Definition parse_agg.c:2019
Index assignSortGroupRef(TargetEntry *tle, List *tlist)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
#define CURSOR_OPT_SCROLL
#define CURSOR_OPT_FAST_PLAN
@ RTE_JOIN
@ RTE_VALUES
@ RTE_SUBQUERY
@ RTE_RESULT
@ RTE_FUNCTION
@ RTE_TABLEFUNC
@ RTE_GROUP
@ RTE_RELATION
@ OBJECT_VIEW
#define CURSOR_OPT_PARALLEL_OK
void CheckSelectLocking(Query *qry, LockClauseStrength strength)
Definition analyze.c:3745
const char * LCS_asString(LockClauseStrength strength)
Definition analyze.c:3720
#define rt_fetch(rangetable_index, rangetable)
Definition parsetree.h:31
void DestroyPartitionDirectory(PartitionDirectory pdir)
Definition partdesc.c:484
List * append_pathkeys(List *target, List *source)
Definition pathkeys.c:107
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition pathkeys.c:558
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition pathkeys.c:1336
List * make_pathkeys_for_sortclauses_extended(PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool remove_group_rtindex, bool *sortable, bool set_ec_sortref)
Definition pathkeys.c:1381
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition pathkeys.c:343
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition pathkeys.c:304
List * get_useful_group_keys_orderings(PlannerInfo *root, Path *path)
Definition pathkeys.c:467
IndexPath * create_index_path(PlannerInfo *root, IndexOptInfo *index, List *indexclauses, List *indexorderbys, List *indexorderbycols, List *pathkeys, ScanDirection indexscandir, bool indexonly, Relids required_outer, double loop_count, bool partial_path)
Definition pathnode.c:1092
ProjectSetPath * create_set_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition pathnode.c:2785
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition pathnode.c:2587
WindowAggPath * create_windowagg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *windowFuncs, List *runCondition, WindowClause *winclause, List *qual, bool topwindow)
Definition pathnode.c:3393
LockRowsPath * create_lockrows_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *rowMarks, int epqParam)
Definition pathnode.c:3630
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition pathnode.c:2696
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition pathnode.c:1026
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition pathnode.c:1813
void set_cheapest(RelOptInfo *parent_rel)
Definition pathnode.c:268
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition pathnode.c:793
LimitPath * create_limit_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, Node *limitOffset, Node *limitCount, LimitOption limitOption, int64 offset_est, int64 count_est)
Definition pathnode.c:3793
ModifyTablePath * create_modifytable_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, CmdType operation, bool canSetTag, Index nominalRelation, Index rootRelation, List *resultRelations, List *updateColnosLists, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, List *mergeActionLists, List *mergeJoinConditions, ForPortionOfExpr *forPortionOf, int epqParam)
Definition pathnode.c:3692
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition pathnode.c:123
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition pathnode.c:2855
GroupingSetsPath * create_groupingsets_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *having_qual, AggStrategy aggstrategy, List *rollups, const AggClauseCosts *agg_costs)
Definition pathnode.c:3139
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition pathnode.c:2904
GroupPath * create_group_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *groupClause, List *qual, double numGroups)
Definition pathnode.c:2948
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition pathnode.c:459
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, AppendPathInput input, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition pathnode.c:1352
UniquePath * create_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition pathnode.c:3005
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition pathnode.c:3057
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition pathnode.c:1664
#define PGS_NESTLOOP_MEMOIZE
Definition pathnodes.h:76
#define PGS_TIDSCAN
Definition pathnodes.h:70
#define PGS_FOREIGNJOIN
Definition pathnodes.h:71
#define PGS_APPEND
Definition pathnodes.h:78
#define PGS_MERGE_APPEND
Definition pathnodes.h:79
PartitionwiseAggregateType
Definition pathnodes.h:3646
@ PARTITIONWISE_AGGREGATE_PARTIAL
Definition pathnodes.h:3649
@ PARTITIONWISE_AGGREGATE_FULL
Definition pathnodes.h:3648
@ PARTITIONWISE_AGGREGATE_NONE
Definition pathnodes.h:3647
#define IS_SIMPLE_REL(rel)
Definition pathnodes.h:989
#define IS_DUMMY_REL(r)
Definition pathnodes.h:2299
#define PGS_SEQSCAN
Definition pathnodes.h:66
#define PGS_CONSIDER_INDEXONLY
Definition pathnodes.h:82
#define PGS_NESTLOOP_MATERIALIZE
Definition pathnodes.h:75
#define PGS_MERGEJOIN_PLAIN
Definition pathnodes.h:72
#define GROUPING_CAN_USE_HASH
Definition pathnodes.h:3631
#define PGS_MERGEJOIN_MATERIALIZE
Definition pathnodes.h:73
#define PGS_HASHJOIN
Definition pathnodes.h:77
#define get_pathtarget_sortgroupref(target, colno)
Definition pathnodes.h:1894
#define IS_PARTITIONED_REL(rel)
Definition pathnodes.h:1231
#define PGS_CONSIDER_NONPARTIAL
Definition pathnodes.h:84
#define PGS_BITMAPSCAN
Definition pathnodes.h:69
#define PGS_GATHER
Definition pathnodes.h:80
#define GROUPING_CAN_USE_SORT
Definition pathnodes.h:3630
#define GROUPING_CAN_PARTIAL_AGG
Definition pathnodes.h:3632
#define PGS_CONSIDER_PARTITIONWISE
Definition pathnodes.h:83
#define PGS_GATHER_MERGE
Definition pathnodes.h:81
@ UPPERREL_GROUP_AGG
Definition pathnodes.h:147
@ UPPERREL_FINAL
Definition pathnodes.h:152
@ UPPERREL_DISTINCT
Definition pathnodes.h:150
@ UPPERREL_PARTIAL_GROUP_AGG
Definition pathnodes.h:145
@ UPPERREL_ORDERED
Definition pathnodes.h:151
@ UPPERREL_WINDOW
Definition pathnodes.h:148
@ UPPERREL_PARTIAL_DISTINCT
Definition pathnodes.h:149
@ RELOPT_OTHER_UPPER_REL
Definition pathnodes.h:982
#define IS_OTHER_REL(rel)
Definition pathnodes.h:1004
#define PGS_INDEXONLYSCAN
Definition pathnodes.h:68
#define PGS_INDEXSCAN
Definition pathnodes.h:67
#define PGS_NESTLOOP_PLAIN
Definition pathnodes.h:74
@ PATHKEYS_BETTER2
Definition paths.h:221
@ PATHKEYS_BETTER1
Definition paths.h:220
@ PATHKEYS_DIFFERENT
Definition paths.h:222
@ PATHKEYS_EQUAL
Definition paths.h:219
#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 linitial_node(type, l)
Definition pg_list.h:181
#define NIL
Definition pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
#define foreach_current_index(var_or_cell)
Definition pg_list.h:435
#define lfirst_int(lc)
Definition pg_list.h:173
#define list_make1(x1)
Definition pg_list.h:244
#define linitial_int(l)
Definition pg_list.h:179
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition pg_list.h:595
#define for_each_cell(cell, lst, initcell)
Definition pg_list.h:470
#define for_each_from(cell, lst, N)
Definition pg_list.h:446
static void * list_nth(const List *list, int n)
Definition pg_list.h:331
#define linitial(l)
Definition pg_list.h:178
#define foreach_node(type, var, lst)
Definition pg_list.h:528
static ListCell * list_head(const List *l)
Definition pg_list.h:128
#define foreach_oid(var, lst)
Definition pg_list.h:503
#define list_nth_node(type, list, n)
Definition pg_list.h:359
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:375
#define list_make1_int(x1)
Definition pg_list.h:259
#define lfirst_oid(lc)
Definition pg_list.h:174
static int list_cell_number(const List *l, const ListCell *c)
Definition pg_list.h:365
#define llast_node(type, l)
Definition pg_list.h:202
static int scale
Definition pgbench.c:182
void preprocess_minmax_aggregates(PlannerInfo *root)
Definition planagg.c:74
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition plancat.c:1305
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition plancat.c:1472
RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra)
Definition planmain.c:54
#define DEFAULT_CURSOR_TUPLE_FRACTION
Definition planmain.h:21
#define EXPRKIND_TABLEFUNC_LATERAL
Definition planner.c:99
static RelOptInfo * create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *distinct_rel)
Definition planner.c:5323
static List * postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
Definition planner.c:6061
static PathTarget * make_partial_grouping_target(PlannerInfo *root, PathTarget *grouping_target, Node *havingQual)
Definition planner.c:5923
Expr * expression_planner_with_deps(Expr *expr, List **relationOids, List **invalItems)
Definition planner.c:7054
#define EXPRKIND_TARGET
Definition planner.c:88
#define EXPRKIND_APPINFO
Definition planner.c:94
static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
Definition planner.c:8034
static void preprocess_rowmarks(PlannerInfo *root)
Definition planner.c:2686
#define EXPRKIND_TABLESAMPLE
Definition planner.c:96
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, PlannerInfo *parent_root, PlannerInfo *alternative_root, bool hasRecursion, double tuple_fraction, SetOperationStmt *setops)
Definition planner.c:775
static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra)
Definition planner.c:7362
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition planner.c:333
static void create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel)
Definition planner.c:4257
char * choose_plan_name(PlannerGlobal *glob, const char *name, bool always_number)
Definition planner.c:9232
#define EXPRKIND_GROUPEXPR
Definition planner.c:100
planner_hook_type planner_hook
Definition planner.c:74
double cursor_tuple_fraction
Definition planner.c:68
static bool is_degenerate_grouping(PlannerInfo *root)
Definition planner.c:4236
planner_shutdown_hook_type planner_shutdown_hook
Definition planner.c:80
bool plan_cluster_use_sort(Oid tableOid, Oid indexOid)
Definition planner.c:7107
static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
Definition planner.c:1509
int plan_create_index_workers(Oid tableOid, Oid indexOid)
Definition planner.c:7229
#define EXPRKIND_PHV
Definition planner.c:95
#define EXPRKIND_RTFUNC_LATERAL
Definition planner.c:90
#define EXPRKIND_VALUES_LATERAL
Definition planner.c:92
static void create_ordinary_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, GroupPathExtraData *extra, RelOptInfo **partially_grouped_rel_p)
Definition planner.c:4320
RelOptInfo * create_unique_paths(PlannerInfo *root, RelOptInfo *rel, SpecialJoinInfo *sjinfo)
Definition planner.c:8680
#define EXPRKIND_LIMIT
Definition planner.c:93
#define EXPRKIND_VALUES
Definition planner.c:91
static bool can_partial_agg(PlannerInfo *root)
Definition planner.c:8117
static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est)
Definition planner.c:2864
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition planner.c:6865
Expr * preprocess_phv_expression(PlannerInfo *root, Expr *expr)
Definition planner.c:1688
static List * get_useful_pathkeys_for_distinct(PlannerInfo *root, List *needed_pathkeys, List *path_pathkeys)
Definition planner.c:5503
planner_setup_hook_type planner_setup_hook
Definition planner.c:77
bool parallel_leader_participation
Definition planner.c:70
static PathTarget * make_window_input_target(PlannerInfo *root, PathTarget *final_target, List *activeWindows)
Definition planner.c:6441
static Bitmapset * find_having_collation_conflicts(Query *parse, Index group_rtindex)
Definition planner.c:1558
static void apply_scanjoin_target_to_paths(PlannerInfo *root, RelOptInfo *rel, List *scanjoin_targets, List *scanjoin_targets_contain_srfs, bool scanjoin_target_parallel_safe, bool tlist_same_exprs)
Definition planner.c:8159
static RelOptInfo * create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target)
Definition planner.c:5070
static void optimize_window_clauses(PlannerInfo *root, WindowFuncLists *wflists)
Definition planner.c:6098
RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength)
Definition planner.c:2798
static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs)
Definition planner.c:6911
static void create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *final_distinct_rel, PathTarget *target)
Definition planner.c:5140
#define EXPRKIND_QUAL
Definition planner.c:87
static List * preprocess_groupclause(PlannerInfo *root, List *force)
Definition planner.c:3115
static Node * preprocess_expression(PlannerInfo *root, Node *expr, int kind)
Definition planner.c:1407
static Path * make_ordered_path(PlannerInfo *root, RelOptInfo *rel, Path *path, Path *cheapest_path, List *pathkeys, double limit_tuples)
Definition planner.c:7975
static bool has_volatile_pathkey(List *keys)
Definition planner.c:3471
static bool having_collation_conflict_walker(Node *node, having_collation_ctx *ctx)
Definition planner.c:1595
static RelOptInfo * create_partial_grouping_paths(PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *input_rel, grouping_sets_data *gd, GroupPathExtraData *extra, bool force_rel_creation)
Definition planner.c:7623
static void name_active_windows(List *activeWindows)
Definition planner.c:6321
static void create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel, List *sortPathkeys, List *groupClause, SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
Definition planner.c:8949
static PathTarget * make_sort_input_target(PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs)
Definition planner.c:6689
static void create_one_window_path(PlannerInfo *root, RelOptInfo *window_rel, Path *path, PathTarget *input_target, PathTarget *output_target, WindowFuncLists *wflists, List *activeWindows)
Definition planner.c:4900
bool enable_distinct_reordering
Definition planner.c:71
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition planner.c:6026
static grouping_sets_data * preprocess_grouping_sets(PlannerInfo *root)
Definition planner.c:2469
int debug_parallel_query
Definition planner.c:69
static List * remap_to_groupclause_idx(List *groupClause, List *gsets, int *tleref_to_colnum_map)
Definition planner.c:2649
static void adjust_group_pathkeys_for_groupagg(PlannerInfo *root)
Definition planner.c:3516
static PathTarget * make_group_input_target(PlannerInfo *root, PathTarget *final_target)
Definition planner.c:5811
static List * reorder_grouping_sets(List *groupingSets, List *sortclause)
Definition planner.c:3423
static int common_prefix_cmp(const void *a, const void *b)
Definition planner.c:6372
static void grouping_planner(PlannerInfo *root, double tuple_fraction, SetOperationStmt *setops)
Definition planner.c:1721
static RelOptInfo * make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, Node *havingQual)
Definition planner.c:4180
static List * generate_setop_child_grouplist(SetOperationStmt *op, List *targetlist)
Definition planner.c:8624
PlannedStmt * standard_planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition planner.c:351
static List * select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
Definition planner.c:6238
Expr * expression_planner(Expr *expr)
Definition planner.c:7027
static void create_partial_unique_paths(PlannerInfo *root, RelOptInfo *input_rel, List *sortPathkeys, List *groupClause, SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
Definition planner.c:9074
bool limit_needed(Query *parse)
Definition planner.c:3049
create_upper_paths_hook_type create_upper_paths_hook
Definition planner.c:83
#define EXPRKIND_TABLEFUNC
Definition planner.c:98
static void consider_groupingsets_paths(PlannerInfo *root, RelOptInfo *grouped_rel, Path *path, bool is_sorted, bool can_hash, grouping_sets_data *gd, const AggClauseCosts *agg_costs, double dNumGroups)
Definition planner.c:4451
static List * make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist)
Definition planner.c:6561
static RelOptInfo * create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, double limit_tuples)
Definition planner.c:5588
#define EXPRKIND_RTFUNC
Definition planner.c:89
static double get_number_of_groups(PlannerInfo *root, double path_rows, grouping_sets_data *gd, List *target_list)
Definition planner.c:3945
static List * extract_rollup_sets(List *groupingSets)
Definition planner.c:3211
static RelOptInfo * create_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, grouping_sets_data *gd)
Definition planner.c:4067
static void create_partitionwise_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel, RelOptInfo *grouped_rel, RelOptInfo *partially_grouped_rel, const AggClauseCosts *agg_costs, grouping_sets_data *gd, PartitionwiseAggregateType patype, GroupPathExtraData *extra)
Definition planner.c:8400
#define EXPRKIND_ARBITER_ELEM
Definition planner.c:97
static bool group_by_has_partkey(RelOptInfo *input_rel, List *targetList, List *groupClause)
Definition planner.c:8537
static void standard_qp_callback(PlannerInfo *root, void *extra)
Definition planner.c:3740
static RelOptInfo * create_window_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *input_target, PathTarget *output_target, bool output_target_parallel_safe, WindowFuncLists *wflists, List *activeWindows)
Definition planner.c:4813
PlannedStmt *(* planner_hook_type)(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition planner.h:28
void(* planner_setup_hook_type)(PlannerGlobal *glob, Query *parse, const char *query_string, int cursorOptions, double *tuple_fraction, ExplainState *es)
Definition planner.h:36
void(* create_upper_paths_hook_type)(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel, RelOptInfo *output_rel, void *extra)
Definition planner.h:50
void(* planner_shutdown_hook_type)(PlannerGlobal *glob, Query *parse, const char *query_string, PlannedStmt *pstmt)
Definition planner.h:44
@ PLAN_STMT_STANDARD
Definition plannodes.h:39
RowMarkType
Definition plannodes.h:1556
@ ROW_MARK_COPY
Definition plannodes.h:1562
@ ROW_MARK_REFERENCE
Definition plannodes.h:1561
@ ROW_MARK_SHARE
Definition plannodes.h:1559
@ ROW_MARK_EXCLUSIVE
Definition plannodes.h:1557
@ ROW_MARK_NOKEYEXCLUSIVE
Definition plannodes.h:1558
@ ROW_MARK_KEYSHARE
Definition plannodes.h:1560
#define snprintf
Definition port.h:260
#define qsort(a, b, c, d)
Definition port.h:495
#define printf(...)
Definition port.h:266
static Datum Int64GetDatum(int64 X)
Definition postgres.h:426
static int64 DatumGetInt64(Datum X)
Definition postgres.h:416
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define PointerGetDatum(X)
Definition postgres.h:354
#define InvalidOid
unsigned int Oid
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition prepagg.c:559
void preprocess_aggrefs(PlannerInfo *root, Node *clause)
Definition prepagg.c:110
void preprocess_function_rtes(PlannerInfo *root)
void flatten_simple_union_all(PlannerInfo *root)
void transform_MERGE_to_join(Query *parse)
void remove_useless_result_rtes(PlannerInfo *root)
void pull_up_sublinks(PlannerInfo *root)
void replace_empty_jointree(Query *parse)
void pull_up_subqueries(PlannerInfo *root)
Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins, bool include_inner_joins)
Query * preprocess_relation_rtes(PlannerInfo *root)
void reduce_outer_joins(PlannerInfo *root)
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition prepqual.c:293
char * c
e
static int fb(int x)
void preprocess_targetlist(PlannerInfo *root)
Definition preptlist.c:66
RelOptInfo * plan_set_operations(PlannerInfo *root)
Definition prepunion.c:98
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
tree ctl root
Definition radixtree.h:1857
List * RelationGetIndexPredicate(Relation relation)
Definition relcache.c:5201
List * RelationGetIndexExpressions(Relation relation)
Definition relcache.c:5088
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition relnode.c:544
void setup_simple_rel_arrays(PlannerInfo *root)
Definition relnode.c:114
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition relnode.c:1617
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition relnode.c:212
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)
@ ForwardScanDirection
Definition sdir.h:28
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition selfuncs.c:3800
double estimate_hashagg_tablesize(PlannerInfo *root, Path *path, const AggClauseCosts *agg_costs, double dNumGroups)
Definition selfuncs.c:4526
Plan * set_plan_references(PlannerInfo *root, Plan *plan)
Definition setrefs.c:291
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition setrefs.c:3749
void check_stack_depth(void)
Definition stack_depth.c:95
List * aggdistinct
Definition primnodes.h:494
List * args
Definition primnodes.h:488
Expr * aggfilter
Definition primnodes.h:497
List * aggorder
Definition primnodes.h:491
GetForeignRowMarkType_function GetForeignRowMarkType
Definition fdwapi.h:251
GetForeignUpperPaths_function GetForeignUpperPaths
Definition fdwapi.h:230
Cardinality limit_tuples
Definition pathnodes.h:3693
Node * quals
Definition primnodes.h:2397
List * fromlist
Definition primnodes.h:2396
PartitionwiseAggregateType patype
Definition pathnodes.h:3677
AggClauseCosts agg_final_costs
Definition pathnodes.h:3671
AggClauseCosts agg_partial_costs
Definition pathnodes.h:3670
Definition pg_list.h:54
Definition nodes.h:135
List * exprs
Definition pathnodes.h:1878
List * pathkeys
Definition pathnodes.h:2011
Cardinality rows
Definition pathnodes.h:2005
Bitmapset * prunableRelids
Definition pathnodes.h:206
char maxParallelHazard
Definition pathnodes.h:260
List * subplans
Definition pathnodes.h:178
bool dependsOnRole
Definition pathnodes.h:251
Bitmapset * allRelids
Definition pathnodes.h:199
List * subrtinfos
Definition pathnodes.h:212
List * appendRelations
Definition pathnodes.h:221
List * finalrowmarks
Definition pathnodes.h:215
List * invalItems
Definition pathnodes.h:230
List * relationOids
Definition pathnodes.h:227
List * paramExecTypes
Definition pathnodes.h:233
bool parallelModeOK
Definition pathnodes.h:254
bool transientPlan
Definition pathnodes.h:248
Bitmapset * rewindPlanIDs
Definition pathnodes.h:190
List * finalrteperminfos
Definition pathnodes.h:209
List * subpaths
Definition pathnodes.h:181
Index lastRowMarkId
Definition pathnodes.h:242
List * resultRelations
Definition pathnodes.h:218
List * partPruneInfos
Definition pathnodes.h:224
List * finalrtable
Definition pathnodes.h:193
uint64 default_pgs_mask
Definition pathnodes.h:263
List * elidedNodes
Definition pathnodes.h:236
bool parallelModeNeeded
Definition pathnodes.h:257
Cost per_tuple
Definition pathnodes.h:121
List * rtable
Definition parsenodes.h:178
CmdType commandType
Definition parsenodes.h:121
List * ppilist
Definition pathnodes.h:1051
bool useridiscurrent
Definition pathnodes.h:1115
Relids relids
Definition pathnodes.h:1021
struct PathTarget * reltarget
Definition pathnodes.h:1045
uint64 pgs_mask
Definition pathnodes.h:1039
List * unique_pathkeys
Definition pathnodes.h:1134
Cardinality tuples
Definition pathnodes.h:1096
bool consider_parallel
Definition pathnodes.h:1037
BlockNumber pages
Definition pathnodes.h:1095
List * cheapest_parameterized_paths
Definition pathnodes.h:1055
List * pathlist
Definition pathnodes.h:1050
RelOptKind reloptkind
Definition pathnodes.h:1015
List * indexlist
Definition pathnodes.h:1091
struct Path * cheapest_startup_path
Definition pathnodes.h:1053
struct Path * cheapest_total_path
Definition pathnodes.h:1054
List * unique_groupclause
Definition pathnodes.h:1136
Bitmapset * live_parts
Definition pathnodes.h:1204
int rel_parallel_workers
Definition pathnodes.h:1103
List * partial_pathlist
Definition pathnodes.h:1052
struct RelOptInfo * unique_rel
Definition pathnodes.h:1132
Cardinality rows
Definition pathnodes.h:1027
Form_pg_class rd_rel
Definition rel.h:111
LockClauseStrength strength
LockWaitPolicy waitPolicy
List * semi_rhs_exprs
Definition pathnodes.h:3241
JoinType jointype
Definition pathnodes.h:3230
Relids syn_righthand
Definition pathnodes.h:3229
List * semi_operators
Definition pathnodes.h:3240
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295
WindowClause * wc
Definition planner.c:123
Node * startOffset
List * partitionClause
Node * endOffset
List * orderClause
Index winref
Definition primnodes.h:612
int * tleref_to_colnum_map
Definition planner.c:114
Bitmapset * unhashable_refs
Definition planner.c:112
List * unsortable_sets
Definition planner.c:113
List * hash_sets_idx
Definition planner.c:108
double dNumHashGroups
Definition planner.c:109
Bitmapset * unsortable_refs
Definition planner.c:111
List * ancestor_collids
Definition planner.c:148
Definition type.h:96
List * activeWindows
Definition planner.c:131
grouping_sets_data * gset_data
Definition planner.c:132
SetOperationStmt * setop
Definition planner.c:133
Node * SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
Definition subselect.c:2207
void SS_process_ctes(PlannerInfo *root)
Definition subselect.c:884
void SS_identify_outer_params(PlannerInfo *root)
Definition subselect.c:2365
Node * SS_replace_correlation_vars(PlannerInfo *root, Node *expr)
Definition subselect.c:2152
void SS_finalize_plan(PlannerInfo *root, Plan *plan)
Definition subselect.c:2549
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition subselect.c:2493
void SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
Definition subselect.c:2429
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
void split_pathtarget_at_srfs_grouping(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition tlist.c:868
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition tlist.c:88
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition tlist.c:227
SortGroupClause * get_sortgroupref_clause_noerr(Index sortref, List *clauses)
Definition tlist.c:452
SortGroupClause * get_sortgroupref_clause(Index sortref, List *clauses)
Definition tlist.c:431
bool grouping_is_sortable(List *groupClause)
Definition tlist.c:549
List * make_tlist_from_pathtarget(PathTarget *target)
Definition tlist.c:633
PathTarget * copy_pathtarget(PathTarget *src)
Definition tlist.c:666
void add_new_columns_to_pathtarget(PathTarget *target, List *exprs)
Definition tlist.c:761
PathTarget * create_empty_pathtarget(void)
Definition tlist.c:690
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition tlist.c:401
void split_pathtarget_at_srfs(PlannerInfo *root, PathTarget *target, PathTarget *input_target, List **targets, List **targets_contain_srfs)
Definition tlist.c:845
bool grouping_is_hashable(List *groupClause)
Definition tlist.c:569
void add_column_to_pathtarget(PathTarget *target, Expr *expr, Index sortgroupref)
Definition tlist.c:704
#define create_pathtarget(root, tlist)
Definition tlist.h:58
Node * flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
Definition var.c:999
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition var.c:114
List * pull_var_clause(Node *node, int flags)
Definition var.c:653
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition var.c:781
const char * name