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