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