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