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