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-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/optimizer/plan/planner.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include <limits.h>
19 : : #include <math.h>
20 : :
21 : : #include "access/genam.h"
22 : : #include "access/parallel.h"
23 : : #include "access/sysattr.h"
24 : : #include "access/table.h"
25 : : #include "catalog/pg_aggregate.h"
26 : : #include "catalog/pg_inherits.h"
27 : : #include "catalog/pg_proc.h"
28 : : #include "catalog/pg_type.h"
29 : : #include "executor/executor.h"
30 : : #include "foreign/fdwapi.h"
31 : : #include "jit/jit.h"
32 : : #include "lib/bipartite_match.h"
33 : : #include "lib/knapsack.h"
34 : : #include "miscadmin.h"
35 : : #include "nodes/makefuncs.h"
36 : : #include "nodes/nodeFuncs.h"
37 : : #ifdef OPTIMIZER_DEBUG
38 : : #include "nodes/print.h"
39 : : #endif
40 : : #include "nodes/supportnodes.h"
41 : : #include "optimizer/appendinfo.h"
42 : : #include "optimizer/clauses.h"
43 : : #include "optimizer/cost.h"
44 : : #include "optimizer/optimizer.h"
45 : : #include "optimizer/paramassign.h"
46 : : #include "optimizer/pathnode.h"
47 : : #include "optimizer/paths.h"
48 : : #include "optimizer/plancat.h"
49 : : #include "optimizer/planmain.h"
50 : : #include "optimizer/planner.h"
51 : : #include "optimizer/prep.h"
52 : : #include "optimizer/subselect.h"
53 : : #include "optimizer/tlist.h"
54 : : #include "parser/analyze.h"
55 : : #include "parser/parse_agg.h"
56 : : #include "parser/parse_clause.h"
57 : : #include "parser/parse_relation.h"
58 : : #include "parser/parsetree.h"
59 : : #include "partitioning/partdesc.h"
60 : : #include "rewrite/rewriteManip.h"
61 : : #include "utils/acl.h"
62 : : #include "utils/backend_status.h"
63 : : #include "utils/lsyscache.h"
64 : : #include "utils/rel.h"
65 : : #include "utils/selfuncs.h"
66 : :
67 : : /* GUC parameters */
68 : : double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
69 : : int debug_parallel_query = DEBUG_PARALLEL_OFF;
70 : : bool parallel_leader_participation = true;
71 : : bool enable_distinct_reordering = true;
72 : :
73 : : /* Hook for plugins to get control in planner() */
74 : : planner_hook_type planner_hook = NULL;
75 : :
76 : : /* Hook for plugins to get control after PlannerGlobal is initialized */
77 : : planner_setup_hook_type planner_setup_hook = NULL;
78 : :
79 : : /* Hook for plugins to get control before PlannerGlobal is discarded */
80 : : planner_shutdown_hook_type planner_shutdown_hook = NULL;
81 : :
82 : : /* Hook for plugins to get control when grouping_planner() plans upper rels */
83 : : create_upper_paths_hook_type create_upper_paths_hook = NULL;
84 : :
85 : :
86 : : /* Expression kind codes for preprocess_expression */
87 : : #define EXPRKIND_QUAL 0
88 : : #define EXPRKIND_TARGET 1
89 : : #define EXPRKIND_RTFUNC 2
90 : : #define EXPRKIND_RTFUNC_LATERAL 3
91 : : #define EXPRKIND_VALUES 4
92 : : #define EXPRKIND_VALUES_LATERAL 5
93 : : #define EXPRKIND_LIMIT 6
94 : : #define EXPRKIND_APPINFO 7
95 : : #define EXPRKIND_PHV 8
96 : : #define EXPRKIND_TABLESAMPLE 9
97 : : #define EXPRKIND_ARBITER_ELEM 10
98 : : #define EXPRKIND_TABLEFUNC 11
99 : : #define EXPRKIND_TABLEFUNC_LATERAL 12
100 : : #define EXPRKIND_GROUPEXPR 13
101 : :
102 : : /*
103 : : * Data specific to grouping sets
104 : : */
105 : : typedef struct
106 : : {
107 : : List *rollups;
108 : : List *hash_sets_idx;
109 : : double dNumHashGroups;
110 : : bool any_hashable;
111 : : Bitmapset *unsortable_refs;
112 : : Bitmapset *unhashable_refs;
113 : : List *unsortable_sets;
114 : : int *tleref_to_colnum_map;
115 : : } grouping_sets_data;
116 : :
117 : : /*
118 : : * Temporary structure for use during WindowClause reordering in order to be
119 : : * able to sort WindowClauses on partitioning/ordering prefix.
120 : : */
121 : : typedef struct
122 : : {
123 : : WindowClause *wc;
124 : : List *uniqueOrder; /* A List of unique ordering/partitioning
125 : : * clauses per Window */
126 : : } WindowClauseSortData;
127 : :
128 : : /* Passthrough data for standard_qp_callback */
129 : : typedef struct
130 : : {
131 : : List *activeWindows; /* active windows, if any */
132 : : grouping_sets_data *gset_data; /* grouping sets data, if any */
133 : : SetOperationStmt *setop; /* parent set operation or NULL if not a
134 : : * subquery belonging to a set operation */
135 : : } standard_qp_extra;
136 : :
137 : : /*
138 : : * Context for the find_having_collation_conflicts walker.
139 : : *
140 : : * ancestor_collids is a stack of inputcollids contributed by collation-aware
141 : : * ancestors of the current node. Entries are pushed before recursing into a
142 : : * node's children and popped afterwards, so the stack reflects exactly the
143 : : * inputcollids on the current root-to-node path.
144 : : */
145 : : typedef struct
146 : : {
147 : : Index group_rtindex;
148 : : List *ancestor_collids;
149 : : } having_collation_ctx;
150 : :
151 : : /* Local functions */
152 : : static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
153 : : static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
154 : : static Bitmapset *find_having_collation_conflicts(Query *parse,
155 : : Index group_rtindex);
156 : : static bool having_collation_conflict_walker(Node *node,
157 : : having_collation_ctx *ctx);
158 : : static void grouping_planner(PlannerInfo *root, double tuple_fraction,
159 : : SetOperationStmt *setops);
160 : : static grouping_sets_data *preprocess_grouping_sets(PlannerInfo *root);
161 : : static List *remap_to_groupclause_idx(List *groupClause, List *gsets,
162 : : int *tleref_to_colnum_map);
163 : : static void preprocess_rowmarks(PlannerInfo *root);
164 : : static double preprocess_limit(PlannerInfo *root,
165 : : double tuple_fraction,
166 : : int64 *offset_est, int64 *count_est);
167 : : static List *preprocess_groupclause(PlannerInfo *root, List *force);
168 : : static List *extract_rollup_sets(List *groupingSets);
169 : : static List *reorder_grouping_sets(List *groupingSets, List *sortclause);
170 : : static void standard_qp_callback(PlannerInfo *root, void *extra);
171 : : static double get_number_of_groups(PlannerInfo *root,
172 : : double path_rows,
173 : : grouping_sets_data *gd,
174 : : List *target_list);
175 : : static RelOptInfo *create_grouping_paths(PlannerInfo *root,
176 : : RelOptInfo *input_rel,
177 : : PathTarget *target,
178 : : bool target_parallel_safe,
179 : : grouping_sets_data *gd);
180 : : static bool is_degenerate_grouping(PlannerInfo *root);
181 : : static void create_degenerate_grouping_paths(PlannerInfo *root,
182 : : RelOptInfo *input_rel,
183 : : RelOptInfo *grouped_rel);
184 : : static RelOptInfo *make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
185 : : PathTarget *target, bool target_parallel_safe,
186 : : Node *havingQual);
187 : : static void create_ordinary_grouping_paths(PlannerInfo *root,
188 : : RelOptInfo *input_rel,
189 : : RelOptInfo *grouped_rel,
190 : : const AggClauseCosts *agg_costs,
191 : : grouping_sets_data *gd,
192 : : GroupPathExtraData *extra,
193 : : RelOptInfo **partially_grouped_rel_p);
194 : : static void consider_groupingsets_paths(PlannerInfo *root,
195 : : RelOptInfo *grouped_rel,
196 : : Path *path,
197 : : bool is_sorted,
198 : : bool can_hash,
199 : : grouping_sets_data *gd,
200 : : const AggClauseCosts *agg_costs,
201 : : double dNumGroups);
202 : : static RelOptInfo *create_window_paths(PlannerInfo *root,
203 : : RelOptInfo *input_rel,
204 : : PathTarget *input_target,
205 : : PathTarget *output_target,
206 : : bool output_target_parallel_safe,
207 : : WindowFuncLists *wflists,
208 : : List *activeWindows);
209 : : static void create_one_window_path(PlannerInfo *root,
210 : : RelOptInfo *window_rel,
211 : : Path *path,
212 : : PathTarget *input_target,
213 : : PathTarget *output_target,
214 : : WindowFuncLists *wflists,
215 : : List *activeWindows);
216 : : static RelOptInfo *create_distinct_paths(PlannerInfo *root,
217 : : RelOptInfo *input_rel,
218 : : PathTarget *target);
219 : : static void create_partial_distinct_paths(PlannerInfo *root,
220 : : RelOptInfo *input_rel,
221 : : RelOptInfo *final_distinct_rel,
222 : : PathTarget *target);
223 : : static RelOptInfo *create_final_distinct_paths(PlannerInfo *root,
224 : : RelOptInfo *input_rel,
225 : : RelOptInfo *distinct_rel);
226 : : static List *get_useful_pathkeys_for_distinct(PlannerInfo *root,
227 : : List *needed_pathkeys,
228 : : List *path_pathkeys);
229 : : static RelOptInfo *create_ordered_paths(PlannerInfo *root,
230 : : RelOptInfo *input_rel,
231 : : PathTarget *target,
232 : : bool target_parallel_safe,
233 : : double limit_tuples);
234 : : static PathTarget *make_group_input_target(PlannerInfo *root,
235 : : PathTarget *final_target);
236 : : static PathTarget *make_partial_grouping_target(PlannerInfo *root,
237 : : PathTarget *grouping_target,
238 : : Node *havingQual);
239 : : static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
240 : : static void optimize_window_clauses(PlannerInfo *root,
241 : : WindowFuncLists *wflists);
242 : : static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
243 : : static void name_active_windows(List *activeWindows);
244 : : static PathTarget *make_window_input_target(PlannerInfo *root,
245 : : PathTarget *final_target,
246 : : List *activeWindows);
247 : : static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
248 : : List *tlist);
249 : : static PathTarget *make_sort_input_target(PlannerInfo *root,
250 : : PathTarget *final_target,
251 : : bool *have_postponed_srfs);
252 : : static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
253 : : List *targets, List *targets_contain_srfs);
254 : : static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
255 : : RelOptInfo *grouped_rel,
256 : : RelOptInfo *partially_grouped_rel,
257 : : const AggClauseCosts *agg_costs,
258 : : grouping_sets_data *gd,
259 : : GroupPathExtraData *extra);
260 : : static RelOptInfo *create_partial_grouping_paths(PlannerInfo *root,
261 : : RelOptInfo *grouped_rel,
262 : : RelOptInfo *input_rel,
263 : : grouping_sets_data *gd,
264 : : GroupPathExtraData *extra,
265 : : bool force_rel_creation);
266 : : static Path *make_ordered_path(PlannerInfo *root,
267 : : RelOptInfo *rel,
268 : : Path *path,
269 : : Path *cheapest_path,
270 : : List *pathkeys,
271 : : double limit_tuples);
272 : : static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel);
273 : : static bool can_partial_agg(PlannerInfo *root);
274 : : static void apply_scanjoin_target_to_paths(PlannerInfo *root,
275 : : RelOptInfo *rel,
276 : : List *scanjoin_targets,
277 : : List *scanjoin_targets_contain_srfs,
278 : : bool scanjoin_target_parallel_safe,
279 : : bool tlist_same_exprs);
280 : : static void create_partitionwise_grouping_paths(PlannerInfo *root,
281 : : RelOptInfo *input_rel,
282 : : RelOptInfo *grouped_rel,
283 : : RelOptInfo *partially_grouped_rel,
284 : : const AggClauseCosts *agg_costs,
285 : : grouping_sets_data *gd,
286 : : PartitionwiseAggregateType patype,
287 : : GroupPathExtraData *extra);
288 : : static bool group_by_has_partkey(RelOptInfo *input_rel,
289 : : List *targetList,
290 : : List *groupClause);
291 : : static int common_prefix_cmp(const void *a, const void *b);
292 : : static List *generate_setop_child_grouplist(SetOperationStmt *op,
293 : : List *targetlist);
294 : : static void create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
295 : : List *sortPathkeys, List *groupClause,
296 : : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
297 : : static void create_partial_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
298 : : List *sortPathkeys, List *groupClause,
299 : : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel);
300 : :
301 : :
302 : : /*****************************************************************************
303 : : *
304 : : * Query optimizer entry point
305 : : *
306 : : * Inputs:
307 : : * parse: an analyzed-and-rewritten query tree for an optimizable statement
308 : : * query_string: source text for the query tree (used for error reports)
309 : : * cursorOptions: bitmask of CURSOR_OPT_XXX flags, see parsenodes.h
310 : : * boundParams: passed-in parameter values, or NULL if none
311 : : * es: ExplainState if being called from EXPLAIN, else NULL
312 : : *
313 : : * The result is a PlannedStmt tree.
314 : : *
315 : : * PARAM_EXTERN Param nodes within the parse tree can be replaced by Consts
316 : : * using values from boundParams, if those values are marked PARAM_FLAG_CONST.
317 : : * Parameter values not so marked are still relied on for estimation purposes.
318 : : *
319 : : * The ExplainState pointer is not currently used by the core planner, but it
320 : : * is passed through to some planner hooks so that they can report information
321 : : * back to EXPLAIN extension hooks.
322 : : *
323 : : * To support loadable plugins that monitor or modify planner behavior,
324 : : * we provide a hook variable that lets a plugin get control before and
325 : : * after the standard planning process. The plugin would normally call
326 : : * standard_planner().
327 : : *
328 : : * Note to plugin authors: standard_planner() scribbles on its Query input,
329 : : * so you'd better copy that data structure if you want to plan more than once.
330 : : *
331 : : *****************************************************************************/
332 : : PlannedStmt *
2252 fujii@postgresql.org 333 :CBC 335991 : planner(Query *parse, const char *query_string, int cursorOptions,
334 : : ParamListInfo boundParams, ExplainState *es)
335 : : {
336 : : PlannedStmt *result;
337 : :
6945 tgl@sss.pgh.pa.us 338 [ + + ]: 335991 : if (planner_hook)
234 rhaas@postgresql.org 339 :GNC 51816 : result = (*planner_hook) (parse, query_string, cursorOptions,
340 : : boundParams, es);
341 : : else
342 : 284175 : result = standard_planner(parse, query_string, cursorOptions,
343 : : boundParams, es);
344 : :
432 michael@paquier.xyz 345 :CBC 331987 : pgstat_report_plan_id(result->planId, false);
346 : :
6945 tgl@sss.pgh.pa.us 347 : 331987 : return result;
348 : : }
349 : :
350 : : PlannedStmt *
2252 fujii@postgresql.org 351 : 335991 : standard_planner(Query *parse, const char *query_string, int cursorOptions,
352 : : ParamListInfo boundParams, ExplainState *es)
353 : : {
354 : : PlannedStmt *result;
355 : : PlannerGlobal *glob;
356 : : double tuple_fraction;
357 : : PlannerInfo *root;
358 : : RelOptInfo *final_rel;
359 : : Path *best_path;
360 : : Plan *top_plan;
361 : : ListCell *lp,
362 : : *lr,
363 : : *lc;
364 : :
365 : : /*
366 : : * Set up global state for this planner invocation. This data is needed
367 : : * across all levels of sub-Query that might exist in the given command,
368 : : * so we keep it in a separate struct that's linked to by each per-Query
369 : : * PlannerInfo.
370 : : */
7040 tgl@sss.pgh.pa.us 371 : 335991 : glob = makeNode(PlannerGlobal);
372 : :
373 : 335991 : glob->boundParams = boundParams;
7037 374 : 335991 : glob->subplans = NIL;
795 375 : 335991 : glob->subpaths = NIL;
5383 376 : 335991 : glob->subroots = NIL;
7032 377 : 335991 : glob->rewindPlanIDs = NULL;
7037 378 : 335991 : glob->finalrtable = NIL;
381 rguo@postgresql.org 379 : 335991 : glob->allRelids = NULL;
380 : 335991 : glob->prunableRelids = NULL;
1271 alvherre@alvh.no-ip. 381 : 335991 : glob->finalrteperminfos = NIL;
6074 tgl@sss.pgh.pa.us 382 : 335991 : glob->finalrowmarks = NIL;
5573 383 : 335991 : glob->resultRelations = NIL;
2362 384 : 335991 : glob->appendRelations = NIL;
381 rguo@postgresql.org 385 : 335991 : glob->partPruneInfos = NIL;
6806 tgl@sss.pgh.pa.us 386 : 335991 : glob->relationOids = NIL;
6472 387 : 335991 : glob->invalItems = NIL;
3120 rhaas@postgresql.org 388 : 335991 : glob->paramExecTypes = NIL;
6430 tgl@sss.pgh.pa.us 389 : 335991 : glob->lastPHId = 0;
5589 390 : 335991 : glob->lastRowMarkId = 0;
3897 rhaas@postgresql.org 391 : 335991 : glob->lastPlanNodeId = 0;
6827 tgl@sss.pgh.pa.us 392 : 335991 : glob->transientPlan = false;
3606 393 : 335991 : glob->dependsOnRole = false;
381 rguo@postgresql.org 394 : 335991 : glob->partition_directory = NULL;
312 rguo@postgresql.org 395 :GNC 335991 : glob->rel_notnullatts_hash = NULL;
396 : :
397 : : /*
398 : : * Assess whether it's feasible to use parallel mode for this query. We
399 : : * can't do this in a standalone backend, or if the command will try to
400 : : * modify any data, or if this is a cursor operation, or if GUCs are set
401 : : * to values that don't permit parallelism, or if parallel-unsafe
402 : : * functions are present in the query tree.
403 : : *
404 : : * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
405 : : * MATERIALIZED VIEW to use parallel plans, but this is safe only because
406 : : * the command is writing into a completely new table which workers won't
407 : : * be able to see. If the workers could see the table, the fact that
408 : : * group locking would cause them to ignore the leader's heavyweight GIN
409 : : * page locks would make this unsafe. We'll have to fix that somehow if
410 : : * we want to allow parallel inserts in general; updates and deletes have
411 : : * additional problems especially around combo CIDs.)
412 : : *
413 : : * For now, we don't try to use parallel mode if we're running inside a
414 : : * parallel worker. We might eventually be able to relax this
415 : : * restriction, but for now it seems best not to have parallel workers
416 : : * trying to create their own parallel workers.
417 : : */
3571 tgl@sss.pgh.pa.us 418 [ + + + + ]:CBC 335991 : if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
419 : 317601 : IsUnderPostmaster &&
1893 akapila@postgresql.o 420 [ + + ]: 317601 : parse->commandType == CMD_SELECT &&
3571 tgl@sss.pgh.pa.us 421 [ + + ]: 260578 : !parse->hasModifyingCTE &&
422 [ + + ]: 260455 : max_parallel_workers_per_gather > 0 &&
2633 tmunro@postgresql.or 423 [ + + ]: 259759 : !IsParallelWorker())
424 : : {
425 : : /* all the cheap tests pass, so scan the query tree */
1893 akapila@postgresql.o 426 : 259719 : glob->maxParallelHazard = max_parallel_hazard(parse);
3571 tgl@sss.pgh.pa.us 427 : 259719 : glob->parallelModeOK = (glob->maxParallelHazard != PROPARALLEL_UNSAFE);
428 : : }
429 : : else
430 : : {
431 : : /* skip the query tree scan, just assume it's unsafe */
432 : 76272 : glob->maxParallelHazard = PROPARALLEL_UNSAFE;
433 : 76272 : glob->parallelModeOK = false;
434 : : }
435 : :
436 : : /*
437 : : * glob->parallelModeNeeded is normally set to false here and changed to
438 : : * true during plan creation if a Gather or Gather Merge plan is actually
439 : : * created (cf. create_gather_plan, create_gather_merge_plan).
440 : : *
441 : : * However, if debug_parallel_query = on or debug_parallel_query =
442 : : * regress, then we impose parallel mode whenever it's safe to do so, even
443 : : * if the final plan doesn't use parallelism. It's not safe to do so if
444 : : * the query contains anything parallel-unsafe; parallelModeOK will be
445 : : * false in that case. Note that parallelModeOK can't change after this
446 : : * point. Otherwise, everything in the query is either parallel-safe or
447 : : * parallel-restricted, and in either case it should be OK to impose
448 : : * parallel-mode restrictions. If that ends up breaking something, then
449 : : * either some function the user included in the query is incorrectly
450 : : * labeled as parallel-safe or parallel-restricted when in reality it's
451 : : * parallel-unsafe, or else the query planner itself has a bug.
452 : : */
3620 rhaas@postgresql.org 453 [ + + ]: 560507 : glob->parallelModeNeeded = glob->parallelModeOK &&
1200 drowley@postgresql.o 454 [ + + ]: 224516 : (debug_parallel_query != DEBUG_PARALLEL_OFF);
455 : :
456 : : /* Determine what fraction of the plan is likely to be scanned */
6984 tgl@sss.pgh.pa.us 457 [ + + ]: 335991 : if (cursorOptions & CURSOR_OPT_FAST_PLAN)
458 : : {
459 : : /*
460 : : * We have no real idea how many tuples the user will ultimately FETCH
461 : : * from a cursor, but it is often the case that he doesn't want 'em
462 : : * all, or would prefer a fast-start plan anyway so that he can
463 : : * process some of the tuples sooner. Use a GUC parameter to decide
464 : : * what fraction to optimize for.
465 : : */
6602 466 : 3198 : tuple_fraction = cursor_tuple_fraction;
467 : :
468 : : /*
469 : : * We document cursor_tuple_fraction as simply being a fraction, which
470 : : * means the edge cases 0 and 1 have to be treated specially here. We
471 : : * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
472 : : */
473 [ - + ]: 3198 : if (tuple_fraction >= 1.0)
6602 tgl@sss.pgh.pa.us 474 :UBC 0 : tuple_fraction = 0.0;
6602 tgl@sss.pgh.pa.us 475 [ - + ]:CBC 3198 : else if (tuple_fraction <= 0.0)
6602 tgl@sss.pgh.pa.us 476 :UBC 0 : tuple_fraction = 1e-10;
477 : : }
478 : : else
479 : : {
480 : : /* Default assumption is we need all the tuples */
8482 tgl@sss.pgh.pa.us 481 :CBC 332793 : tuple_fraction = 0.0;
482 : : }
483 : :
484 : : /*
485 : : * Compute the initial path generation strategy mask.
486 : : *
487 : : * Some strategies, such as PGS_FOREIGNJOIN, have no corresponding enable_*
488 : : * GUC, and so the corresponding bits are always set in the default
489 : : * strategy mask.
490 : : *
491 : : * It may seem surprising that enable_indexscan sets both PGS_INDEXSCAN
492 : : * and PGS_INDEXONLYSCAN. However, the historical behavior of this GUC
493 : : * corresponds to this exactly: enable_indexscan=off disables both
494 : : * index-scan and index-only scan paths, whereas enable_indexonlyscan=off
495 : : * converts the index-only scan paths that we would have considered into
496 : : * index scan paths.
497 : : */
122 rhaas@postgresql.org 498 :GNC 335991 : glob->default_pgs_mask = PGS_APPEND | PGS_MERGE_APPEND | PGS_FOREIGNJOIN |
499 : : PGS_GATHER | PGS_CONSIDER_NONPARTIAL;
500 [ + - ]: 335991 : if (enable_tidscan)
501 : 335991 : glob->default_pgs_mask |= PGS_TIDSCAN;
502 [ + + ]: 335991 : if (enable_seqscan)
503 : 318819 : glob->default_pgs_mask |= PGS_SEQSCAN;
504 [ + + ]: 335991 : if (enable_indexscan)
505 : 333744 : glob->default_pgs_mask |= PGS_INDEXSCAN | PGS_INDEXONLYSCAN;
506 [ + + ]: 335991 : if (enable_indexonlyscan)
507 : 334608 : glob->default_pgs_mask |= PGS_CONSIDER_INDEXONLY;
508 [ + + ]: 335991 : if (enable_bitmapscan)
509 : 326578 : glob->default_pgs_mask |= PGS_BITMAPSCAN;
510 [ + + ]: 335991 : if (enable_mergejoin)
511 : : {
512 : 334047 : glob->default_pgs_mask |= PGS_MERGEJOIN_PLAIN;
513 [ + + ]: 334047 : if (enable_material)
514 : 333980 : glob->default_pgs_mask |= PGS_MERGEJOIN_MATERIALIZE;
515 : : }
516 [ + + ]: 335991 : if (enable_nestloop)
517 : : {
518 : 335687 : glob->default_pgs_mask |= PGS_NESTLOOP_PLAIN;
519 [ + + ]: 335687 : if (enable_material)
520 : 335369 : glob->default_pgs_mask |= PGS_NESTLOOP_MATERIALIZE;
521 [ + + ]: 335687 : if (enable_memoize)
522 : 335567 : glob->default_pgs_mask |= PGS_NESTLOOP_MEMOIZE;
523 : : }
524 [ + + ]: 335991 : if (enable_hashjoin)
525 : 333725 : glob->default_pgs_mask |= PGS_HASHJOIN;
526 [ + - ]: 335991 : if (enable_gathermerge)
527 : 335991 : glob->default_pgs_mask |= PGS_GATHER_MERGE;
528 [ + + ]: 335991 : if (enable_partitionwise_join)
529 : 2074 : glob->default_pgs_mask |= PGS_CONSIDER_PARTITIONWISE;
530 : :
531 : : /* Allow plugins to take control after we've initialized "glob" */
234 532 [ + + ]: 335991 : if (planner_setup_hook)
109 533 : 88950 : (*planner_setup_hook) (glob, parse, query_string, cursorOptions,
534 : : &tuple_fraction, es);
535 : :
536 : : /* primary planning entry point (may recurse for subqueries) */
65 537 : 335221 : root = subquery_planner(glob, parse, NULL, NULL, NULL, false,
538 : : tuple_fraction, NULL);
539 : :
540 : : /* Select best Path and turn it into a Plan */
3736 tgl@sss.pgh.pa.us 541 :CBC 332257 : final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
542 : 332257 : best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
543 : :
544 : 332257 : top_plan = create_plan(root, best_path);
545 : :
546 : : /*
547 : : * If creating a plan for a scrollable cursor, make sure it can run
548 : : * backwards on demand. Add a Material node at the top at need.
549 : : */
6984 550 [ + + ]: 331987 : if (cursorOptions & CURSOR_OPT_SCROLL)
551 : : {
7039 552 [ + + ]: 221 : if (!ExecSupportsBackwardScan(top_plan))
3404 553 : 26 : top_plan = materialize_finished_plan(top_plan);
554 : : }
555 : :
556 : : /*
557 : : * Optionally add a Gather node for testing purposes, provided this is
558 : : * actually a safe thing to do.
559 : : *
560 : : * We can add Gather even when top_plan has parallel-safe initPlans, but
561 : : * then we have to move the initPlans to the Gather node because of
562 : : * SS_finalize_plan's limitations. That would cause cosmetic breakage of
563 : : * regression tests when debug_parallel_query = regress, because initPlans
564 : : * that would normally appear on the top_plan move to the Gather, causing
565 : : * them to disappear from EXPLAIN output. That doesn't seem worth kluging
566 : : * EXPLAIN to hide, so skip it when debug_parallel_query = regress.
567 : : */
1052 568 [ + + ]: 331987 : if (debug_parallel_query != DEBUG_PARALLEL_OFF &&
569 [ + + ]: 157 : top_plan->parallel_safe &&
570 [ - + ]: 104 : (top_plan->initPlan == NIL ||
1052 tgl@sss.pgh.pa.us 571 [ # # ]:UBC 0 : debug_parallel_query != DEBUG_PARALLEL_REGRESS))
572 : : {
3765 rhaas@postgresql.org 573 :CBC 104 : Gather *gather = makeNode(Gather);
574 : : Cost initplan_cost;
575 : : bool unsafe_initplans;
576 : :
577 : 104 : gather->plan.targetlist = top_plan->targetlist;
578 : 104 : gather->plan.qual = NIL;
579 : 104 : gather->plan.lefttree = top_plan;
580 : 104 : gather->plan.righttree = NULL;
581 : 104 : gather->num_workers = 1;
582 : 104 : gather->single_copy = true;
1200 drowley@postgresql.o 583 : 104 : gather->invisible = (debug_parallel_query == DEBUG_PARALLEL_REGRESS);
584 : :
585 : : /* Transfer any initPlans to the new top node */
1052 tgl@sss.pgh.pa.us 586 : 104 : gather->plan.initPlan = top_plan->initPlan;
587 : 104 : top_plan->initPlan = NIL;
588 : :
589 : : /*
590 : : * Since this Gather has no parallel-aware descendants to signal to,
591 : : * we don't need a rescan Param.
592 : : */
3195 593 : 104 : gather->rescan_param = -1;
594 : :
595 : : /*
596 : : * Ideally we'd use cost_gather here, but setting up dummy path data
597 : : * to satisfy it doesn't seem much cleaner than knowing what it does.
598 : : */
3618 599 : 104 : gather->plan.startup_cost = top_plan->startup_cost +
600 : : parallel_setup_cost;
601 : 104 : gather->plan.total_cost = top_plan->total_cost +
602 : 104 : parallel_setup_cost + parallel_tuple_cost * top_plan->plan_rows;
603 : 104 : gather->plan.plan_rows = top_plan->plan_rows;
604 : 104 : gather->plan.plan_width = top_plan->plan_width;
605 : 104 : gather->plan.parallel_aware = false;
3335 606 : 104 : gather->plan.parallel_safe = false;
607 : :
608 : : /*
609 : : * Delete the initplans' cost from top_plan. We needn't add it to the
610 : : * Gather node, since the above coding already included it there.
611 : : */
1052 612 : 104 : SS_compute_initplan_cost(gather->plan.initPlan,
613 : : &initplan_cost, &unsafe_initplans);
614 : 104 : top_plan->startup_cost -= initplan_cost;
615 : 104 : top_plan->total_cost -= initplan_cost;
616 : :
617 : : /* use parallel mode for parallel plans. */
3765 rhaas@postgresql.org 618 : 104 : root->glob->parallelModeNeeded = true;
619 : :
620 : 104 : top_plan = &gather->plan;
621 : : }
622 : :
623 : : /*
624 : : * If any Params were generated, run through the plan tree and compute
625 : : * each plan node's extParam/allParam sets. Ideally we'd merge this into
626 : : * set_plan_references' tree traversal, but for now it has to be separate
627 : : * because we need to visit subplans before not after main plan.
628 : : */
3120 629 [ + + ]: 331987 : if (glob->paramExecTypes != NIL)
630 : : {
3945 tgl@sss.pgh.pa.us 631 [ - + ]: 110099 : Assert(list_length(glob->subplans) == list_length(glob->subroots));
632 : 144282 : forboth(lp, glob->subplans, lr, glob->subroots)
[ + + + +
+ + + + +
+ + - +
+ ]
633 : : {
634 : 34183 : Plan *subplan = (Plan *) lfirst(lp);
3189 635 : 34183 : PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
636 : :
3945 637 : 34183 : SS_finalize_plan(subroot, subplan);
638 : : }
639 : 110099 : SS_finalize_plan(root, top_plan);
640 : : }
641 : :
642 : : /* final cleanup of the plan */
7037 643 [ - + ]: 331987 : Assert(glob->finalrtable == NIL);
1271 alvherre@alvh.no-ip. 644 [ - + ]: 331987 : Assert(glob->finalrteperminfos == NIL);
6074 tgl@sss.pgh.pa.us 645 [ - + ]: 331987 : Assert(glob->finalrowmarks == NIL);
5573 646 [ - + ]: 331987 : Assert(glob->resultRelations == NIL);
2362 647 [ - + ]: 331987 : Assert(glob->appendRelations == NIL);
5383 648 : 331987 : top_plan = set_plan_references(root, top_plan);
649 : : /* ... and the subplans (both regular subplans and initplans) */
650 [ - + ]: 331987 : Assert(list_length(glob->subplans) == list_length(glob->subroots));
651 : 366170 : forboth(lp, glob->subplans, lr, glob->subroots)
[ + + + +
+ + + + +
+ + - +
+ ]
652 : : {
6771 bruce@momjian.us 653 : 34183 : Plan *subplan = (Plan *) lfirst(lp);
3189 tgl@sss.pgh.pa.us 654 : 34183 : PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
655 : :
5383 656 : 34183 : lfirst(lp) = set_plan_references(subroot, subplan);
657 : : }
658 : :
659 : : /* build the PlannedStmt result */
7039 660 : 331987 : result = makeNode(PlannedStmt);
661 : :
662 : 331987 : result->commandType = parse->commandType;
5177 663 : 331987 : result->queryId = parse->queryId;
303 michael@paquier.xyz 664 :GNC 331987 : result->planOrigin = PLAN_STMT_STANDARD;
6076 tgl@sss.pgh.pa.us 665 :CBC 331987 : result->hasReturning = (parse->returningList != NIL);
5573 666 : 331987 : result->hasModifyingCTE = parse->hasModifyingCTE;
7039 667 : 331987 : result->canSetTag = parse->canSetTag;
6827 668 : 331987 : result->transientPlan = glob->transientPlan;
3606 669 : 331987 : result->dependsOnRole = glob->dependsOnRole;
670 : 331987 : result->parallelModeNeeded = glob->parallelModeNeeded;
7039 671 : 331987 : result->planTree = top_plan;
485 amitlan@postgresql.o 672 : 331987 : result->partPruneInfos = glob->partPruneInfos;
7037 tgl@sss.pgh.pa.us 673 : 331987 : result->rtable = glob->finalrtable;
477 amitlan@postgresql.o 674 : 663974 : result->unprunableRelids = bms_difference(glob->allRelids,
675 : 331987 : glob->prunableRelids);
1271 alvherre@alvh.no-ip. 676 : 331987 : result->permInfos = glob->finalrteperminfos;
109 rhaas@postgresql.org 677 :GNC 331987 : result->subrtinfos = glob->subrtinfos;
2362 tgl@sss.pgh.pa.us 678 :CBC 331987 : result->appendRelations = glob->appendRelations;
7037 679 : 331987 : result->subplans = glob->subplans;
7032 680 : 331987 : result->rewindPlanIDs = glob->rewindPlanIDs;
6074 681 : 331987 : result->rowMarks = glob->finalrowmarks;
682 : :
683 : : /*
684 : : * Compute resultRelationRelids and rowMarkRelids from resultRelations and
685 : : * rowMarks. These can be used for cheap membership checks.
686 : : */
61 melanieplageman@gmai 687 [ + + + + :GNC 396729 : foreach(lc, glob->resultRelations)
+ + ]
688 : 64742 : result->resultRelationRelids = bms_add_member(result->resultRelationRelids,
689 : : lfirst_int(lc));
690 [ + + + + : 342794 : foreach(lc, glob->finalrowmarks)
+ + ]
691 : 10807 : result->rowMarkRelids = bms_add_member(result->rowMarkRelids,
692 : 10807 : ((PlanRowMark *) lfirst(lc))->rti);
693 : :
6806 tgl@sss.pgh.pa.us 694 :CBC 331987 : result->relationOids = glob->relationOids;
6472 695 : 331987 : result->invalItems = glob->invalItems;
3120 rhaas@postgresql.org 696 : 331987 : result->paramExecTypes = glob->paramExecTypes;
697 : : /* utilityStmt should be null, but we might as well copy it */
3423 tgl@sss.pgh.pa.us 698 : 331987 : result->utilityStmt = parse->utilityStmt;
109 rhaas@postgresql.org 699 :GNC 331987 : result->elidedNodes = glob->elidedNodes;
3423 tgl@sss.pgh.pa.us 700 :CBC 331987 : result->stmt_location = parse->stmt_location;
701 : 331987 : result->stmt_len = parse->stmt_len;
702 : :
2991 andres@anarazel.de 703 : 331987 : result->jitFlags = PGJIT_NONE;
704 [ - + - - ]: 331987 : if (jit_enabled && jit_above_cost >= 0 &&
2991 andres@anarazel.de 705 [ # # ]:LBC (221789) : top_plan->total_cost > jit_above_cost)
706 : : {
707 : (490) : result->jitFlags |= PGJIT_PERFORM;
708 : :
709 : : /*
710 : : * Decide how much effort should be put into generating better code.
711 : : */
712 [ # # ]: (490) : if (jit_optimize_above_cost >= 0 &&
713 [ # # ]: (490) : top_plan->total_cost > jit_optimize_above_cost)
714 : (215) : result->jitFlags |= PGJIT_OPT3;
2985 715 [ # # ]: (490) : if (jit_inline_above_cost >= 0 &&
716 [ # # ]: (490) : top_plan->total_cost > jit_inline_above_cost)
717 : (215) : result->jitFlags |= PGJIT_INLINE;
718 : :
719 : : /*
720 : : * Decide which operations should be JITed.
721 : : */
2993 722 [ # # ]: (490) : if (jit_expressions)
723 : (490) : result->jitFlags |= PGJIT_EXPR;
2987 724 [ # # ]: (490) : if (jit_tuple_deforming)
725 : (490) : result->jitFlags |= PGJIT_DEFORM;
726 : : }
727 : :
728 : : /* Allow plugins to take control before we discard "glob" */
234 rhaas@postgresql.org 729 [ + + ]:GNC 331987 : if (planner_shutdown_hook)
730 : 87407 : (*planner_shutdown_hook) (glob, parse, query_string, result);
731 : :
2641 rhaas@postgresql.org 732 [ + + ]:CBC 331987 : if (glob->partition_directory != NULL)
733 : 9167 : DestroyPartitionDirectory(glob->partition_directory);
734 : :
7039 tgl@sss.pgh.pa.us 735 : 331987 : return result;
736 : : }
737 : :
738 : :
739 : : /*--------------------
740 : : * subquery_planner
741 : : * Invokes the planner on a subquery. We recurse to here for each
742 : : * sub-SELECT found in the query tree.
743 : : *
744 : : * glob is the global state for the current planner run.
745 : : * parse is the querytree produced by the parser & rewriter.
746 : : * plan_name is the name to assign to this subplan (NULL at the top level).
747 : : * parent_root is the immediate parent Query's info (NULL at the top level).
748 : : * alternative_root is a previously created PlannerInfo for which this query
749 : : * level is an alternative implementation, or else NULL.
750 : : * hasRecursion is true if this is a recursive WITH query.
751 : : * tuple_fraction is the fraction of tuples we expect will be retrieved.
752 : : * tuple_fraction is interpreted as explained for grouping_planner, below.
753 : : * setops is used for set operation subqueries to provide the subquery with
754 : : * the context in which it's being used so that Paths correctly sorted for the
755 : : * set operation can be generated. NULL when not planning a set operation
756 : : * child, or when a child of a set op that isn't interested in sorted input.
757 : : *
758 : : * Basically, this routine does the stuff that should only be done once
759 : : * per Query object. It then calls grouping_planner. At one time,
760 : : * grouping_planner could be invoked recursively on the same Query object;
761 : : * that's not currently true, but we keep the separation between the two
762 : : * routines anyway, in case we need it again someday.
763 : : *
764 : : * subquery_planner will be called recursively to handle sub-Query nodes
765 : : * found within the query's expressions and rangetable.
766 : : *
767 : : * Returns the PlannerInfo struct ("root") that contains all data generated
768 : : * while planning the subquery. In particular, the Path(s) attached to
769 : : * the (UPPERREL_FINAL, NULL) upperrel represent our conclusions about the
770 : : * cheapest way(s) to implement the query. The top level will select the
771 : : * best Path and pass it through createplan.c to produce a finished Plan.
772 : : *--------------------
773 : : */
774 : : PlannerInfo *
235 rhaas@postgresql.org 775 :GNC 399969 : subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name,
776 : : PlannerInfo *parent_root, PlannerInfo *alternative_root,
777 : : bool hasRecursion, double tuple_fraction,
778 : : SetOperationStmt *setops)
779 : : {
780 : : PlannerInfo *root;
781 : : List *newWithCheckOptions;
782 : : List *newHaving;
783 : : Bitmapset *havingCollationConflicts;
784 : : int havingIdx;
785 : : bool hasOuterJoins;
786 : : bool hasResultRTEs;
787 : : RelOptInfo *final_rel;
788 : : ListCell *l;
789 : :
790 : : /* Create a PlannerInfo data structure for this subquery */
7664 tgl@sss.pgh.pa.us 791 :CBC 399969 : root = makeNode(PlannerInfo);
792 : 399969 : root->parse = parse;
7040 793 : 399969 : root->glob = glob;
6447 794 [ + + ]: 399969 : root->query_level = parent_root ? parent_root->query_level + 1 : 1;
235 rhaas@postgresql.org 795 :GNC 399969 : root->plan_name = plan_name;
65 796 [ + + ]: 399969 : if (alternative_root != NULL)
797 : 1333 : root->alternative_plan_name = alternative_root->plan_name;
798 : : else
799 : 398636 : root->alternative_plan_name = plan_name;
6447 tgl@sss.pgh.pa.us 800 :CBC 399969 : root->parent_root = parent_root;
5015 801 : 399969 : root->plan_params = NIL;
3945 802 : 399969 : root->outer_params = NULL;
7070 803 : 399969 : root->planner_cxt = CurrentMemoryContext;
7040 804 : 399969 : root->init_plans = NIL;
6447 805 : 399969 : root->cte_plan_ids = NIL;
4364 806 : 399969 : root->multiexpr_params = NIL;
1216 807 : 399969 : root->join_domains = NIL;
7070 808 : 399969 : root->eq_classes = NIL;
2505 drowley@postgresql.o 809 : 399969 : root->ec_merging_done = false;
1216 tgl@sss.pgh.pa.us 810 : 399969 : root->last_rinfo_serial = 0;
1886 811 : 399969 : root->all_result_relids =
812 [ + + ]: 399969 : parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL;
813 : 399969 : root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */
7424 814 : 399969 : root->append_rel_list = NIL;
1886 815 : 399969 : root->row_identity_vars = NIL;
6060 816 : 399969 : root->rowMarks = NIL;
3736 817 : 399969 : memset(root->upper_rels, 0, sizeof(root->upper_rels));
3729 818 : 399969 : memset(root->upper_targets, 0, sizeof(root->upper_targets));
1228 819 : 399969 : root->processed_groupClause = NIL;
820 : 399969 : root->processed_distinctClause = NIL;
3736 821 : 399969 : root->processed_tlist = NIL;
1886 822 : 399969 : root->update_colnos = NIL;
4032 andres@anarazel.de 823 : 399969 : root->grouping_map = NULL;
3736 tgl@sss.pgh.pa.us 824 : 399969 : root->minmax_aggs = NIL;
3419 825 : 399969 : root->qual_security_level = 0;
2071 826 : 399969 : root->hasPseudoConstantQuals = false;
827 : 399969 : root->hasAlternativeSubPlans = false;
1382 828 : 399969 : root->placeholdersFrozen = false;
6447 829 : 399969 : root->hasRecursion = hasRecursion;
283 rhaas@postgresql.org 830 :GNC 399969 : root->assumeReplanning = false;
6447 tgl@sss.pgh.pa.us 831 [ + + ]:CBC 399969 : if (hasRecursion)
2696 832 : 694 : root->wt_param_id = assign_special_exec_param(root);
833 : : else
6447 834 : 399275 : root->wt_param_id = -1;
3736 835 : 399969 : root->non_recursive_path = NULL;
836 : :
837 : : /*
838 : : * Create the top-level join domain. This won't have valid contents until
839 : : * deconstruct_jointree fills it in, but the node needs to exist before
840 : : * that so we can build EquivalenceClasses referencing it.
841 : : */
1216 842 : 399969 : root->join_domains = list_make1(makeNode(JoinDomain));
843 : :
844 : : /*
845 : : * If there is a WITH list, process each WITH query and either convert it
846 : : * to RTE_SUBQUERY RTE(s) or build an initplan SubPlan structure for it.
847 : : */
6447 848 [ + + ]: 399969 : if (parse->cteList)
849 : 2209 : SS_process_ctes(root);
850 : :
851 : : /*
852 : : * If it's a MERGE command, transform the joinlist as appropriate.
853 : : */
1524 alvherre@alvh.no-ip. 854 : 399965 : transform_MERGE_to_join(parse);
855 : :
856 : : /*
857 : : * Scan the rangetable for relation RTEs and retrieve the necessary
858 : : * catalog information for each relation. Using this information, clear
859 : : * the inh flag for any relation that has no children, collect not-null
860 : : * attribute numbers for any relation that has column not-null
861 : : * constraints, and expand virtual generated columns for any relation that
862 : : * contains them. Note that this step does not descend into sublinks and
863 : : * subqueries; if we pull up any sublinks or subqueries below, their
864 : : * relation RTEs are processed just before pulling them up.
865 : : */
312 rguo@postgresql.org 866 :GNC 399965 : parse = root->parse = preprocess_relation_rtes(root);
867 : :
868 : : /*
869 : : * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
870 : : * that we don't need so many special cases to deal with that situation.
871 : : */
2679 tgl@sss.pgh.pa.us 872 :CBC 399965 : replace_empty_jointree(parse);
873 : :
874 : : /*
875 : : * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
876 : : * to transform them into joins. Note that this step does not descend
877 : : * into subqueries; if we pull up any subqueries below, their SubLinks are
878 : : * processed just before pulling them up.
879 : : */
8531 880 [ + + ]: 399965 : if (parse->hasSubLinks)
6495 881 : 31602 : pull_up_sublinks(root);
882 : :
883 : : /*
884 : : * Scan the rangetable for function RTEs, do const-simplification on them,
885 : : * and then inline them if possible (producing subqueries that might get
886 : : * pulled up next). Recursion issues here are handled in the same way as
887 : : * for SubLinks.
888 : : */
2494 889 : 399965 : preprocess_function_rtes(root);
890 : :
891 : : /*
892 : : * Check to see if any subqueries in the jointree can be merged into this
893 : : * query.
894 : : */
4098 895 : 399961 : pull_up_subqueries(root);
896 : :
897 : : /*
898 : : * If this is a simple UNION ALL query, flatten it into an appendrel. We
899 : : * do this now because it requires applying pull_up_subqueries to the leaf
900 : : * queries of the UNION ALL, which weren't touched above because they
901 : : * weren't referenced by the jointree (they will be after we do this).
902 : : */
5682 903 [ + + ]: 399961 : if (parse->setOperations)
904 : 5520 : flatten_simple_union_all(root);
905 : :
906 : : /*
907 : : * Survey the rangetable to see what kinds of entries are present. We can
908 : : * skip some later processing if relevant SQL features are not used; for
909 : : * example if there are no JOIN RTEs we can avoid the expense of doing
910 : : * flatten_join_alias_vars(). This must be done after we have finished
911 : : * adding rangetable entries, of course. (Note: actually, processing of
912 : : * inherited or partitioned rels can cause RTEs for their child tables to
913 : : * get added later; but those must all be RTE_RELATION entries, so they
914 : : * don't invalidate the conclusions drawn here.)
915 : : */
7664 916 : 399961 : root->hasJoinRTEs = false;
5025 917 : 399961 : root->hasLateralRTEs = false;
627 rguo@postgresql.org 918 : 399961 : root->group_rtindex = 0;
6498 tgl@sss.pgh.pa.us 919 : 399961 : hasOuterJoins = false;
2679 920 : 399961 : hasResultRTEs = false;
8039 neilc@samurai.com 921 [ + - + + : 1104025 : foreach(l, parse->rtable)
+ + ]
922 : : {
3189 tgl@sss.pgh.pa.us 923 : 704064 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
924 : :
2618 925 [ + + + + ]: 704064 : switch (rte->rtekind)
[ + + + +
+ ]
926 : : {
927 : 74778 : case RTE_JOIN:
928 : 74778 : root->hasJoinRTEs = true;
929 [ + + ]: 74778 : if (IS_OUTER_JOIN(rte->jointype))
930 : 37428 : hasOuterJoins = true;
931 : 74778 : break;
932 : 144895 : case RTE_RESULT:
933 : 144895 : hasResultRTEs = true;
934 : 144895 : break;
627 rguo@postgresql.org 935 : 4322 : case RTE_GROUP:
936 [ - + ]: 4322 : Assert(parse->hasGroupRTE);
937 : 4322 : root->group_rtindex = list_cell_number(parse->rtable, l) + 1;
938 : 4322 : break;
2618 tgl@sss.pgh.pa.us 939 : 480069 : default:
940 : : /* No work here for other RTE types */
941 : 480069 : break;
942 : : }
943 : :
5025 944 [ + + ]: 704064 : if (rte->lateral)
945 : 8138 : root->hasLateralRTEs = true;
946 : :
947 : : /*
948 : : * We can also determine the maximum security level required for any
949 : : * securityQuals now. Addition of inheritance-child RTEs won't affect
950 : : * this, because child tables don't have their own securityQuals; see
951 : : * expand_single_inheritance_child().
952 : : */
2617 953 [ + + ]: 704064 : if (rte->securityQuals)
954 [ - + ]: 2455 : root->qual_security_level = Max(root->qual_security_level,
955 : : list_length(rte->securityQuals));
956 : : }
957 : :
958 : : /*
959 : : * If we have now verified that the query target relation is
960 : : * non-inheriting, mark it as a leaf target.
961 : : */
1886 962 [ + + ]: 399961 : if (parse->resultRelation)
963 : : {
964 : 61071 : RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable);
965 : :
966 [ + + ]: 61071 : if (!rte->inh)
967 : 58755 : root->leaf_result_relids =
968 : 58755 : bms_make_singleton(parse->resultRelation);
969 : : }
970 : :
971 : : /*
972 : : * This would be a convenient time to check access permissions for all
973 : : * relations mentioned in the query, since it would be better to fail now,
974 : : * before doing any detailed planning. However, for historical reasons,
975 : : * we leave this to be done at executor startup.
976 : : *
977 : : * Note, however, that we do need to check access permissions for any view
978 : : * relations mentioned in the query, in order to prevent information being
979 : : * leaked by selectivity estimation functions, which only check view owner
980 : : * permissions on underlying tables (see all_rows_selectable() and its
981 : : * callers). This is a little ugly, because it means that access
982 : : * permissions for views will be checked twice, which is another reason
983 : : * why it would be better to do all the ACL checks here.
984 : : */
292 dean.a.rasheed@gmail 985 [ + - + + : 1103235 : foreach(l, parse->rtable)
+ + ]
986 : : {
987 : 703541 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
988 : :
989 [ + + ]: 703541 : if (rte->perminfoindex != 0 &&
990 [ + + ]: 380977 : rte->relkind == RELKIND_VIEW)
991 : : {
992 : : RTEPermissionInfo *perminfo;
993 : : bool result;
994 : :
995 : 16905 : perminfo = getRTEPermissionInfo(parse->rteperminfos, rte);
996 : 16905 : result = ExecCheckOneRelPerms(perminfo);
997 [ + + ]: 16905 : if (!result)
998 : 267 : aclcheck_error(ACLCHECK_NO_PRIV, OBJECT_VIEW,
999 : 267 : get_rel_name(perminfo->relid));
1000 : : }
1001 : : }
1002 : :
1003 : : /*
1004 : : * Preprocess RowMark information. We need to do this after subquery
1005 : : * pullup, so that all base relations are present.
1006 : : */
6060 tgl@sss.pgh.pa.us 1007 : 399694 : preprocess_rowmarks(root);
1008 : :
1009 : : /*
1010 : : * Set hasHavingQual to remember if HAVING clause is present. Needed
1011 : : * because preprocess_expression will reduce a constant-true condition to
1012 : : * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
1013 : : */
7664 1014 : 399694 : root->hasHavingQual = (parse->havingQual != NULL);
1015 : :
1016 : : /*
1017 : : * Do expression preprocessing on targetlist and quals, as well as other
1018 : : * random expressions in the querytree. Note that we do not need to
1019 : : * handle sort/group expressions explicitly, because they are actually
1020 : : * part of the targetlist.
1021 : : */
9566 1022 : 397048 : parse->targetList = (List *)
7664 1023 : 399694 : preprocess_expression(root, (Node *) parse->targetList,
1024 : : EXPRKIND_TARGET);
1025 : :
4699 sfrost@snowman.net 1026 : 397048 : newWithCheckOptions = NIL;
1027 [ + + + + : 399616 : foreach(l, parse->withCheckOptions)
+ + ]
1028 : : {
3189 tgl@sss.pgh.pa.us 1029 : 2568 : WithCheckOption *wco = lfirst_node(WithCheckOption, l);
1030 : :
4699 sfrost@snowman.net 1031 : 2568 : wco->qual = preprocess_expression(root, wco->qual,
1032 : : EXPRKIND_QUAL);
1033 [ + + ]: 2568 : if (wco->qual != NULL)
1034 : 2236 : newWithCheckOptions = lappend(newWithCheckOptions, wco);
1035 : : }
1036 : 397048 : parse->withCheckOptions = newWithCheckOptions;
1037 : :
7231 tgl@sss.pgh.pa.us 1038 : 397048 : parse->returningList = (List *)
1039 : 397048 : preprocess_expression(root, (Node *) parse->returningList,
1040 : : EXPRKIND_TARGET);
1041 : :
7664 1042 : 397048 : preprocess_qual_conditions(root, (Node *) parse->jointree);
1043 : :
1044 : 397048 : parse->havingQual = preprocess_expression(root, parse->havingQual,
1045 : : EXPRKIND_QUAL);
1046 : :
5951 1047 [ + + + + : 399495 : foreach(l, parse->windowClause)
+ + ]
1048 : : {
3189 1049 : 2447 : WindowClause *wc = lfirst_node(WindowClause, l);
1050 : :
1051 : : /* partitionClause/orderClause are sort/group expressions */
5951 1052 : 2447 : wc->startOffset = preprocess_expression(root, wc->startOffset,
1053 : : EXPRKIND_LIMIT);
1054 : 2447 : wc->endOffset = preprocess_expression(root, wc->endOffset,
1055 : : EXPRKIND_LIMIT);
1056 : : }
1057 : :
7664 1058 : 397048 : parse->limitOffset = preprocess_expression(root, parse->limitOffset,
1059 : : EXPRKIND_LIMIT);
1060 : 397048 : parse->limitCount = preprocess_expression(root, parse->limitCount,
1061 : : EXPRKIND_LIMIT);
1062 : :
4040 andres@anarazel.de 1063 [ + + ]: 397048 : if (parse->onConflict)
1064 : : {
3671 tgl@sss.pgh.pa.us 1065 : 3576 : parse->onConflict->arbiterElems = (List *)
1066 : 1788 : preprocess_expression(root,
1067 : 1788 : (Node *) parse->onConflict->arbiterElems,
1068 : : EXPRKIND_ARBITER_ELEM);
1069 : 3576 : parse->onConflict->arbiterWhere =
1070 : 1788 : preprocess_expression(root,
1071 : 1788 : parse->onConflict->arbiterWhere,
1072 : : EXPRKIND_QUAL);
4040 andres@anarazel.de 1073 : 3576 : parse->onConflict->onConflictSet = (List *)
3671 tgl@sss.pgh.pa.us 1074 : 1788 : preprocess_expression(root,
1075 : 1788 : (Node *) parse->onConflict->onConflictSet,
1076 : : EXPRKIND_TARGET);
4040 andres@anarazel.de 1077 : 1788 : parse->onConflict->onConflictWhere =
3671 tgl@sss.pgh.pa.us 1078 : 1788 : preprocess_expression(root,
1079 : 1788 : parse->onConflict->onConflictWhere,
1080 : : EXPRKIND_QUAL);
1081 : : /* exclRelTlist contains only Vars, so no preprocessing needed */
1082 : : }
1083 : :
1524 alvherre@alvh.no-ip. 1084 [ + + + + : 399315 : foreach(l, parse->mergeActionList)
+ + ]
1085 : : {
1086 : 2267 : MergeAction *action = (MergeAction *) lfirst(l);
1087 : :
1088 : 2267 : action->targetList = (List *)
1089 : 2267 : preprocess_expression(root,
1090 : 2267 : (Node *) action->targetList,
1091 : : EXPRKIND_TARGET);
1092 : 2267 : action->qual =
1093 : 2267 : preprocess_expression(root,
1094 : : (Node *) action->qual,
1095 : : EXPRKIND_QUAL);
1096 : : }
1097 : :
791 dean.a.rasheed@gmail 1098 : 397048 : parse->mergeJoinCondition =
1099 : 397048 : preprocess_expression(root, parse->mergeJoinCondition, EXPRKIND_QUAL);
1100 : :
7424 tgl@sss.pgh.pa.us 1101 : 397048 : root->append_rel_list = (List *)
1102 : 397048 : preprocess_expression(root, (Node *) root->append_rel_list,
1103 : : EXPRKIND_APPINFO);
1104 : :
1105 : : /* Also need to preprocess expressions within RTEs */
8039 neilc@samurai.com 1106 [ + - + + : 1097275 : foreach(l, parse->rtable)
+ + ]
1107 : : {
3189 tgl@sss.pgh.pa.us 1108 : 700227 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
1109 : : int kind;
1110 : : ListCell *lcsq;
1111 : :
4033 simon@2ndQuadrant.co 1112 [ + + ]: 700227 : if (rte->rtekind == RTE_RELATION)
1113 : : {
1114 [ + + ]: 367176 : if (rte->tablesample)
3962 tgl@sss.pgh.pa.us 1115 : 180 : rte->tablesample = (TableSampleClause *)
1116 : 180 : preprocess_expression(root,
1117 : 180 : (Node *) rte->tablesample,
1118 : : EXPRKIND_TABLESAMPLE);
1119 : : }
4033 simon@2ndQuadrant.co 1120 [ + + ]: 333051 : else if (rte->rtekind == RTE_SUBQUERY)
1121 : : {
1122 : : /*
1123 : : * We don't want to do all preprocessing yet on the subquery's
1124 : : * expressions, since that will happen when we plan it. But if it
1125 : : * contains any join aliases of our level, those have to get
1126 : : * expanded now, because planning of the subquery won't do it.
1127 : : * That's only possible if the subquery is LATERAL.
1128 : : */
5020 tgl@sss.pgh.pa.us 1129 [ + + + + ]: 64510 : if (rte->lateral && root->hasJoinRTEs)
1130 : 1591 : rte->subquery = (Query *)
1216 1131 : 1591 : flatten_join_alias_vars(root, root->parse,
2678 1132 : 1591 : (Node *) rte->subquery);
1133 : : }
5020 1134 [ + + ]: 268541 : else if (rte->rtekind == RTE_FUNCTION)
1135 : : {
1136 : : /* Preprocess the function expression(s) fully */
1137 [ + + ]: 35914 : kind = rte->lateral ? EXPRKIND_RTFUNC_LATERAL : EXPRKIND_RTFUNC;
3370 alvherre@alvh.no-ip. 1138 : 35914 : rte->functions = (List *)
1139 : 35914 : preprocess_expression(root, (Node *) rte->functions, kind);
1140 : : }
1141 [ + + ]: 232627 : else if (rte->rtekind == RTE_TABLEFUNC)
1142 : : {
1143 : : /* Preprocess the function expression(s) fully */
1144 [ + + ]: 517 : kind = rte->lateral ? EXPRKIND_TABLEFUNC_LATERAL : EXPRKIND_TABLEFUNC;
1145 : 517 : rte->tablefunc = (TableFunc *)
1146 : 517 : preprocess_expression(root, (Node *) rte->tablefunc, kind);
1147 : : }
7241 mail@joeconway.com 1148 [ + + ]: 232110 : else if (rte->rtekind == RTE_VALUES)
1149 : : {
1150 : : /* Preprocess the values lists fully */
5020 tgl@sss.pgh.pa.us 1151 [ + + ]: 6890 : kind = rte->lateral ? EXPRKIND_VALUES_LATERAL : EXPRKIND_VALUES;
7241 mail@joeconway.com 1152 : 6890 : rte->values_lists = (List *)
5020 tgl@sss.pgh.pa.us 1153 : 6890 : preprocess_expression(root, (Node *) rte->values_lists, kind);
1154 : : }
627 rguo@postgresql.org 1155 [ + + ]: 225220 : else if (rte->rtekind == RTE_GROUP)
1156 : : {
1157 : : /* Preprocess the groupexprs list fully */
1158 : 4322 : rte->groupexprs = (List *)
1159 : 4322 : preprocess_expression(root, (Node *) rte->groupexprs,
1160 : : EXPRKIND_GROUPEXPR);
1161 : : }
1162 : :
1163 : : /*
1164 : : * Process each element of the securityQuals list as if it were a
1165 : : * separate qual expression (as indeed it is). We need to do it this
1166 : : * way to get proper canonicalization of AND/OR structure. Note that
1167 : : * this converts each element into an implicit-AND sublist.
1168 : : */
3419 tgl@sss.pgh.pa.us 1169 [ + + + + : 703032 : foreach(lcsq, rte->securityQuals)
+ + ]
1170 : : {
1171 : 2805 : lfirst(lcsq) = preprocess_expression(root,
1172 : 2805 : (Node *) lfirst(lcsq),
1173 : : EXPRKIND_QUAL);
1174 : : }
1175 : : }
1176 : :
1177 : : /*
1178 : : * Now that we are done preprocessing expressions, and in particular done
1179 : : * flattening join alias variables, get rid of the joinaliasvars lists.
1180 : : * They no longer match what expressions in the rest of the tree look
1181 : : * like, because we have not preprocessed expressions in those lists (and
1182 : : * do not want to; for example, expanding a SubLink there would result in
1183 : : * a useless unreferenced subplan). Leaving them in place simply creates
1184 : : * a hazard for later scans of the tree. We could try to prevent that by
1185 : : * using QTW_IGNORE_JOINALIASES in every tree scan done after this point,
1186 : : * but that doesn't sound very reliable.
1187 : : */
3140 1188 [ + + ]: 397048 : if (root->hasJoinRTEs)
1189 : : {
1190 [ + - + + : 260197 : foreach(l, parse->rtable)
+ + ]
1191 : : {
1192 : 213263 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
1193 : :
1194 : 213263 : rte->joinaliasvars = NIL;
1195 : : }
1196 : : }
1197 : :
1198 : : /*
1199 : : * Before we flatten GROUP Vars, check which HAVING clauses have collation
1200 : : * conflicts. When GROUP BY uses a nondeterministic collation, values
1201 : : * that are "equal" for grouping may be distinguishable under a different
1202 : : * collation. If such a HAVING clause were moved to WHERE, it would
1203 : : * filter individual rows before grouping, potentially eliminating some
1204 : : * members of a group and thereby changing aggregate results.
1205 : : *
1206 : : * We do this check before flatten_group_exprs because we can easily
1207 : : * identify grouping expressions by checking whether a Var references
1208 : : * RTE_GROUP, and such Vars directly carry the GROUP BY collation as their
1209 : : * varcollid. After flattening, these Vars are replaced by the underlying
1210 : : * expressions, and we would have to match expressions in the HAVING
1211 : : * clause back to grouping expressions, which is much more complex.
1212 : : */
29 rguo@postgresql.org 1213 [ + + ]: 397048 : if (parse->hasGroupRTE)
1214 : : havingCollationConflicts =
1215 : 4322 : find_having_collation_conflicts(parse, root->group_rtindex);
1216 : : else
1217 : 392726 : havingCollationConflicts = NULL;
1218 : :
1219 : : /*
1220 : : * Replace any Vars in the subquery's targetlist and havingQual that
1221 : : * reference GROUP outputs with the underlying grouping expressions.
1222 : : *
1223 : : * Note that we need to perform this replacement after we've preprocessed
1224 : : * the grouping expressions. This is to ensure that there is only one
1225 : : * instance of SubPlan for each SubLink contained within the grouping
1226 : : * expressions.
1227 : : */
627 1228 [ + + ]: 397048 : if (parse->hasGroupRTE)
1229 : : {
1230 : 4322 : parse->targetList = (List *)
1231 : 4322 : flatten_group_exprs(root, root->parse, (Node *) parse->targetList);
1232 : 4322 : parse->havingQual =
1233 : 4322 : flatten_group_exprs(root, root->parse, parse->havingQual);
1234 : : }
1235 : :
1236 : : /* Constant-folding might have removed all set-returning functions */
1237 [ + + ]: 397048 : if (parse->hasTargetSRFs)
1238 : 10404 : parse->hasTargetSRFs = expression_returns_set((Node *) parse->targetList);
1239 : :
1240 : : /*
1241 : : * If we have grouping sets, expand the groupingSets tree of this query to
1242 : : * a flat list of grouping sets. We need to do this before optimizing
1243 : : * HAVING, since we can't easily tell if there's an empty grouping set
1244 : : * until we have this representation.
1245 : : */
221 1246 [ + + ]: 397048 : if (parse->groupingSets)
1247 : : {
1248 : 905 : parse->groupingSets =
1249 : 905 : expand_grouping_sets(parse->groupingSets, parse->groupDistinct, -1);
1250 : : }
1251 : :
1252 : : /*
1253 : : * In some cases we may want to transfer a HAVING clause into WHERE. We
1254 : : * cannot do so if the HAVING clause contains aggregates (obviously) or
1255 : : * volatile functions (since a HAVING clause is supposed to be executed
1256 : : * only once per group). We also can't do this if there are any grouping
1257 : : * sets and the clause references any columns that are nullable by the
1258 : : * grouping sets; the nulled values of those columns are not available
1259 : : * before the grouping step. (The test on groupClause might seem wrong,
1260 : : * but it's okay: it's just an optimization to avoid running pull_varnos
1261 : : * when there cannot be any Vars in the HAVING clause.)
1262 : : *
1263 : : * We also cannot do this if the HAVING clause uses a different collation
1264 : : * than the GROUP BY for any grouping expression whose GROUP BY collation
1265 : : * is nondeterministic. This is detected before flatten_group_exprs (see
1266 : : * find_having_collation_conflicts above) and recorded in the
1267 : : * havingCollationConflicts bitmapset. The bitmapset indexes remain valid
1268 : : * here because flatten_group_exprs uses expression_tree_mutator, which
1269 : : * preserves the list length and ordering of havingQual.
1270 : : *
1271 : : * Also, it may be that the clause is so expensive to execute that we're
1272 : : * better off doing it only once per group, despite the loss of
1273 : : * selectivity. This is hard to estimate short of doing the entire
1274 : : * planning process twice, so we use a heuristic: clauses containing
1275 : : * subplans are left in HAVING. Otherwise, we move or copy the HAVING
1276 : : * clause into WHERE, in hopes of eliminating tuples before aggregation
1277 : : * instead of after.
1278 : : *
1279 : : * If the query has no empty grouping set then we can simply move such a
1280 : : * clause into WHERE; any group that fails the clause will not be in the
1281 : : * output because none of its tuples will reach the grouping or
1282 : : * aggregation stage. Otherwise we have to keep the clause in HAVING to
1283 : : * ensure that we don't emit a bogus aggregated row. But then the HAVING
1284 : : * clause must be degenerate (variable-free), so we can copy it into WHERE
1285 : : * so that query_planner() can use it in a gating Result node. (This could
1286 : : * be done better, but it seems not worth optimizing.)
1287 : : *
1288 : : * Note that a HAVING clause may contain expressions that are not fully
1289 : : * preprocessed. This can happen if these expressions are part of
1290 : : * grouping items. In such cases, they are replaced with GROUP Vars in
1291 : : * the parser and then replaced back after we're done with expression
1292 : : * preprocessing on havingQual. This is not an issue if the clause
1293 : : * remains in HAVING, because these expressions will be matched to lower
1294 : : * target items in setrefs.c. However, if the clause is moved or copied
1295 : : * into WHERE, we need to ensure that these expressions are fully
1296 : : * preprocessed.
1297 : : *
1298 : : * Note that both havingQual and parse->jointree->quals are in
1299 : : * implicitly-ANDed-list form at this point, even though they are declared
1300 : : * as Node *.
1301 : : */
9263 tgl@sss.pgh.pa.us 1302 : 397048 : newHaving = NIL;
29 rguo@postgresql.org 1303 : 397048 : havingIdx = 0;
8039 neilc@samurai.com 1304 [ + + + + : 398319 : foreach(l, (List *) parse->havingQual)
+ + ]
1305 : : {
1306 : 1271 : Node *havingclause = (Node *) lfirst(l);
1307 : :
598 rguo@postgresql.org 1308 [ + + + - ]: 1862 : if (contain_agg_clause(havingclause) ||
7751 tgl@sss.pgh.pa.us 1309 [ + - ]: 1182 : contain_volatile_functions(havingclause) ||
598 rguo@postgresql.org 1310 [ + + ]: 1182 : contain_subplans(havingclause) ||
29 1311 : 591 : bms_is_member(havingIdx, havingCollationConflicts) ||
598 1312 [ + + + + : 611 : (parse->groupClause && parse->groupingSets &&
+ + ]
1313 : 100 : bms_is_member(root->group_rtindex, pull_varnos(root, havingclause))))
1314 : : {
1315 : : /* keep it in HAVING */
9263 tgl@sss.pgh.pa.us 1316 : 820 : newHaving = lappend(newHaving, havingclause);
1317 : : }
221 rguo@postgresql.org 1318 [ + + ]: 451 : else if (parse->groupClause &&
1319 [ + + ]: 421 : (parse->groupingSets == NIL ||
1320 [ + + ]: 40 : (List *) linitial(parse->groupingSets) != NIL))
7751 tgl@sss.pgh.pa.us 1321 : 411 : {
1322 : : /* There is GROUP BY, but no empty grouping set */
1323 : : Node *whereclause;
1324 : :
1325 : : /* Preprocess the HAVING clause fully */
627 rguo@postgresql.org 1326 : 411 : whereclause = preprocess_expression(root, havingclause,
1327 : : EXPRKIND_QUAL);
1328 : : /* ... and move it to WHERE */
9263 tgl@sss.pgh.pa.us 1329 : 411 : parse->jointree->quals = (Node *)
627 rguo@postgresql.org 1330 : 411 : list_concat((List *) parse->jointree->quals,
1331 : : (List *) whereclause);
1332 : : }
1333 : : else
1334 : : {
1335 : : /* There is an empty grouping set (perhaps implicitly) */
1336 : : Node *whereclause;
1337 : :
1338 : : /* Preprocess the HAVING clause fully */
1339 : 40 : whereclause = preprocess_expression(root, copyObject(havingclause),
1340 : : EXPRKIND_QUAL);
1341 : : /* ... and put a copy in WHERE */
7751 tgl@sss.pgh.pa.us 1342 : 80 : parse->jointree->quals = (Node *)
627 rguo@postgresql.org 1343 : 40 : list_concat((List *) parse->jointree->quals,
1344 : : (List *) whereclause);
1345 : : /* ... and also keep it in HAVING */
7751 tgl@sss.pgh.pa.us 1346 : 40 : newHaving = lappend(newHaving, havingclause);
1347 : : }
1348 : :
29 rguo@postgresql.org 1349 : 1271 : havingIdx++;
1350 : : }
9263 tgl@sss.pgh.pa.us 1351 : 397048 : parse->havingQual = (Node *) newHaving;
1352 : :
1353 : : /*
1354 : : * If we have any outer joins, try to reduce them to plain inner joins.
1355 : : * This step is most easily done after we've done expression
1356 : : * preprocessing.
1357 : : */
6498 1358 [ + + ]: 397048 : if (hasOuterJoins)
7664 1359 : 25966 : reduce_outer_joins(root);
1360 : :
1361 : : /*
1362 : : * If we have any RTE_RESULT relations, see if they can be deleted from
1363 : : * the jointree. We also rely on this processing to flatten single-child
1364 : : * FromExprs underneath outer joins. This step is most effectively done
1365 : : * after we've done expression preprocessing and outer join reduction.
1366 : : */
1216 1367 [ + + + + ]: 397048 : if (hasResultRTEs || hasOuterJoins)
2679 1368 : 167025 : remove_useless_result_rtes(root);
1369 : :
1370 : : /*
1371 : : * Do the main planning.
1372 : : */
739 rhaas@postgresql.org 1373 : 397048 : grouping_planner(root, tuple_fraction, setops);
1374 : :
1375 : : /*
1376 : : * Capture the set of outer-level param IDs we have access to, for use in
1377 : : * extParam/allParam calculations later.
1378 : : */
3945 tgl@sss.pgh.pa.us 1379 : 397001 : SS_identify_outer_params(root);
1380 : :
1381 : : /*
1382 : : * If any initPlans were created in this query level, adjust the surviving
1383 : : * Paths' costs and parallel-safety flags to account for them. The
1384 : : * initPlans won't actually get attached to the plan tree till
1385 : : * create_plan() runs, but we must include their effects now.
1386 : : */
3736 1387 : 397001 : final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
1388 : 397001 : SS_charge_for_initplans(root, final_rel);
1389 : :
1390 : : /*
1391 : : * Make sure we've identified the cheapest Path for the final rel. (By
1392 : : * doing this here not in grouping_planner, we include initPlan costs in
1393 : : * the decision, though it's unlikely that will change anything.)
1394 : : */
1395 : 397001 : set_cheapest(final_rel);
1396 : :
1397 : 397001 : return root;
1398 : : }
1399 : :
1400 : : /*
1401 : : * preprocess_expression
1402 : : * Do subquery_planner's preprocessing work for an expression,
1403 : : * which can be a targetlist, a WHERE clause (including JOIN/ON
1404 : : * conditions), a HAVING clause, or a few other things.
1405 : : */
1406 : : static Node *
7664 1407 : 3348125 : preprocess_expression(PlannerInfo *root, Node *expr, int kind)
1408 : : {
1409 : : /*
1410 : : * Fall out quickly if expression is empty. This occurs often enough to
1411 : : * be worth checking. Note that null->null is the correct conversion for
1412 : : * implicit-AND result format, too.
1413 : : */
7670 1414 [ + + ]: 3348125 : if (expr == NULL)
1415 : 2629350 : return NULL;
1416 : :
1417 : : /*
1418 : : * If the query has any join RTEs, replace join alias variables with
1419 : : * base-relation variables. We must do this first, since any expressions
1420 : : * we may extract from the joinaliasvars lists have not been preprocessed.
1421 : : * For example, if we did this after sublink processing, sublinks expanded
1422 : : * out from join aliases would not get processed. But we can skip this in
1423 : : * non-lateral RTE functions, VALUES lists, and TABLESAMPLE clauses, since
1424 : : * they can't contain any Vars of the current query level.
1425 : : */
5020 1426 [ + + + + ]: 718775 : if (root->hasJoinRTEs &&
3962 1427 [ + + + - ]: 334232 : !(kind == EXPRKIND_RTFUNC ||
1428 [ + + ]: 166968 : kind == EXPRKIND_VALUES ||
1429 : : kind == EXPRKIND_TABLESAMPLE ||
1430 : : kind == EXPRKIND_TABLEFUNC))
1216 1431 : 166953 : expr = flatten_join_alias_vars(root, root->parse, expr);
1432 : :
1433 : : /*
1434 : : * Simplify constant expressions. For function RTEs, this was already
1435 : : * done by preprocess_function_rtes. (But note we must do it again for
1436 : : * EXPRKIND_RTFUNC_LATERAL, because those might by now contain
1437 : : * un-simplified subexpressions inserted by flattening of subqueries or
1438 : : * join alias variables.)
1439 : : *
1440 : : * Note: an essential effect of this is to convert named-argument function
1441 : : * calls to positional notation and insert the current actual values of
1442 : : * any default arguments for functions. To ensure that happens, we *must*
1443 : : * process all expressions here. Previous PG versions sometimes skipped
1444 : : * const-simplification if it didn't seem worth the trouble, but we can't
1445 : : * do that anymore.
1446 : : *
1447 : : * Note: this also flattens nested AND and OR expressions into N-argument
1448 : : * form. All processing of a qual expression after this point must be
1449 : : * careful to maintain AND/OR flatness --- that is, do not generate a tree
1450 : : * with AND directly under AND, nor OR directly under OR.
1451 : : */
1689 1452 [ + + ]: 718775 : if (kind != EXPRKIND_RTFUNC)
2494 1453 : 687389 : expr = eval_const_expressions(root, expr);
1454 : :
1455 : : /*
1456 : : * If it's a qual or havingQual, canonicalize it.
1457 : : */
8531 1458 [ + + ]: 716129 : if (kind == EXPRKIND_QUAL)
1459 : : {
3002 1460 : 266917 : expr = (Node *) canonicalize_qual((Expr *) expr, false);
1461 : :
1462 : : #ifdef OPTIMIZER_DEBUG
1463 : : printf("After canonicalize_qual()\n");
1464 : : pprint(expr);
1465 : : #endif
1466 : : }
1467 : :
1468 : : /*
1469 : : * Check for ANY ScalarArrayOpExpr with Const arrays and set the
1470 : : * hashfuncid of any that might execute more quickly by using hash lookups
1471 : : * instead of a linear search.
1472 : : */
1878 drowley@postgresql.o 1473 [ + + + + ]: 716129 : if (kind == EXPRKIND_QUAL || kind == EXPRKIND_TARGET)
1474 : : {
1475 : 656844 : convert_saop_to_hashed_saop(expr);
1476 : : }
1477 : :
1478 : : /* Expand SubLinks to SubPlans */
7664 tgl@sss.pgh.pa.us 1479 [ + + ]: 716129 : if (root->parse->hasSubLinks)
7040 1480 : 92405 : expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
1481 : :
1482 : : /*
1483 : : * XXX do not insert anything here unless you have grokked the comments in
1484 : : * SS_replace_correlation_vars ...
1485 : : */
1486 : :
1487 : : /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
1488 [ + + ]: 716129 : if (root->query_level > 1)
1489 : 150757 : expr = SS_replace_correlation_vars(root, expr);
1490 : :
1491 : : /*
1492 : : * If it's a qual or havingQual, convert it to implicit-AND format. (We
1493 : : * don't want to do this before eval_const_expressions, since the latter
1494 : : * would be unable to simplify a top-level AND correctly. Also,
1495 : : * SS_process_sublinks expects explicit-AND format.)
1496 : : */
8174 1497 [ + + ]: 716129 : if (kind == EXPRKIND_QUAL)
1498 : 266917 : expr = (Node *) make_ands_implicit((Expr *) expr);
1499 : :
9374 1500 : 716129 : return expr;
1501 : : }
1502 : :
1503 : : /*
1504 : : * preprocess_qual_conditions
1505 : : * Recursively scan the query's jointree and do subquery_planner's
1506 : : * preprocessing work on each qual condition found therein.
1507 : : */
1508 : : static void
7664 1509 : 1009484 : preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
1510 : : {
9374 1511 [ - + ]: 1009484 : if (jtnode == NULL)
9374 tgl@sss.pgh.pa.us 1512 :UBC 0 : return;
9374 tgl@sss.pgh.pa.us 1513 [ + + ]:CBC 1009484 : if (IsA(jtnode, RangeTblRef))
1514 : : {
1515 : : /* nothing to do here */
1516 : : }
1517 [ + + ]: 495841 : else if (IsA(jtnode, FromExpr))
1518 : : {
1519 : 412225 : FromExpr *f = (FromExpr *) jtnode;
1520 : : ListCell *l;
1521 : :
1522 [ + + + + : 857429 : foreach(l, f->fromlist)
+ + ]
7664 1523 : 445204 : preprocess_qual_conditions(root, lfirst(l));
1524 : :
1525 : 412225 : f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
1526 : : }
9374 1527 [ + - ]: 83616 : else if (IsA(jtnode, JoinExpr))
1528 : : {
1529 : 83616 : JoinExpr *j = (JoinExpr *) jtnode;
1530 : :
7664 1531 : 83616 : preprocess_qual_conditions(root, j->larg);
1532 : 83616 : preprocess_qual_conditions(root, j->rarg);
1533 : :
1534 : 83616 : j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
1535 : : }
1536 : : else
8345 tgl@sss.pgh.pa.us 1537 [ # # ]:UBC 0 : elog(ERROR, "unrecognized node type: %d",
1538 : : (int) nodeTag(jtnode));
1539 : : }
1540 : :
1541 : : /*
1542 : : * find_having_collation_conflicts
1543 : : * Identify HAVING clauses that must not be moved to WHERE due to collation
1544 : : * mismatches with GROUP BY.
1545 : : *
1546 : : * This must be called before flatten_group_exprs, while the HAVING clause
1547 : : * still contains GROUP Vars (Vars referencing RTE_GROUP). These GROUP Vars
1548 : : * carry the GROUP BY collation as their varcollid. A GROUP Var with a
1549 : : * nondeterministic varcollid conflicts whenever some collation-aware ancestor
1550 : : * on its path applies a different inputcollid: that operator would distinguish
1551 : : * values which the GROUP BY considers equal, so the clause is unsafe to push
1552 : : * to WHERE.
1553 : : *
1554 : : * Returns a Bitmapset of zero-based indexes into the havingQual list for
1555 : : * clauses that have collation conflicts and must stay in HAVING.
1556 : : */
1557 : : static Bitmapset *
29 rguo@postgresql.org 1558 :CBC 4322 : find_having_collation_conflicts(Query *parse, Index group_rtindex)
1559 : : {
1560 : 4322 : Bitmapset *result = NULL;
1561 : : having_collation_ctx ctx;
1562 : : int idx;
1563 : :
1564 [ + + ]: 4322 : if (parse->havingQual == NULL)
1565 : 3484 : return NULL;
1566 : :
1567 : 838 : ctx.group_rtindex = group_rtindex;
1568 : 838 : ctx.ancestor_collids = NIL;
1569 : :
1570 : 838 : idx = 0;
1571 [ + - + + : 2653 : foreach_ptr(Node, clause, (List *) parse->havingQual)
+ + ]
1572 : : {
1573 [ + + ]: 977 : if (having_collation_conflict_walker(clause, &ctx))
1574 : 80 : result = bms_add_member(result, idx);
1575 : 977 : idx++;
1576 [ - + ]: 977 : Assert(ctx.ancestor_collids == NIL);
1577 : : }
1578 : :
1579 : 838 : return result;
1580 : : }
1581 : :
1582 : : /*
1583 : : * Walker function for find_having_collation_conflicts.
1584 : : *
1585 : : * Walk the clause top-down, maintaining a stack of inputcollids contributed
1586 : : * by collation-aware ancestors. At each GROUP Var with a nondeterministic
1587 : : * varcollid, the clause has a conflict if any ancestor's inputcollid differs
1588 : : * from the GROUP Var's varcollid. Most collation-aware nodes expose their
1589 : : * inputcollid through exprInputCollation(). Two structural exceptions need
1590 : : * special handling:
1591 : : *
1592 : : * - RowCompareExpr carries one inputcollid per column in inputcollids[], so we
1593 : : * descend into its (largs[i], rargs[i]) pairs explicitly with the matching
1594 : : * collation pushed onto the stack.
1595 : : *
1596 : : * - A simple CASE (CaseExpr with a non-NULL arg) holds the arg outside the
1597 : : * WHEN's OpExpr, even though the WHEN's OpExpr is the place where the
1598 : : * comparison's inputcollid lives. Parse analysis builds each WHEN as
1599 : : * "OpExpr(CaseTestExpr op val)" -- the CaseTestExpr is a placeholder for
1600 : : * the arg. Before walking cexpr->arg we therefore push every WHEN's
1601 : : * inputcollid onto the ancestor stack, so a GROUP Var at the arg is
1602 : : * checked against the same collations the WHEN comparisons would apply.
1603 : : * The WHEN bodies and defresult are then walked under the unchanged stack
1604 : : * so their own collation contexts are picked up by the default path.
1605 : : */
1606 : : static bool
1607 : 4306 : having_collation_conflict_walker(Node *node, having_collation_ctx *ctx)
1608 : : {
1609 : : Oid this_collid;
1610 : : bool result;
1611 : :
1612 [ + + ]: 4306 : if (node == NULL)
1613 : 453 : return false;
1614 : :
1615 [ + + ]: 3853 : if (IsA(node, Var))
1616 : : {
1617 : 928 : Var *var = (Var *) node;
1618 : :
1619 : : /* We should not see any upper-level Vars here */
1620 [ - + ]: 928 : Assert(var->varlevelsup == 0);
1621 : :
1622 [ + + ]: 928 : if (var->varno == ctx->group_rtindex &&
1623 [ + + ]: 544 : OidIsValid(var->varcollid) &&
1624 [ + + ]: 361 : !get_collation_isdeterministic(var->varcollid))
1625 : : {
1626 [ + - + + : 280 : foreach_oid(collid, ctx->ancestor_collids)
+ + ]
1627 : : {
1628 [ + + ]: 160 : if (collid != var->varcollid)
1629 : 80 : return true;
1630 : : }
1631 : : }
1632 : 848 : return false;
1633 : : }
1634 : :
1635 [ + + ]: 2925 : if (IsA(node, RowCompareExpr))
1636 : : {
1637 : 10 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1638 : : ListCell *lc_l;
1639 : : ListCell *lc_r;
1640 : : ListCell *lc_c;
1641 : :
1642 : : /*
1643 : : * Each column of a row comparison is compared under its own
1644 : : * inputcollids[i]. Walk each (largs[i], rargs[i]) pair with that
1645 : : * collation pushed, so a Var in column i is checked against the
1646 : : * collation that actually applies to it.
1647 : : */
1648 : 10 : forthree(lc_l, rcexpr->largs,
[ + - + -
+ - + - +
- + - + -
+ - + - +
- ]
1649 : : lc_r, rcexpr->rargs,
1650 : : lc_c, rcexpr->inputcollids)
1651 : : {
1652 : 10 : Oid collid = lfirst_oid(lc_c);
1653 : : bool found;
1654 : :
1655 [ + - ]: 10 : if (OidIsValid(collid))
1656 : 10 : ctx->ancestor_collids = lappend_oid(ctx->ancestor_collids,
1657 : : collid);
1658 : :
1659 : 10 : found = having_collation_conflict_walker((Node *) lfirst(lc_l),
1660 [ - + - - ]: 10 : ctx) ||
29 rguo@postgresql.org 1661 :UBC 0 : having_collation_conflict_walker((Node *) lfirst(lc_r),
1662 : : ctx);
1663 : :
29 rguo@postgresql.org 1664 [ + - ]:CBC 10 : if (OidIsValid(collid))
1665 : 10 : ctx->ancestor_collids =
1666 : 10 : list_delete_last(ctx->ancestor_collids);
1667 : :
1668 [ + - ]: 10 : if (found)
1669 : 10 : return true;
1670 : : }
29 rguo@postgresql.org 1671 :UBC 0 : return false;
1672 : : }
1673 : :
22 rguo@postgresql.org 1674 [ + + + + ]:CBC 2915 : if (IsA(node, CaseExpr) && ((CaseExpr *) node)->arg != NULL)
1675 : : {
1676 : 30 : CaseExpr *cexpr = (CaseExpr *) node;
1677 : 30 : int saved_len = list_length(ctx->ancestor_collids);
1678 : : bool found;
1679 : :
1680 : : /*
1681 : : * Push every WHEN's inputcollid before walking cexpr->arg, since each
1682 : : * WHEN implicitly compares the arg under that inputcollid.
1683 : : */
1684 [ + - + + : 90 : foreach_node(CaseWhen, cw, cexpr->args)
+ + ]
1685 : : {
1686 : 30 : Oid collid = exprInputCollation((Node *) cw->expr);
1687 : :
1688 [ + - ]: 30 : if (OidIsValid(collid))
1689 : 30 : ctx->ancestor_collids = lappend_oid(ctx->ancestor_collids,
1690 : : collid);
1691 : : }
1692 : :
1693 : 30 : found = having_collation_conflict_walker((Node *) cexpr->arg, ctx);
1694 : :
1695 : 30 : ctx->ancestor_collids = list_truncate(ctx->ancestor_collids,
1696 : : saved_len);
1697 : :
1698 [ + + ]: 30 : if (found)
1699 : 20 : return true;
1700 : :
1701 : : /*
1702 : : * Walk the WHEN bodies and defresult under the unchanged ancestor
1703 : : * stack; any inputcollids inside them are picked up by the default
1704 : : * path.
1705 : : */
1706 [ + - + + : 30 : foreach_node(CaseWhen, cw, cexpr->args)
+ + ]
1707 : : {
1708 [ + - - + ]: 20 : if (having_collation_conflict_walker((Node *) cw->expr, ctx) ||
1709 : 10 : having_collation_conflict_walker((Node *) cw->result, ctx))
22 rguo@postgresql.org 1710 :UBC 0 : return true;
1711 : : }
22 rguo@postgresql.org 1712 :CBC 10 : return having_collation_conflict_walker((Node *) cexpr->defresult,
1713 : : ctx);
1714 : : }
1715 : :
29 1716 : 2885 : this_collid = exprInputCollation(node);
1717 [ + + ]: 2885 : if (OidIsValid(this_collid))
1718 : 366 : ctx->ancestor_collids = lappend_oid(ctx->ancestor_collids,
1719 : : this_collid);
1720 : :
1721 : 2885 : result = expression_tree_walker(node, having_collation_conflict_walker,
1722 : : ctx);
1723 : :
1724 [ + + ]: 2885 : if (OidIsValid(this_collid))
1725 : 366 : ctx->ancestor_collids = list_delete_last(ctx->ancestor_collids);
1726 : :
1727 : 2885 : return result;
1728 : : }
1729 : :
1730 : : /*
1731 : : * preprocess_phv_expression
1732 : : * Do preprocessing on a PlaceHolderVar expression that's been pulled up.
1733 : : *
1734 : : * If a LATERAL subquery references an output of another subquery, and that
1735 : : * output must be wrapped in a PlaceHolderVar because of an intermediate outer
1736 : : * join, then we'll push the PlaceHolderVar expression down into the subquery
1737 : : * and later pull it back up during find_lateral_references, which runs after
1738 : : * subquery_planner has preprocessed all the expressions that were in the
1739 : : * current query level to start with. So we need to preprocess it then.
1740 : : */
1741 : : Expr *
5025 tgl@sss.pgh.pa.us 1742 : 75 : preprocess_phv_expression(PlannerInfo *root, Expr *expr)
1743 : : {
1744 : 75 : return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
1745 : : }
1746 : :
1747 : : /*--------------------
1748 : : * grouping_planner
1749 : : * Perform planning steps related to grouping, aggregation, etc.
1750 : : *
1751 : : * This function adds all required top-level processing to the scan/join
1752 : : * Path(s) produced by query_planner.
1753 : : *
1754 : : * tuple_fraction is the fraction of tuples we expect will be retrieved.
1755 : : * tuple_fraction is interpreted as follows:
1756 : : * 0: expect all tuples to be retrieved (normal case)
1757 : : * 0 < tuple_fraction < 1: expect the given fraction of tuples available
1758 : : * from the plan to be retrieved
1759 : : * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
1760 : : * expected to be retrieved (ie, a LIMIT specification).
1761 : : * setops is used for set operation subqueries to provide the subquery with
1762 : : * the context in which it's being used so that Paths correctly sorted for the
1763 : : * set operation can be generated. NULL when not planning a set operation
1764 : : * child, or when a child of a set op that isn't interested in sorted input.
1765 : : *
1766 : : * Returns nothing; the useful output is in the Paths we attach to the
1767 : : * (UPPERREL_FINAL, NULL) upperrel in *root. In addition,
1768 : : * root->processed_tlist contains the final processed targetlist.
1769 : : *
1770 : : * Note that we have not done set_cheapest() on the final rel; it's convenient
1771 : : * to leave this to the caller.
1772 : : *--------------------
1773 : : */
1774 : : static void
739 rhaas@postgresql.org 1775 : 397048 : grouping_planner(PlannerInfo *root, double tuple_fraction,
1776 : : SetOperationStmt *setops)
1777 : : {
7664 tgl@sss.pgh.pa.us 1778 : 397048 : Query *parse = root->parse;
7248 bruce@momjian.us 1779 : 397048 : int64 offset_est = 0;
1780 : 397048 : int64 count_est = 0;
6966 tgl@sss.pgh.pa.us 1781 : 397048 : double limit_tuples = -1.0;
3732 1782 : 397048 : bool have_postponed_srfs = false;
1783 : : PathTarget *final_target;
1784 : : List *final_targets;
1785 : : List *final_targets_contain_srfs;
1786 : : bool final_target_parallel_safe;
1787 : : RelOptInfo *current_rel;
1788 : : RelOptInfo *final_rel;
1789 : : FinalPathExtraData extra;
1790 : : ListCell *lc;
1791 : :
1792 : : /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
7590 1793 [ + + + + ]: 397048 : if (parse->limitCount || parse->limitOffset)
1794 : : {
1795 : 3705 : tuple_fraction = preprocess_limit(root, tuple_fraction,
1796 : : &offset_est, &count_est);
1797 : :
1798 : : /*
1799 : : * If we have a known LIMIT, and don't have an unknown OFFSET, we can
1800 : : * estimate the effects of using a bounded sort.
1801 : : */
6966 1802 [ + + + + ]: 3705 : if (count_est > 0 && offset_est >= 0)
1803 : 3243 : limit_tuples = (double) count_est + (double) offset_est;
1804 : : }
1805 : :
1806 : : /* Make tuple_fraction accessible to lower-level routines */
3736 1807 : 397048 : root->tuple_fraction = tuple_fraction;
1808 : :
9368 1809 [ + + ]: 397048 : if (parse->setOperations)
1810 : : {
1811 : : /*
1812 : : * Construct Paths for set operations. The results will not need any
1813 : : * work except perhaps a top-level sort and/or LIMIT. Note that any
1814 : : * special work for recursive unions is the responsibility of
1815 : : * plan_set_operations.
1816 : : */
3736 1817 : 4974 : current_rel = plan_set_operations(root);
1818 : :
1819 : : /*
1820 : : * We should not need to call preprocess_targetlist, since we must be
1821 : : * in a SELECT query node. Instead, use the processed_tlist returned
1822 : : * by plan_set_operations (since this tells whether it returned any
1823 : : * resjunk columns!), and transfer any sort key information from the
1824 : : * original tlist.
1825 : : */
9368 1826 [ - + ]: 4970 : Assert(parse->commandType == CMD_SELECT);
1827 : :
1828 : : /* for safety, copy processed_tlist instead of modifying in-place */
2621 1829 : 4970 : root->processed_tlist =
1830 : 4970 : postprocess_setop_tlist(copyObject(root->processed_tlist),
1831 : : parse->targetList);
1832 : :
1833 : : /* Also extract the PathTarget form of the setop result tlist */
3732 1834 : 4970 : final_target = current_rel->cheapest_total_path->pathtarget;
1835 : :
1836 : : /* And check whether it's parallel safe */
1837 : : final_target_parallel_safe =
3005 rhaas@postgresql.org 1838 : 4970 : is_parallel_safe(root, (Node *) final_target->exprs);
1839 : :
1840 : : /* The setop result tlist couldn't contain any SRFs */
3419 andres@anarazel.de 1841 [ - + ]: 4970 : Assert(!parse->hasTargetSRFs);
1842 : 4970 : final_targets = final_targets_contain_srfs = NIL;
1843 : :
1844 : : /*
1845 : : * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
1846 : : * checked already, but let's make sure).
1847 : : */
9306 tgl@sss.pgh.pa.us 1848 [ - + ]: 4970 : if (parse->rowMarks)
8345 tgl@sss.pgh.pa.us 1849 [ # # ]:UBC 0 : ereport(ERROR,
1850 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1851 : : /*------
1852 : : translator: %s is a SQL row locking clause such as FOR UPDATE */
1853 : : errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1854 : : LCS_asString(linitial_node(RowMarkClause,
1855 : : parse->rowMarks)->strength))));
1856 : :
1857 : : /*
1858 : : * Calculate pathkeys that represent result ordering requirements
1859 : : */
6512 tgl@sss.pgh.pa.us 1860 [ - + ]:CBC 4970 : Assert(parse->distinctClause == NIL);
6507 1861 : 4970 : root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
1862 : : parse->sortClause,
1863 : : root->processed_tlist);
1864 : : }
1865 : : else
1866 : : {
1867 : : /* No set operations, do regular planning */
1868 : : PathTarget *sort_input_target;
1869 : : List *sort_input_targets;
1870 : : List *sort_input_targets_contain_srfs;
1871 : : bool sort_input_target_parallel_safe;
1872 : : PathTarget *grouping_target;
1873 : : List *grouping_targets;
1874 : : List *grouping_targets_contain_srfs;
1875 : : bool grouping_target_parallel_safe;
1876 : : PathTarget *scanjoin_target;
1877 : : List *scanjoin_targets;
1878 : : List *scanjoin_targets_contain_srfs;
1879 : : bool scanjoin_target_parallel_safe;
1880 : : bool scanjoin_target_same_exprs;
1881 : : bool have_grouping;
6362 1882 : 392074 : WindowFuncLists *wflists = NULL;
1883 : 392074 : List *activeWindows = NIL;
3351 rhodiumtoad@postgres 1884 : 392074 : grouping_sets_data *gset_data = NULL;
1885 : : standard_qp_extra qp_extra;
1886 : :
1887 : : /* A recursive query should always have setOperations */
6447 tgl@sss.pgh.pa.us 1888 [ - + ]: 392074 : Assert(!root->hasRecursion);
1889 : :
1890 : : /* Preprocess grouping sets and GROUP BY clause, if any */
4032 andres@anarazel.de 1891 [ + + ]: 392074 : if (parse->groupingSets)
1892 : : {
3351 rhodiumtoad@postgres 1893 : 905 : gset_data = preprocess_grouping_sets(root);
1894 : : }
1228 tgl@sss.pgh.pa.us 1895 [ + + ]: 391169 : else if (parse->groupClause)
1896 : : {
1897 : : /* Preprocess regular GROUP BY clause, if any */
723 akorotkov@postgresql 1898 : 3482 : root->processed_groupClause = preprocess_groupclause(root, NIL);
1899 : : }
1900 : :
1901 : : /*
1902 : : * Preprocess targetlist. Note that much of the remaining planning
1903 : : * work will be done with the PathTarget representation of tlists, but
1904 : : * we must also maintain the full representation of the final tlist so
1905 : : * that we can transfer its decoration (resnames etc) to the topmost
1906 : : * tlist of the finished Plan. This is kept in processed_tlist.
1907 : : */
1886 tgl@sss.pgh.pa.us 1908 : 392070 : preprocess_targetlist(root);
1909 : :
1910 : : /*
1911 : : * Mark all the aggregates with resolved aggtranstypes, and detect
1912 : : * aggregates that are duplicates or can share transition state. We
1913 : : * must do this before slicing and dicing the tlist into various
1914 : : * pathtargets, else some copies of the Aggref nodes might escape
1915 : : * being marked.
1916 : : */
3619 1917 [ + + ]: 392070 : if (parse->hasAggs)
1918 : : {
2013 heikki.linnakangas@i 1919 : 33513 : preprocess_aggrefs(root, (Node *) root->processed_tlist);
1920 : 33513 : preprocess_aggrefs(root, (Node *) parse->havingQual);
1921 : : }
1922 : :
1923 : : /*
1924 : : * Locate any window functions in the tlist. (We don't need to look
1925 : : * anywhere else, since expressions used in ORDER BY will be in there
1926 : : * too.) Note that they could all have been eliminated by constant
1927 : : * folding, in which case we don't need to do any more work.
1928 : : */
6362 tgl@sss.pgh.pa.us 1929 [ + + ]: 392070 : if (parse->hasWindowFuncs)
1930 : : {
2621 1931 : 2237 : wflists = find_window_functions((Node *) root->processed_tlist,
6362 1932 : 2237 : list_length(parse->windowClause));
1933 [ + + ]: 2237 : if (wflists->numWindowFuncs > 0)
1934 : : {
1935 : : /*
1936 : : * See if any modifications can be made to each WindowClause
1937 : : * to allow the executor to execute the WindowFuncs more
1938 : : * quickly.
1939 : : */
1254 drowley@postgresql.o 1940 : 2232 : optimize_window_clauses(root, wflists);
1941 : :
1942 : : /* Extract the list of windows actually in use. */
6362 tgl@sss.pgh.pa.us 1943 : 2232 : activeWindows = select_active_windows(root, wflists);
1944 : :
1945 : : /* Make sure they all have names, for EXPLAIN's use. */
445 1946 : 2232 : name_active_windows(activeWindows);
1947 : : }
1948 : : else
6362 1949 : 5 : parse->hasWindowFuncs = false;
1950 : : }
1951 : :
1952 : : /*
1953 : : * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1954 : : * adding logic between here and the query_planner() call. Anything
1955 : : * that is needed in MIN/MAX-optimizable cases will have to be
1956 : : * duplicated in planagg.c.
1957 : : */
5686 1958 [ + + ]: 392070 : if (parse->hasAggs)
2621 1959 : 33513 : preprocess_minmax_aggregates(root);
1960 : :
1961 : : /*
1962 : : * Figure out whether there's a hard limit on the number of rows that
1963 : : * query_planner's result subplan needs to return. Even if we know a
1964 : : * hard limit overall, it doesn't apply if the query has any
1965 : : * grouping/aggregation operations, or SRFs in the tlist.
1966 : : */
5672 1967 [ + + ]: 392070 : if (parse->groupClause ||
4032 andres@anarazel.de 1968 [ + + ]: 387752 : parse->groupingSets ||
5672 tgl@sss.pgh.pa.us 1969 [ + + ]: 387687 : parse->distinctClause ||
1970 [ + + ]: 385747 : parse->hasAggs ||
1971 [ + + ]: 355934 : parse->hasWindowFuncs ||
3546 1972 [ + + ]: 353818 : parse->hasTargetSRFs ||
5672 1973 [ + + ]: 343748 : root->hasHavingQual)
4681 1974 : 48342 : root->limit_tuples = -1.0;
1975 : : else
1976 : 343728 : root->limit_tuples = limit_tuples;
1977 : :
1978 : : /* Set up data needed by standard_qp_callback */
4779 1979 : 392070 : qp_extra.activeWindows = activeWindows;
1228 1980 : 392070 : qp_extra.gset_data = gset_data;
1981 : :
1982 : : /*
1983 : : * If we're a subquery for a set operation, store the SetOperationStmt
1984 : : * in qp_extra.
1985 : : */
739 rhaas@postgresql.org 1986 : 392070 : qp_extra.setop = setops;
1987 : :
1988 : : /*
1989 : : * Generate the best unsorted and presorted paths for the scan/join
1990 : : * portion of this Query, ie the processing represented by the
1991 : : * FROM/WHERE clauses. (Note there may not be any presorted paths.)
1992 : : * We also generate (in standard_qp_callback) pathkey representations
1993 : : * of the query's sort clause, distinct clause, etc.
1994 : : */
2621 tgl@sss.pgh.pa.us 1995 : 392070 : current_rel = query_planner(root, standard_qp_callback, &qp_extra);
1996 : :
1997 : : /*
1998 : : * Convert the query's result tlist into PathTarget format.
1999 : : *
2000 : : * Note: this cannot be done before query_planner() has performed
2001 : : * appendrel expansion, because that might add resjunk entries to
2002 : : * root->processed_tlist. Waiting till afterwards is also helpful
2003 : : * because the target width estimates can use per-Var width numbers
2004 : : * that were obtained within query_planner().
2005 : : */
2006 : 392035 : final_target = create_pathtarget(root, root->processed_tlist);
2007 : : final_target_parallel_safe =
3005 rhaas@postgresql.org 2008 : 392035 : is_parallel_safe(root, (Node *) final_target->exprs);
2009 : :
2010 : : /*
2011 : : * If ORDER BY was given, consider whether we should use a post-sort
2012 : : * projection, and compute the adjusted target for preceding steps if
2013 : : * so.
2014 : : */
3732 tgl@sss.pgh.pa.us 2015 [ + + ]: 392035 : if (parse->sortClause)
2016 : : {
2017 : 58931 : sort_input_target = make_sort_input_target(root,
2018 : : final_target,
2019 : : &have_postponed_srfs);
2020 : : sort_input_target_parallel_safe =
3005 rhaas@postgresql.org 2021 : 58931 : is_parallel_safe(root, (Node *) sort_input_target->exprs);
2022 : : }
2023 : : else
2024 : : {
3732 tgl@sss.pgh.pa.us 2025 : 333104 : sort_input_target = final_target;
3005 rhaas@postgresql.org 2026 : 333104 : sort_input_target_parallel_safe = final_target_parallel_safe;
2027 : : }
2028 : :
2029 : : /*
2030 : : * If we have window functions to deal with, the output from any
2031 : : * grouping step needs to be what the window functions want;
2032 : : * otherwise, it should be sort_input_target.
2033 : : */
3734 tgl@sss.pgh.pa.us 2034 [ + + ]: 392035 : if (activeWindows)
2035 : : {
2036 : 2232 : grouping_target = make_window_input_target(root,
2037 : : final_target,
2038 : : activeWindows);
2039 : : grouping_target_parallel_safe =
3005 rhaas@postgresql.org 2040 : 2232 : is_parallel_safe(root, (Node *) grouping_target->exprs);
2041 : : }
2042 : : else
2043 : : {
3732 tgl@sss.pgh.pa.us 2044 : 389803 : grouping_target = sort_input_target;
3005 rhaas@postgresql.org 2045 : 389803 : grouping_target_parallel_safe = sort_input_target_parallel_safe;
2046 : : }
2047 : :
2048 : : /*
2049 : : * If we have grouping or aggregation to do, the topmost scan/join
2050 : : * plan node must emit what the grouping step wants; otherwise, it
2051 : : * should emit grouping_target.
2052 : : */
3734 tgl@sss.pgh.pa.us 2053 [ + + ]: 387717 : have_grouping = (parse->groupClause || parse->groupingSets ||
2054 [ + + + + : 779752 : parse->hasAggs || root->hasHavingQual);
+ + ]
2055 [ + + ]: 392035 : if (have_grouping)
2056 : : {
3732 2057 : 34247 : scanjoin_target = make_group_input_target(root, final_target);
2058 : : scanjoin_target_parallel_safe =
2636 efujita@postgresql.o 2059 : 34247 : is_parallel_safe(root, (Node *) scanjoin_target->exprs);
2060 : : }
2061 : : else
2062 : : {
3734 tgl@sss.pgh.pa.us 2063 : 357788 : scanjoin_target = grouping_target;
3005 rhaas@postgresql.org 2064 : 357788 : scanjoin_target_parallel_safe = grouping_target_parallel_safe;
2065 : : }
2066 : :
2067 : : /*
2068 : : * If there are any SRFs in the targetlist, we must separate each of
2069 : : * these PathTargets into SRF-computing and SRF-free targets. Replace
2070 : : * each of the named targets with a SRF-free version, and remember the
2071 : : * list of additional projection steps we need to add afterwards.
2072 : : */
3419 andres@anarazel.de 2073 [ + + ]: 392035 : if (parse->hasTargetSRFs)
2074 : : {
2075 : : /* final_target doesn't recompute any SRFs in sort_input_target */
2076 : 10404 : split_pathtarget_at_srfs(root, final_target, sort_input_target,
2077 : : &final_targets,
2078 : : &final_targets_contain_srfs);
3189 tgl@sss.pgh.pa.us 2079 : 10404 : final_target = linitial_node(PathTarget, final_targets);
3419 andres@anarazel.de 2080 [ - + ]: 10404 : Assert(!linitial_int(final_targets_contain_srfs));
2081 : : /* likewise for sort_input_target vs. grouping_target */
2082 : 10404 : split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
2083 : : &sort_input_targets,
2084 : : &sort_input_targets_contain_srfs);
3189 tgl@sss.pgh.pa.us 2085 : 10404 : sort_input_target = linitial_node(PathTarget, sort_input_targets);
3419 andres@anarazel.de 2086 [ - + ]: 10404 : Assert(!linitial_int(sort_input_targets_contain_srfs));
2087 : : /* likewise for grouping_target vs. scanjoin_target */
156 rguo@postgresql.org 2088 : 10404 : split_pathtarget_at_srfs_grouping(root,
2089 : : grouping_target, scanjoin_target,
2090 : : &grouping_targets,
2091 : : &grouping_targets_contain_srfs);
3189 tgl@sss.pgh.pa.us 2092 : 10404 : grouping_target = linitial_node(PathTarget, grouping_targets);
3419 andres@anarazel.de 2093 [ - + ]: 10404 : Assert(!linitial_int(grouping_targets_contain_srfs));
2094 : : /* scanjoin_target will not have any SRFs precomputed for it */
2095 : 10404 : split_pathtarget_at_srfs(root, scanjoin_target, NULL,
2096 : : &scanjoin_targets,
2097 : : &scanjoin_targets_contain_srfs);
3189 tgl@sss.pgh.pa.us 2098 : 10404 : scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
3419 andres@anarazel.de 2099 [ - + ]: 10404 : Assert(!linitial_int(scanjoin_targets_contain_srfs));
2100 : : }
2101 : : else
2102 : : {
2103 : : /* initialize lists; for most of these, dummy values are OK */
2104 : 381631 : final_targets = final_targets_contain_srfs = NIL;
2105 : 381631 : sort_input_targets = sort_input_targets_contain_srfs = NIL;
2106 : 381631 : grouping_targets = grouping_targets_contain_srfs = NIL;
2984 rhaas@postgresql.org 2107 : 381631 : scanjoin_targets = list_make1(scanjoin_target);
2108 : 381631 : scanjoin_targets_contain_srfs = NIL;
2109 : : }
2110 : :
2111 : : /* Apply scan/join target. */
2112 : 392035 : scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
2113 [ + + + + ]: 392035 : && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
2114 : 392035 : apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
2115 : : scanjoin_targets_contain_srfs,
2116 : : scanjoin_target_parallel_safe,
2117 : : scanjoin_target_same_exprs);
2118 : :
2119 : : /*
2120 : : * Save the various upper-rel PathTargets we just computed into
2121 : : * root->upper_targets[]. The core code doesn't use this, but it
2122 : : * provides a convenient place for extensions to get at the info. For
2123 : : * consistency, we save all the intermediate targets, even though some
2124 : : * of the corresponding upperrels might not be needed for this query.
2125 : : */
3729 tgl@sss.pgh.pa.us 2126 : 392035 : root->upper_targets[UPPERREL_FINAL] = final_target;
2658 efujita@postgresql.o 2127 : 392035 : root->upper_targets[UPPERREL_ORDERED] = final_target;
2128 : 392035 : root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
843 drowley@postgresql.o 2129 : 392035 : root->upper_targets[UPPERREL_PARTIAL_DISTINCT] = sort_input_target;
3729 tgl@sss.pgh.pa.us 2130 : 392035 : root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
2131 : 392035 : root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
2132 : :
2133 : : /*
2134 : : * If we have grouping and/or aggregation, consider ways to implement
2135 : : * that. We build a new upperrel representing the output of this
2136 : : * phase.
2137 : : */
3734 2138 [ + + ]: 392035 : if (have_grouping)
2139 : : {
3736 2140 : 34247 : current_rel = create_grouping_paths(root,
2141 : : current_rel,
2142 : : grouping_target,
2143 : : grouping_target_parallel_safe,
2144 : : gset_data);
2145 : : /* Fix things up if grouping_target contains SRFs */
3419 andres@anarazel.de 2146 [ + + ]: 34243 : if (parse->hasTargetSRFs)
2147 : 299 : adjust_paths_for_srfs(root, current_rel,
2148 : : grouping_targets,
2149 : : grouping_targets_contain_srfs);
2150 : : }
2151 : :
2152 : : /*
2153 : : * If we have window functions, consider ways to implement those. We
2154 : : * build a new upperrel representing the output of this phase.
2155 : : */
3736 tgl@sss.pgh.pa.us 2156 [ + + ]: 392031 : if (activeWindows)
2157 : : {
2158 : 2232 : current_rel = create_window_paths(root,
2159 : : current_rel,
2160 : : grouping_target,
2161 : : sort_input_target,
2162 : : sort_input_target_parallel_safe,
2163 : : wflists,
2164 : : activeWindows);
2165 : : /* Fix things up if sort_input_target contains SRFs */
3419 andres@anarazel.de 2166 [ + + ]: 2232 : if (parse->hasTargetSRFs)
2167 : 10 : adjust_paths_for_srfs(root, current_rel,
2168 : : sort_input_targets,
2169 : : sort_input_targets_contain_srfs);
2170 : : }
2171 : :
2172 : : /*
2173 : : * If there is a DISTINCT clause, consider ways to implement that. We
2174 : : * build a new upperrel representing the output of this phase.
2175 : : */
3736 tgl@sss.pgh.pa.us 2176 [ + + ]: 392031 : if (parse->distinctClause)
2177 : : {
2178 : 1967 : current_rel = create_distinct_paths(root,
2179 : : current_rel,
2180 : : sort_input_target);
2181 : : }
2182 : : } /* end of if (setOperations) */
2183 : :
2184 : : /*
2185 : : * If ORDER BY was given, consider ways to implement that, and generate a
2186 : : * new upperrel containing only paths that emit the correct ordering and
2187 : : * project the correct final_target. We can apply the original
2188 : : * limit_tuples limit in sort costing here, but only if there are no
2189 : : * postponed SRFs.
2190 : : */
2191 [ + + ]: 397001 : if (parse->sortClause)
2192 : : {
2193 [ + + ]: 62200 : current_rel = create_ordered_paths(root,
2194 : : current_rel,
2195 : : final_target,
2196 : : final_target_parallel_safe,
2197 : : have_postponed_srfs ? -1.0 :
2198 : : limit_tuples);
2199 : : /* Fix things up if final_target contains SRFs */
3419 andres@anarazel.de 2200 [ + + ]: 62200 : if (parse->hasTargetSRFs)
2201 : 182 : adjust_paths_for_srfs(root, current_rel,
2202 : : final_targets,
2203 : : final_targets_contain_srfs);
2204 : : }
2205 : :
2206 : : /*
2207 : : * Now we are prepared to build the final-output upperrel.
2208 : : */
3736 tgl@sss.pgh.pa.us 2209 : 397001 : final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
2210 : :
2211 : : /*
2212 : : * If the input rel is marked consider_parallel and there's nothing that's
2213 : : * not parallel-safe in the LIMIT clause, then the final_rel can be marked
2214 : : * consider_parallel as well. Note that if the query has rowMarks or is
2215 : : * not a SELECT, consider_parallel will be false for every relation in the
2216 : : * query.
2217 : : */
3620 rhaas@postgresql.org 2218 [ + + + + ]: 537756 : if (current_rel->consider_parallel &&
3571 tgl@sss.pgh.pa.us 2219 [ + + ]: 281490 : is_parallel_safe(root, parse->limitOffset) &&
2220 : 140735 : is_parallel_safe(root, parse->limitCount))
3620 rhaas@postgresql.org 2221 : 140730 : final_rel->consider_parallel = true;
2222 : :
2223 : : /*
2224 : : * If the current_rel belongs to a single FDW, so does the final_rel.
2225 : : */
tgl@sss.pgh.pa.us 2226 : 397001 : final_rel->serverid = current_rel->serverid;
3606 2227 : 397001 : final_rel->userid = current_rel->userid;
2228 : 397001 : final_rel->useridiscurrent = current_rel->useridiscurrent;
3620 2229 : 397001 : final_rel->fdwroutine = current_rel->fdwroutine;
2230 : :
2231 : : /*
2232 : : * Generate paths for the final_rel. Insert all surviving paths, with
2233 : : * LockRows, Limit, and/or ModifyTable steps added if needed.
2234 : : */
3736 2235 [ + - + + : 810284 : foreach(lc, current_rel->pathlist)
+ + ]
2236 : : {
2237 : 413283 : Path *path = (Path *) lfirst(lc);
2238 : :
2239 : : /*
2240 : : * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
2241 : : * (Note: we intentionally test parse->rowMarks not root->rowMarks
2242 : : * here. If there are only non-locking rowmarks, they should be
2243 : : * handled by the ModifyTable node instead. However, root->rowMarks
2244 : : * is what goes into the LockRows node.)
2245 : : */
2246 [ + + ]: 413283 : if (parse->rowMarks)
2247 : : {
2248 : 6820 : path = (Path *) create_lockrows_path(root, final_rel, path,
2249 : : root->rowMarks,
2250 : : assign_special_exec_param(root));
2251 : : }
2252 : :
2253 : : /*
2254 : : * If there is a LIMIT/OFFSET clause, add the LIMIT node.
2255 : : */
2256 [ + + ]: 413283 : if (limit_needed(parse))
2257 : : {
2258 : 4167 : path = (Path *) create_limit_path(root, final_rel, path,
2259 : : parse->limitOffset,
2260 : : parse->limitCount,
2261 : : parse->limitOption,
2262 : : offset_est, count_est);
2263 : : }
2264 : :
2265 : : /*
2266 : : * If this is an INSERT/UPDATE/DELETE/MERGE, add the ModifyTable node.
2267 : : */
1886 2268 [ + + ]: 413283 : if (parse->commandType != CMD_SELECT)
2269 : : {
2270 : : Index rootRelation;
2271 : 60717 : List *resultRelations = NIL;
2272 : 60717 : List *updateColnosLists = NIL;
2273 : 60717 : List *withCheckOptionLists = NIL;
2274 : 60717 : List *returningLists = NIL;
1524 alvherre@alvh.no-ip. 2275 : 60717 : List *mergeActionLists = NIL;
791 dean.a.rasheed@gmail 2276 : 60717 : List *mergeJoinConditions = NIL;
2277 : : List *rowMarks;
2278 : :
1886 tgl@sss.pgh.pa.us 2279 [ + + ]: 60717 : if (bms_membership(root->all_result_relids) == BMS_MULTIPLE)
2280 : : {
2281 : : /* Inherited UPDATE/DELETE/MERGE */
2282 : 2288 : RelOptInfo *top_result_rel = find_base_rel(root,
2283 : : parse->resultRelation);
2284 : 2288 : int resultRelation = -1;
2285 : :
2286 : : /* Pass the root result rel forward to the executor. */
949 2287 : 2288 : rootRelation = parse->resultRelation;
2288 : :
2289 : : /* Add only leaf children to ModifyTable. */
1886 2290 : 6718 : while ((resultRelation = bms_next_member(root->leaf_result_relids,
2291 [ + + ]: 6718 : resultRelation)) >= 0)
2292 : : {
2293 : 4430 : RelOptInfo *this_result_rel = find_base_rel(root,
2294 : : resultRelation);
2295 : :
2296 : : /*
2297 : : * Also exclude any leaf rels that have turned dummy since
2298 : : * being added to the list, for example, by being excluded
2299 : : * by constraint exclusion.
2300 : : */
2301 [ + + ]: 4430 : if (IS_DUMMY_REL(this_result_rel))
2302 : 153 : continue;
2303 : :
2304 : : /* Build per-target-rel lists needed by ModifyTable */
2305 : 4277 : resultRelations = lappend_int(resultRelations,
2306 : : resultRelation);
2307 [ + + ]: 4277 : if (parse->commandType == CMD_UPDATE)
2308 : : {
2309 : 2933 : List *update_colnos = root->update_colnos;
2310 : :
2311 [ + - ]: 2933 : if (this_result_rel != top_result_rel)
2312 : : update_colnos =
2313 : 2933 : adjust_inherited_attnums_multilevel(root,
2314 : : update_colnos,
2315 : : this_result_rel->relid,
2316 : : top_result_rel->relid);
2317 : 2933 : updateColnosLists = lappend(updateColnosLists,
2318 : : update_colnos);
2319 : : }
2320 [ + + ]: 4277 : if (parse->withCheckOptions)
2321 : : {
2322 : 416 : List *withCheckOptions = parse->withCheckOptions;
2323 : :
2324 [ + - ]: 416 : if (this_result_rel != top_result_rel)
2325 : : withCheckOptions = (List *)
2326 : 416 : adjust_appendrel_attrs_multilevel(root,
2327 : : (Node *) withCheckOptions,
2328 : : this_result_rel,
2329 : : top_result_rel);
2330 : 416 : withCheckOptionLists = lappend(withCheckOptionLists,
2331 : : withCheckOptions);
2332 : : }
2333 [ + + ]: 4277 : if (parse->returningList)
2334 : : {
2335 : 645 : List *returningList = parse->returningList;
2336 : :
2337 [ + - ]: 645 : if (this_result_rel != top_result_rel)
2338 : : returningList = (List *)
2339 : 645 : adjust_appendrel_attrs_multilevel(root,
2340 : : (Node *) returningList,
2341 : : this_result_rel,
2342 : : top_result_rel);
2343 : 645 : returningLists = lappend(returningLists,
2344 : : returningList);
2345 : : }
1524 alvherre@alvh.no-ip. 2346 [ + + ]: 4277 : if (parse->mergeActionList)
2347 : : {
2348 : : ListCell *l;
2349 : 425 : List *mergeActionList = NIL;
2350 : :
2351 : : /*
2352 : : * Copy MergeActions and translate stuff that
2353 : : * references attribute numbers.
2354 : : */
2355 [ + - + + : 1322 : foreach(l, parse->mergeActionList)
+ + ]
2356 : : {
2357 : 897 : MergeAction *action = lfirst(l),
2358 : 897 : *leaf_action = copyObject(action);
2359 : :
2360 : 897 : leaf_action->qual =
2361 : 897 : adjust_appendrel_attrs_multilevel(root,
2362 : : (Node *) action->qual,
2363 : : this_result_rel,
2364 : : top_result_rel);
2365 : 897 : leaf_action->targetList = (List *)
2366 : 897 : adjust_appendrel_attrs_multilevel(root,
2367 : 897 : (Node *) action->targetList,
2368 : : this_result_rel,
2369 : : top_result_rel);
2370 [ + + ]: 897 : if (leaf_action->commandType == CMD_UPDATE)
2371 : 491 : leaf_action->updateColnos =
2372 : 491 : adjust_inherited_attnums_multilevel(root,
2373 : : action->updateColnos,
2374 : : this_result_rel->relid,
2375 : : top_result_rel->relid);
2376 : 897 : mergeActionList = lappend(mergeActionList,
2377 : : leaf_action);
2378 : : }
2379 : :
2380 : 425 : mergeActionLists = lappend(mergeActionLists,
2381 : : mergeActionList);
2382 : : }
791 dean.a.rasheed@gmail 2383 [ + + ]: 4277 : if (parse->commandType == CMD_MERGE)
2384 : : {
2385 : 425 : Node *mergeJoinCondition = parse->mergeJoinCondition;
2386 : :
2387 [ + - ]: 425 : if (this_result_rel != top_result_rel)
2388 : : mergeJoinCondition =
2389 : 425 : adjust_appendrel_attrs_multilevel(root,
2390 : : mergeJoinCondition,
2391 : : this_result_rel,
2392 : : top_result_rel);
2393 : 425 : mergeJoinConditions = lappend(mergeJoinConditions,
2394 : : mergeJoinCondition);
2395 : : }
2396 : : }
2397 : :
1886 tgl@sss.pgh.pa.us 2398 [ + + ]: 2288 : if (resultRelations == NIL)
2399 : : {
2400 : : /*
2401 : : * We managed to exclude every child rel, so generate a
2402 : : * dummy one-relation plan using info for the top target
2403 : : * rel (even though that may not be a leaf target).
2404 : : * Although it's clear that no data will be updated or
2405 : : * deleted, we still need to have a ModifyTable node so
2406 : : * that any statement triggers will be executed. (This
2407 : : * could be cleaner if we fixed nodeModifyTable.c to allow
2408 : : * zero target relations, but that probably wouldn't be a
2409 : : * net win.)
2410 : : */
2411 : 28 : resultRelations = list_make1_int(parse->resultRelation);
2412 [ + + ]: 28 : if (parse->commandType == CMD_UPDATE)
2413 : 26 : updateColnosLists = list_make1(root->update_colnos);
2414 [ - + ]: 28 : if (parse->withCheckOptions)
1886 tgl@sss.pgh.pa.us 2415 :UBC 0 : withCheckOptionLists = list_make1(parse->withCheckOptions);
1886 tgl@sss.pgh.pa.us 2416 [ + + ]:CBC 28 : if (parse->returningList)
2417 : 15 : returningLists = list_make1(parse->returningList);
1524 alvherre@alvh.no-ip. 2418 [ + + ]: 28 : if (parse->mergeActionList)
2419 : 1 : mergeActionLists = list_make1(parse->mergeActionList);
791 dean.a.rasheed@gmail 2420 [ + + ]: 28 : if (parse->commandType == CMD_MERGE)
2421 : 1 : mergeJoinConditions = list_make1(parse->mergeJoinCondition);
2422 : : }
2423 : : }
2424 : : else
2425 : : {
2426 : : /* Single-relation INSERT/UPDATE/DELETE/MERGE. */
949 tgl@sss.pgh.pa.us 2427 : 58429 : rootRelation = 0; /* there's no separate root rel */
1886 2428 : 58429 : resultRelations = list_make1_int(parse->resultRelation);
2429 [ + + ]: 58429 : if (parse->commandType == CMD_UPDATE)
2430 : 8810 : updateColnosLists = list_make1(root->update_colnos);
2431 [ + + ]: 58429 : if (parse->withCheckOptions)
2432 : 889 : withCheckOptionLists = list_make1(parse->withCheckOptions);
2433 [ + + ]: 58429 : if (parse->returningList)
2434 : 2202 : returningLists = list_make1(parse->returningList);
1524 alvherre@alvh.no-ip. 2435 [ + + ]: 58429 : if (parse->mergeActionList)
2436 : 1287 : mergeActionLists = list_make1(parse->mergeActionList);
791 dean.a.rasheed@gmail 2437 [ + + ]: 58429 : if (parse->commandType == CMD_MERGE)
2438 : 1287 : mergeJoinConditions = list_make1(parse->mergeJoinCondition);
2439 : : }
2440 : :
2441 : : /*
2442 : : * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
2443 : : * will have dealt with fetching non-locked marked rows, else we
2444 : : * need to have ModifyTable do that.
2445 : : */
3736 tgl@sss.pgh.pa.us 2446 [ - + ]: 60717 : if (parse->rowMarks)
3736 tgl@sss.pgh.pa.us 2447 :UBC 0 : rowMarks = NIL;
2448 : : else
3736 tgl@sss.pgh.pa.us 2449 :CBC 60717 : rowMarks = root->rowMarks;
2450 : :
2451 : : path = (Path *)
2452 : 60717 : create_modifytable_path(root, final_rel,
2453 : : path,
2454 : : parse->commandType,
2455 : 60717 : parse->canSetTag,
2456 : 60717 : parse->resultRelation,
2457 : : rootRelation,
2458 : : resultRelations,
2459 : : updateColnosLists,
2460 : : withCheckOptionLists,
2461 : : returningLists,
2462 : : rowMarks,
2463 : : parse->onConflict,
2464 : : mergeActionLists,
2465 : : mergeJoinConditions,
2466 : : parse->forPortionOf,
2467 : : assign_special_exec_param(root));
2468 : : }
2469 : :
2470 : : /* And shove it into final_rel */
2471 : 413283 : add_path(final_rel, path);
2472 : : }
2473 : :
2474 : : /*
2475 : : * Generate partial paths for final_rel, too, if outer query levels might
2476 : : * be able to make use of them.
2477 : : */
3000 rhaas@postgresql.org 2478 [ + + + + ]: 397001 : if (final_rel->consider_parallel && root->query_level > 1 &&
2479 [ + + ]: 24965 : !limit_needed(parse))
2480 : : {
2481 [ + - - + ]: 24788 : Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
2482 [ + + + + : 24900 : foreach(lc, current_rel->partial_pathlist)
+ + ]
2483 : : {
2484 : 112 : Path *partial_path = (Path *) lfirst(lc);
2485 : :
2486 : 112 : add_partial_path(final_rel, partial_path);
2487 : : }
2488 : : }
2489 : :
2615 efujita@postgresql.o 2490 : 397001 : extra.limit_needed = limit_needed(parse);
2491 : 397001 : extra.limit_tuples = limit_tuples;
2492 : 397001 : extra.count_est = count_est;
2493 : 397001 : extra.offset_est = offset_est;
2494 : :
2495 : : /*
2496 : : * If there is an FDW that's responsible for all baserels of the query,
2497 : : * let it consider adding ForeignPaths.
2498 : : */
3620 tgl@sss.pgh.pa.us 2499 [ + + ]: 397001 : if (final_rel->fdwroutine &&
2500 [ + + ]: 662 : final_rel->fdwroutine->GetForeignUpperPaths)
2501 : 625 : final_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_FINAL,
2502 : : current_rel, final_rel,
2503 : : &extra);
2504 : :
2505 : : /* Let extensions possibly add some more paths */
3700 2506 [ - + ]: 397001 : if (create_upper_paths_hook)
3700 tgl@sss.pgh.pa.us 2507 :UBC 0 : (*create_upper_paths_hook) (root, UPPERREL_FINAL,
2508 : : current_rel, final_rel, &extra);
2509 : :
2510 : : /* Note: currently, we leave it to callers to do set_cheapest() */
3736 tgl@sss.pgh.pa.us 2511 :CBC 397001 : }
2512 : :
2513 : : /*
2514 : : * Do preprocessing for groupingSets clause and related data.
2515 : : *
2516 : : * We expect that parse->groupingSets has already been expanded into a flat
2517 : : * list of grouping sets (that is, just integer Lists of ressortgroupref
2518 : : * numbers) by expand_grouping_sets(). This function handles the preliminary
2519 : : * steps of organizing the grouping sets into lists of rollups, and preparing
2520 : : * annotations which will later be filled in with size estimates.
2521 : : */
2522 : : static grouping_sets_data *
3351 rhodiumtoad@postgres 2523 : 905 : preprocess_grouping_sets(PlannerInfo *root)
2524 : : {
2525 : 905 : Query *parse = root->parse;
2526 : : List *sets;
2527 : 905 : int maxref = 0;
2528 : : ListCell *lc_set;
171 michael@paquier.xyz 2529 :GNC 905 : grouping_sets_data *gd = palloc0_object(grouping_sets_data);
2530 : :
2531 : : /*
2532 : : * We don't currently make any attempt to optimize the groupClause when
2533 : : * there are grouping sets, so just duplicate it in processed_groupClause.
2534 : : */
1228 tgl@sss.pgh.pa.us 2535 :CBC 905 : root->processed_groupClause = parse->groupClause;
2536 : :
2537 : : /* Detect unhashable and unsortable grouping expressions */
221 rguo@postgresql.org 2538 : 905 : gd->any_hashable = false;
2539 : 905 : gd->unhashable_refs = NULL;
2540 : 905 : gd->unsortable_refs = NULL;
2541 : 905 : gd->unsortable_sets = NIL;
2542 : :
3351 rhodiumtoad@postgres 2543 [ + + ]: 905 : if (parse->groupClause)
2544 : : {
2545 : : ListCell *lc;
2546 : :
2547 [ + - + + : 2651 : foreach(lc, parse->groupClause)
+ + ]
2548 : : {
3189 tgl@sss.pgh.pa.us 2549 : 1811 : SortGroupClause *gc = lfirst_node(SortGroupClause, lc);
3351 rhodiumtoad@postgres 2550 : 1811 : Index ref = gc->tleSortGroupRef;
2551 : :
2552 [ + + ]: 1811 : if (ref > maxref)
2553 : 1771 : maxref = ref;
2554 : :
2555 [ + + ]: 1811 : if (!gc->hashable)
2556 : 24 : gd->unhashable_refs = bms_add_member(gd->unhashable_refs, ref);
2557 : :
2558 [ + + ]: 1811 : if (!OidIsValid(gc->sortop))
2559 : 33 : gd->unsortable_refs = bms_add_member(gd->unsortable_refs, ref);
2560 : : }
2561 : : }
2562 : :
2563 : : /* Allocate workspace array for remapping */
2564 : 905 : gd->tleref_to_colnum_map = (int *) palloc((maxref + 1) * sizeof(int));
2565 : :
2566 : : /*
2567 : : * If we have any unsortable sets, we must extract them before trying to
2568 : : * prepare rollups. Unsortable sets don't go through
2569 : : * reorder_grouping_sets, so we must apply the GroupingSetData annotation
2570 : : * here.
2571 : : */
2572 [ + + ]: 905 : if (!bms_is_empty(gd->unsortable_refs))
2573 : : {
2574 : 33 : List *sortable_sets = NIL;
2575 : : ListCell *lc;
2576 : :
2577 [ + - + + : 99 : foreach(lc, parse->groupingSets)
+ + ]
2578 : : {
3189 tgl@sss.pgh.pa.us 2579 : 70 : List *gset = (List *) lfirst(lc);
2580 : :
3351 rhodiumtoad@postgres 2581 [ + + ]: 70 : if (bms_overlap_list(gd->unsortable_refs, gset))
2582 : : {
2583 : 38 : GroupingSetData *gs = makeNode(GroupingSetData);
2584 : :
2585 : 38 : gs->set = gset;
2586 : 38 : gd->unsortable_sets = lappend(gd->unsortable_sets, gs);
2587 : :
2588 : : /*
2589 : : * We must enforce here that an unsortable set is hashable;
2590 : : * later code assumes this. Parse analysis only checks that
2591 : : * every individual column is either hashable or sortable.
2592 : : *
2593 : : * Note that passing this test doesn't guarantee we can
2594 : : * generate a plan; there might be other showstoppers.
2595 : : */
2596 [ + + ]: 38 : if (bms_overlap_list(gd->unhashable_refs, gset))
2597 [ + - ]: 4 : ereport(ERROR,
2598 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2599 : : errmsg("could not implement GROUP BY"),
2600 : : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2601 : : }
2602 : : else
2603 : 32 : sortable_sets = lappend(sortable_sets, gset);
2604 : : }
2605 : :
2606 [ + + ]: 29 : if (sortable_sets)
2607 : 24 : sets = extract_rollup_sets(sortable_sets);
2608 : : else
2609 : 5 : sets = NIL;
2610 : : }
2611 : : else
2612 : 872 : sets = extract_rollup_sets(parse->groupingSets);
2613 : :
2614 [ + + + + : 2376 : foreach(lc_set, sets)
+ + ]
2615 : : {
2616 : 1475 : List *current_sets = (List *) lfirst(lc_set);
2617 : 1475 : RollupData *rollup = makeNode(RollupData);
2618 : : GroupingSetData *gs;
2619 : :
2620 : : /*
2621 : : * Reorder the current list of grouping sets into correct prefix
2622 : : * order. If only one aggregation pass is needed, try to make the
2623 : : * list match the ORDER BY clause; if more than one pass is needed, we
2624 : : * don't bother with that.
2625 : : *
2626 : : * Note that this reorders the sets from smallest-member-first to
2627 : : * largest-member-first, and applies the GroupingSetData annotations,
2628 : : * though the data will be filled in later.
2629 : : */
2630 [ + + ]: 1475 : current_sets = reorder_grouping_sets(current_sets,
2631 : 1475 : (list_length(sets) == 1
2632 : : ? parse->sortClause
2633 : : : NIL));
2634 : :
2635 : : /*
2636 : : * Get the initial (and therefore largest) grouping set.
2637 : : */
3189 tgl@sss.pgh.pa.us 2638 : 1475 : gs = linitial_node(GroupingSetData, current_sets);
2639 : :
2640 : : /*
2641 : : * Order the groupClause appropriately. If the first grouping set is
2642 : : * empty, then the groupClause must also be empty; otherwise we have
2643 : : * to force the groupClause to match that grouping set's order.
2644 : : *
2645 : : * (The first grouping set can be empty even though parse->groupClause
2646 : : * is not empty only if all non-empty grouping sets are unsortable.
2647 : : * The groupClauses for hashed grouping sets are built later on.)
2648 : : */
3351 rhodiumtoad@postgres 2649 [ + + ]: 1475 : if (gs->set)
723 akorotkov@postgresql 2650 : 1410 : rollup->groupClause = preprocess_groupclause(root, gs->set);
2651 : : else
3351 rhodiumtoad@postgres 2652 : 65 : rollup->groupClause = NIL;
2653 : :
2654 : : /*
2655 : : * Is it hashable? We pretend empty sets are hashable even though we
2656 : : * actually force them not to be hashed later. But don't bother if
2657 : : * there's nothing but empty sets (since in that case we can't hash
2658 : : * anything).
2659 : : */
2660 [ + + ]: 1475 : if (gs->set &&
2661 [ + + ]: 1410 : !bms_overlap_list(gd->unhashable_refs, gs->set))
2662 : : {
2663 : 1390 : rollup->hashable = true;
2664 : 1390 : gd->any_hashable = true;
2665 : : }
2666 : :
2667 : : /*
2668 : : * Now that we've pinned down an order for the groupClause for this
2669 : : * list of grouping sets, we need to remap the entries in the grouping
2670 : : * sets from sortgrouprefs to plain indices (0-based) into the
2671 : : * groupClause for this collection of grouping sets. We keep the
2672 : : * original form for later use, though.
2673 : : */
2674 : 1475 : rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
2675 : : current_sets,
2676 : : gd->tleref_to_colnum_map);
2677 : 1475 : rollup->gsets_data = current_sets;
2678 : :
2679 : 1475 : gd->rollups = lappend(gd->rollups, rollup);
2680 : : }
2681 : :
2682 [ + + ]: 901 : if (gd->unsortable_sets)
2683 : : {
2684 : : /*
2685 : : * We have not yet pinned down a groupclause for this, but we will
2686 : : * need index-based lists for estimation purposes. Construct
2687 : : * hash_sets_idx based on the entire original groupclause for now.
2688 : : */
2689 : 29 : gd->hash_sets_idx = remap_to_groupclause_idx(parse->groupClause,
2690 : : gd->unsortable_sets,
2691 : : gd->tleref_to_colnum_map);
2692 : 29 : gd->any_hashable = true;
2693 : : }
2694 : :
2695 : 901 : return gd;
2696 : : }
2697 : :
2698 : : /*
2699 : : * Given a groupclause and a list of GroupingSetData, return equivalent sets
2700 : : * (without annotation) mapped to indexes into the given groupclause.
2701 : : */
2702 : : static List *
2703 : 4147 : remap_to_groupclause_idx(List *groupClause,
2704 : : List *gsets,
2705 : : int *tleref_to_colnum_map)
2706 : : {
2707 : 4147 : int ref = 0;
2708 : 4147 : List *result = NIL;
2709 : : ListCell *lc;
2710 : :
2711 [ + + + + : 9861 : foreach(lc, groupClause)
+ + ]
2712 : : {
3189 tgl@sss.pgh.pa.us 2713 : 5714 : SortGroupClause *gc = lfirst_node(SortGroupClause, lc);
2714 : :
3351 rhodiumtoad@postgres 2715 : 5714 : tleref_to_colnum_map[gc->tleSortGroupRef] = ref++;
2716 : : }
2717 : :
2718 [ + - + + : 9444 : foreach(lc, gsets)
+ + ]
2719 : : {
2720 : 5297 : List *set = NIL;
2721 : : ListCell *lc2;
3189 tgl@sss.pgh.pa.us 2722 : 5297 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
2723 : :
3351 rhodiumtoad@postgres 2724 [ + + + + : 11720 : foreach(lc2, gs->set)
+ + ]
2725 : : {
2726 : 6423 : set = lappend_int(set, tleref_to_colnum_map[lfirst_int(lc2)]);
2727 : : }
2728 : :
2729 : 5297 : result = lappend(result, set);
2730 : : }
2731 : :
2732 : 4147 : return result;
2733 : : }
2734 : :
2735 : :
2736 : : /*
2737 : : * preprocess_rowmarks - set up PlanRowMarks if needed
2738 : : */
2739 : : static void
6060 tgl@sss.pgh.pa.us 2740 : 399694 : preprocess_rowmarks(PlannerInfo *root)
2741 : : {
2742 : 399694 : Query *parse = root->parse;
2743 : : Bitmapset *rels;
2744 : : List *prowmarks;
2745 : : ListCell *l;
2746 : : int i;
2747 : :
2748 [ + + ]: 399694 : if (parse->rowMarks)
2749 : : {
2750 : : /*
2751 : : * We've got trouble if FOR [KEY] UPDATE/SHARE appears inside
2752 : : * grouping, since grouping renders a reference to individual tuple
2753 : : * CTIDs invalid. This is also checked at parse time, but that's
2754 : : * insufficient because of rule substitution, query pullup, etc.
2755 : : */
3189 2756 : 6573 : CheckSelectLocking(parse, linitial_node(RowMarkClause,
2757 : : parse->rowMarks)->strength);
2758 : : }
2759 : : else
2760 : : {
2761 : : /*
2762 : : * We only need rowmarks for UPDATE, DELETE, MERGE, or FOR [KEY]
2763 : : * UPDATE/SHARE.
2764 : : */
6060 2765 [ + + ]: 393121 : if (parse->commandType != CMD_UPDATE &&
973 dean.a.rasheed@gmail 2766 [ + + ]: 382716 : parse->commandType != CMD_DELETE &&
2767 [ + + ]: 379002 : parse->commandType != CMD_MERGE)
6060 tgl@sss.pgh.pa.us 2768 : 377521 : return;
2769 : : }
2770 : :
2771 : : /*
2772 : : * We need to have rowmarks for all base relations except the target. We
2773 : : * make a bitmapset of all base rels and then remove the items we don't
2774 : : * need or have FOR [KEY] UPDATE/SHARE marks for.
2775 : : */
1216 2776 : 22173 : rels = get_relids_in_jointree((Node *) parse->jointree, false, false);
6060 2777 [ + + ]: 22173 : if (parse->resultRelation)
2778 : 15600 : rels = bms_del_member(rels, parse->resultRelation);
2779 : :
2780 : : /*
2781 : : * Convert RowMarkClauses to PlanRowMark representation.
2782 : : */
2783 : 22173 : prowmarks = NIL;
2784 [ + + + + : 28881 : foreach(l, parse->rowMarks)
+ + ]
2785 : : {
3189 2786 : 6708 : RowMarkClause *rc = lfirst_node(RowMarkClause, l);
6058 2787 : 6708 : RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
2788 : : PlanRowMark *newrc;
2789 : :
2790 : : /*
2791 : : * Currently, it is syntactically impossible to have FOR UPDATE et al
2792 : : * applied to an update/delete target rel. If that ever becomes
2793 : : * possible, we should drop the target from the PlanRowMark list.
2794 : : */
6060 2795 [ - + ]: 6708 : Assert(rc->rti != parse->resultRelation);
2796 : :
2797 : : /*
2798 : : * Ignore RowMarkClauses for subqueries; they aren't real tables and
2799 : : * can't support true locking. Subqueries that got flattened into the
2800 : : * main query should be ignored completely. Any that didn't will get
2801 : : * ROW_MARK_COPY items in the next loop.
2802 : : */
6058 2803 [ + + ]: 6708 : if (rte->rtekind != RTE_RELATION)
2804 : 46 : continue;
2805 : :
6060 2806 : 6662 : rels = bms_del_member(rels, rc->rti);
2807 : :
6058 2808 : 6662 : newrc = makeNode(PlanRowMark);
6060 2809 : 6662 : newrc->rti = newrc->prti = rc->rti;
5589 2810 : 6662 : newrc->rowmarkId = ++(root->glob->lastRowMarkId);
4087 2811 : 6662 : newrc->markType = select_rowmark_type(rte, rc->strength);
4094 2812 : 6662 : newrc->allMarkTypes = (1 << newrc->markType);
2813 : 6662 : newrc->strength = rc->strength;
4253 alvherre@alvh.no-ip. 2814 : 6662 : newrc->waitPolicy = rc->waitPolicy;
6060 tgl@sss.pgh.pa.us 2815 : 6662 : newrc->isParent = false;
2816 : :
2817 : 6662 : prowmarks = lappend(prowmarks, newrc);
2818 : : }
2819 : :
2820 : : /*
2821 : : * Now, add rowmarks for any non-target, non-locked base relations.
2822 : : */
2823 : 22173 : i = 0;
2824 [ + - + + : 52956 : foreach(l, parse->rtable)
+ + ]
2825 : : {
3189 2826 : 30783 : RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
2827 : : PlanRowMark *newrc;
2828 : :
6060 2829 : 30783 : i++;
2830 [ + + ]: 30783 : if (!bms_is_member(i, rels))
2831 : 27834 : continue;
2832 : :
2833 : 2949 : newrc = makeNode(PlanRowMark);
2834 : 2949 : newrc->rti = newrc->prti = i;
5589 2835 : 2949 : newrc->rowmarkId = ++(root->glob->lastRowMarkId);
4087 2836 : 2949 : newrc->markType = select_rowmark_type(rte, LCS_NONE);
4094 2837 : 2949 : newrc->allMarkTypes = (1 << newrc->markType);
2838 : 2949 : newrc->strength = LCS_NONE;
3265 2839 : 2949 : newrc->waitPolicy = LockWaitBlock; /* doesn't matter */
6060 2840 : 2949 : newrc->isParent = false;
2841 : :
2842 : 2949 : prowmarks = lappend(prowmarks, newrc);
2843 : : }
2844 : :
2845 : 22173 : root->rowMarks = prowmarks;
2846 : : }
2847 : :
2848 : : /*
2849 : : * Select RowMarkType to use for a given table
2850 : : */
2851 : : RowMarkType
4087 2852 : 11505 : select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength)
2853 : : {
2854 [ + + ]: 11505 : if (rte->rtekind != RTE_RELATION)
2855 : : {
2856 : : /* If it's not a table at all, use ROW_MARK_COPY */
2857 : 1110 : return ROW_MARK_COPY;
2858 : : }
2859 [ + + ]: 10395 : else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2860 : : {
2861 : : /* Let the FDW select the rowmark type, if it wants to */
4036 2862 : 114 : FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2863 : :
2864 [ - + ]: 114 : if (fdwroutine->GetForeignRowMarkType != NULL)
4036 tgl@sss.pgh.pa.us 2865 :UBC 0 : return fdwroutine->GetForeignRowMarkType(rte, strength);
2866 : : /* Otherwise, use ROW_MARK_COPY by default */
4087 tgl@sss.pgh.pa.us 2867 :CBC 114 : return ROW_MARK_COPY;
2868 : : }
2869 : : else
2870 : : {
2871 : : /* Regular table, apply the appropriate lock type */
2872 [ + + + + : 10281 : switch (strength)
+ - ]
2873 : : {
2874 : 2048 : case LCS_NONE:
2875 : :
2876 : : /*
2877 : : * We don't need a tuple lock, only the ability to re-fetch
2878 : : * the row.
2879 : : */
2880 : 2048 : return ROW_MARK_REFERENCE;
2881 : : break;
2882 : 7064 : case LCS_FORKEYSHARE:
2883 : 7064 : return ROW_MARK_KEYSHARE;
2884 : : break;
2885 : 201 : case LCS_FORSHARE:
2886 : 201 : return ROW_MARK_SHARE;
2887 : : break;
2888 : 41 : case LCS_FORNOKEYUPDATE:
2889 : 41 : return ROW_MARK_NOKEYEXCLUSIVE;
2890 : : break;
2891 : 927 : case LCS_FORUPDATE:
2892 : 927 : return ROW_MARK_EXCLUSIVE;
2893 : : break;
2894 : : }
4087 tgl@sss.pgh.pa.us 2895 [ # # ]:UBC 0 : elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2896 : : return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2897 : : }
2898 : : }
2899 : :
2900 : : /*
2901 : : * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
2902 : : *
2903 : : * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
2904 : : * results back in *count_est and *offset_est. These variables are set to
2905 : : * 0 if the corresponding clause is not present, and -1 if it's present
2906 : : * but we couldn't estimate the value for it. (The "0" convention is OK
2907 : : * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
2908 : : * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
2909 : : * usual practice of never estimating less than one row.) These values will
2910 : : * be passed to create_limit_path, which see if you change this code.
2911 : : *
2912 : : * The return value is the suitably adjusted tuple_fraction to use for
2913 : : * planning the query. This adjustment is not overridable, since it reflects
2914 : : * plan actions that grouping_planner() will certainly take, not assumptions
2915 : : * about context.
2916 : : */
2917 : : static double
7590 tgl@sss.pgh.pa.us 2918 :CBC 3705 : preprocess_limit(PlannerInfo *root, double tuple_fraction,
2919 : : int64 *offset_est, int64 *count_est)
2920 : : {
7659 2921 : 3705 : Query *parse = root->parse;
2922 : : Node *est;
2923 : : double limit_fraction;
2924 : :
2925 : : /* Should not be called unless LIMIT or OFFSET */
7590 2926 [ + + - + ]: 3705 : Assert(parse->limitCount || parse->limitOffset);
2927 : :
2928 : : /*
2929 : : * Try to obtain the clause values. We use estimate_expression_value
2930 : : * primarily because it can sometimes do something useful with Params.
2931 : : */
2932 [ + + ]: 3705 : if (parse->limitCount)
2933 : : {
7040 2934 : 3263 : est = estimate_expression_value(root, parse->limitCount);
7590 2935 [ + - + + ]: 3263 : if (est && IsA(est, Const))
2936 : : {
2937 [ - + ]: 3258 : if (((Const *) est)->constisnull)
2938 : : {
2939 : : /* NULL indicates LIMIT ALL, ie, no limit */
7532 bruce@momjian.us 2940 :UBC 0 : *count_est = 0; /* treat as not present */
2941 : : }
2942 : : else
2943 : : {
7248 bruce@momjian.us 2944 :CBC 3258 : *count_est = DatumGetInt64(((Const *) est)->constvalue);
7590 tgl@sss.pgh.pa.us 2945 [ + + ]: 3258 : if (*count_est <= 0)
3265 2946 : 190 : *count_est = 1; /* force to at least 1 */
2947 : : }
2948 : : }
2949 : : else
7590 2950 : 5 : *count_est = -1; /* can't estimate */
2951 : : }
2952 : : else
2953 : 442 : *count_est = 0; /* not present */
2954 : :
2955 [ + + ]: 3705 : if (parse->limitOffset)
2956 : : {
7040 2957 : 652 : est = estimate_expression_value(root, parse->limitOffset);
7590 2958 [ + - + + ]: 652 : if (est && IsA(est, Const))
2959 : : {
2960 [ - + ]: 632 : if (((Const *) est)->constisnull)
2961 : : {
2962 : : /* Treat NULL as no offset; the executor will too */
7532 bruce@momjian.us 2963 :UBC 0 : *offset_est = 0; /* treat as not present */
2964 : : }
2965 : : else
2966 : : {
7248 bruce@momjian.us 2967 :CBC 632 : *offset_est = DatumGetInt64(((Const *) est)->constvalue);
7590 tgl@sss.pgh.pa.us 2968 [ - + ]: 632 : if (*offset_est < 0)
4330 tgl@sss.pgh.pa.us 2969 :UBC 0 : *offset_est = 0; /* treat as not present */
2970 : : }
2971 : : }
2972 : : else
7590 tgl@sss.pgh.pa.us 2973 :CBC 20 : *offset_est = -1; /* can't estimate */
2974 : : }
2975 : : else
2976 : 3053 : *offset_est = 0; /* not present */
2977 : :
2978 [ + + ]: 3705 : if (*count_est != 0)
2979 : : {
2980 : : /*
2981 : : * A LIMIT clause limits the absolute number of tuples returned.
2982 : : * However, if it's not a constant LIMIT then we have to guess; for
2983 : : * lack of a better idea, assume 10% of the plan's result is wanted.
2984 : : */
2985 [ + + + + ]: 3263 : if (*count_est < 0 || *offset_est < 0)
2986 : : {
2987 : : /* LIMIT or OFFSET is an expression ... punt ... */
2988 : 20 : limit_fraction = 0.10;
2989 : : }
2990 : : else
2991 : : {
2992 : : /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
2993 : 3243 : limit_fraction = (double) *count_est + (double) *offset_est;
2994 : : }
2995 : :
2996 : : /*
2997 : : * If we have absolute limits from both caller and LIMIT, use the
2998 : : * smaller value; likewise if they are both fractional. If one is
2999 : : * fractional and the other absolute, we can't easily determine which
3000 : : * is smaller, but we use the heuristic that the absolute will usually
3001 : : * be smaller.
3002 : : */
7659 3003 [ + + ]: 3263 : if (tuple_fraction >= 1.0)
3004 : : {
3005 [ + - ]: 5 : if (limit_fraction >= 1.0)
3006 : : {
3007 : : /* both absolute */
3008 [ - + ]: 5 : tuple_fraction = Min(tuple_fraction, limit_fraction);
3009 : : }
3010 : : else
3011 : : {
3012 : : /* caller absolute, limit fractional; use caller's value */
3013 : : }
3014 : : }
3015 [ + + ]: 3258 : else if (tuple_fraction > 0.0)
3016 : : {
3017 [ + - ]: 82 : if (limit_fraction >= 1.0)
3018 : : {
3019 : : /* caller fractional, limit absolute; use limit */
7590 3020 : 82 : tuple_fraction = limit_fraction;
3021 : : }
3022 : : else
3023 : : {
3024 : : /* both fractional */
7590 tgl@sss.pgh.pa.us 3025 [ # # ]:UBC 0 : tuple_fraction = Min(tuple_fraction, limit_fraction);
3026 : : }
3027 : : }
3028 : : else
3029 : : {
3030 : : /* no info from caller, just use limit */
7659 tgl@sss.pgh.pa.us 3031 :CBC 3176 : tuple_fraction = limit_fraction;
3032 : : }
3033 : : }
7590 3034 [ + + + + ]: 442 : else if (*offset_est != 0 && tuple_fraction > 0.0)
3035 : : {
3036 : : /*
3037 : : * We have an OFFSET but no LIMIT. This acts entirely differently
3038 : : * from the LIMIT case: here, we need to increase rather than decrease
3039 : : * the caller's tuple_fraction, because the OFFSET acts to cause more
3040 : : * tuples to be fetched instead of fewer. This only matters if we got
3041 : : * a tuple_fraction > 0, however.
3042 : : *
3043 : : * As above, use 10% if OFFSET is present but unestimatable.
3044 : : */
3045 [ - + ]: 12 : if (*offset_est < 0)
7590 tgl@sss.pgh.pa.us 3046 :UBC 0 : limit_fraction = 0.10;
3047 : : else
7590 tgl@sss.pgh.pa.us 3048 :CBC 12 : limit_fraction = (double) *offset_est;
3049 : :
3050 : : /*
3051 : : * If we have absolute counts from both caller and OFFSET, add them
3052 : : * together; likewise if they are both fractional. If one is
3053 : : * fractional and the other absolute, we want to take the larger, and
3054 : : * we heuristically assume that's the fractional one.
3055 : : */
3056 [ - + ]: 12 : if (tuple_fraction >= 1.0)
3057 : : {
7590 tgl@sss.pgh.pa.us 3058 [ # # ]:UBC 0 : if (limit_fraction >= 1.0)
3059 : : {
3060 : : /* both absolute, so add them together */
3061 : 0 : tuple_fraction += limit_fraction;
3062 : : }
3063 : : else
3064 : : {
3065 : : /* caller absolute, limit fractional; use limit */
3066 : 0 : tuple_fraction = limit_fraction;
3067 : : }
3068 : : }
3069 : : else
3070 : : {
7590 tgl@sss.pgh.pa.us 3071 [ - + ]:CBC 12 : if (limit_fraction >= 1.0)
3072 : : {
3073 : : /* caller fractional, limit absolute; use caller's value */
3074 : : }
3075 : : else
3076 : : {
3077 : : /* both fractional, so add them together */
7590 tgl@sss.pgh.pa.us 3078 :UBC 0 : tuple_fraction += limit_fraction;
3079 [ # # ]: 0 : if (tuple_fraction >= 1.0)
3265 3080 : 0 : tuple_fraction = 0.0; /* assume fetch all */
3081 : : }
3082 : : }
3083 : : }
3084 : :
7659 tgl@sss.pgh.pa.us 3085 :CBC 3705 : return tuple_fraction;
3086 : : }
3087 : :
3088 : : /*
3089 : : * limit_needed - do we actually need a Limit plan node?
3090 : : *
3091 : : * If we have constant-zero OFFSET and constant-null LIMIT, we can skip adding
3092 : : * a Limit node. This is worth checking for because "OFFSET 0" is a common
3093 : : * locution for an optimization fence. (Because other places in the planner
3094 : : * merely check whether parse->limitOffset isn't NULL, it will still work as
3095 : : * an optimization fence --- we're just suppressing unnecessary run-time
3096 : : * overhead.)
3097 : : *
3098 : : * This might look like it could be merged into preprocess_limit, but there's
3099 : : * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas
3100 : : * in preprocess_limit it's good enough to consider estimated values.
3101 : : */
3102 : : bool
4825 3103 : 851685 : limit_needed(Query *parse)
3104 : : {
3105 : : Node *node;
3106 : :
3107 : 851685 : node = parse->limitCount;
3108 [ + + ]: 851685 : if (node)
3109 : : {
3110 [ + + ]: 7747 : if (IsA(node, Const))
3111 : : {
3112 : : /* NULL indicates LIMIT ALL, ie, no limit */
3113 [ + - ]: 7526 : if (!((Const *) node)->constisnull)
3114 : 7526 : return true; /* LIMIT with a constant value */
3115 : : }
3116 : : else
3117 : 221 : return true; /* non-constant LIMIT */
3118 : : }
3119 : :
3120 : 843938 : node = parse->limitOffset;
3121 [ + + ]: 843938 : if (node)
3122 : : {
3123 [ + + ]: 1283 : if (IsA(node, Const))
3124 : : {
3125 : : /* Treat NULL as no offset; the executor would too */
3126 [ + - ]: 1025 : if (!((Const *) node)->constisnull)
3127 : : {
4749 bruce@momjian.us 3128 : 1025 : int64 offset = DatumGetInt64(((Const *) node)->constvalue);
3129 : :
4330 tgl@sss.pgh.pa.us 3130 [ + + ]: 1025 : if (offset != 0)
3131 : 107 : return true; /* OFFSET with a nonzero value */
3132 : : }
3133 : : }
3134 : : else
4825 3135 : 258 : return true; /* non-constant OFFSET */
3136 : : }
3137 : :
3138 : 843573 : return false; /* don't need a Limit plan node */
3139 : : }
3140 : :
3141 : : /*
3142 : : * preprocess_groupclause - do preparatory work on GROUP BY clause
3143 : : *
3144 : : * The idea here is to adjust the ordering of the GROUP BY elements
3145 : : * (which in itself is semantically insignificant) to match ORDER BY,
3146 : : * thereby allowing a single sort operation to both implement the ORDER BY
3147 : : * requirement and set up for a Unique step that implements GROUP BY.
3148 : : * We also consider partial match between GROUP BY and ORDER BY elements,
3149 : : * which could allow to implement ORDER BY using the incremental sort.
3150 : : *
3151 : : * We also consider other orderings of the GROUP BY elements, which could
3152 : : * match the sort ordering of other possible plans (eg an indexscan) and
3153 : : * thereby reduce cost. This is implemented during the generation of grouping
3154 : : * paths. See get_useful_group_keys_orderings() for details.
3155 : : *
3156 : : * Note: we need no comparable processing of the distinctClause because
3157 : : * the parser already enforced that that matches ORDER BY.
3158 : : *
3159 : : * Note: we return a fresh List, but its elements are the same
3160 : : * SortGroupClauses appearing in parse->groupClause. This is important
3161 : : * because later processing may modify the processed_groupClause list.
3162 : : *
3163 : : * For grouping sets, the order of items is instead forced to agree with that
3164 : : * of the grouping set (and items not in the grouping set are skipped). The
3165 : : * work of sorting the order of grouping set elements to match the ORDER BY if
3166 : : * possible is done elsewhere.
3167 : : */
3168 : : static List *
723 akorotkov@postgresql 3169 : 7535 : preprocess_groupclause(PlannerInfo *root, List *force)
3170 : : {
6510 tgl@sss.pgh.pa.us 3171 : 7535 : Query *parse = root->parse;
4032 andres@anarazel.de 3172 : 7535 : List *new_groupclause = NIL;
3173 : : ListCell *sl;
3174 : : ListCell *gl;
3175 : :
3176 : : /* For grouping sets, we need to force the ordering */
723 akorotkov@postgresql 3177 [ + + ]: 7535 : if (force)
3178 : : {
3179 [ + - + + : 9704 : foreach(sl, force)
+ + ]
3180 : : {
3181 : 5651 : Index ref = lfirst_int(sl);
3182 : 5651 : SortGroupClause *cl = get_sortgroupref_clause(ref, parse->groupClause);
3183 : :
3184 : 5651 : new_groupclause = lappend(new_groupclause, cl);
3185 : : }
3186 : :
3187 : 4053 : return new_groupclause;
3188 : : }
3189 : :
3190 : : /* If no ORDER BY, nothing useful to do here */
3191 [ + + ]: 3482 : if (parse->sortClause == NIL)
3192 : 1984 : return list_copy(parse->groupClause);
3193 : :
3194 : : /*
3195 : : * Scan the ORDER BY clause and construct a list of matching GROUP BY
3196 : : * items, but only as far as we can make a matching prefix.
3197 : : *
3198 : : * This code assumes that the sortClause contains no duplicate items.
3199 : : */
3200 [ + - + + : 2948 : foreach(sl, parse->sortClause)
+ + ]
3201 : : {
3202 : 1966 : SortGroupClause *sc = lfirst_node(SortGroupClause, sl);
3203 : :
3204 [ + - + + : 2873 : foreach(gl, parse->groupClause)
+ + ]
3205 : : {
3206 : 2357 : SortGroupClause *gc = lfirst_node(SortGroupClause, gl);
3207 : :
3208 [ + + ]: 2357 : if (equal(gc, sc))
3209 : : {
3210 : 1450 : new_groupclause = lappend(new_groupclause, gc);
3211 : 1450 : break;
3212 : : }
3213 : : }
3214 [ + + ]: 1966 : if (gl == NULL)
3215 : 516 : break; /* no match, so stop scanning */
3216 : : }
3217 : :
3218 : :
3219 : : /* If no match at all, no point in reordering GROUP BY */
3220 [ + + ]: 1498 : if (new_groupclause == NIL)
3221 : 228 : return list_copy(parse->groupClause);
3222 : :
3223 : : /*
3224 : : * Add any remaining GROUP BY items to the new list. We don't require a
3225 : : * complete match, because even partial match allows ORDER BY to be
3226 : : * implemented using incremental sort. Also, give up if there are any
3227 : : * non-sortable GROUP BY items, since then there's no hope anyway.
3228 : : */
3229 [ + - + + : 2857 : foreach(gl, parse->groupClause)
+ + ]
3230 : : {
3231 : 1587 : SortGroupClause *gc = lfirst_node(SortGroupClause, gl);
3232 : :
3233 [ + + ]: 1587 : if (list_member_ptr(new_groupclause, gc))
3234 : 1450 : continue; /* it matched an ORDER BY item */
3235 [ - + ]: 137 : if (!OidIsValid(gc->sortop)) /* give up, GROUP BY can't be sorted */
723 akorotkov@postgresql 3236 :UBC 0 : return list_copy(parse->groupClause);
723 akorotkov@postgresql 3237 :CBC 137 : new_groupclause = lappend(new_groupclause, gc);
3238 : : }
3239 : :
3240 : : /* Success --- install the rearranged GROUP BY list */
3241 [ - + ]: 1270 : Assert(list_length(parse->groupClause) == list_length(new_groupclause));
4032 andres@anarazel.de 3242 : 1270 : return new_groupclause;
3243 : : }
3244 : :
3245 : : /*
3246 : : * Extract lists of grouping sets that can be implemented using a single
3247 : : * rollup-type aggregate pass each. Returns a list of lists of grouping sets.
3248 : : *
3249 : : * Input must be sorted with smallest sets first. Result has each sublist
3250 : : * sorted with smallest sets first.
3251 : : *
3252 : : * We want to produce the absolute minimum possible number of lists here to
3253 : : * avoid excess sorts. Fortunately, there is an algorithm for this; the problem
3254 : : * of finding the minimal partition of a partially-ordered set into chains
3255 : : * (which is what we need, taking the list of grouping sets as a poset ordered
3256 : : * by set inclusion) can be mapped to the problem of finding the maximum
3257 : : * cardinality matching on a bipartite graph, which is solvable in polynomial
3258 : : * time with a worst case of no worse than O(n^2.5) and usually much
3259 : : * better. Since our N is at most 4096, we don't need to consider fallbacks to
3260 : : * heuristic or approximate methods. (Planning time for a 12-d cube is under
3261 : : * half a second on my modest system even with optimization off and assertions
3262 : : * on.)
3263 : : */
3264 : : static List *
3265 : 896 : extract_rollup_sets(List *groupingSets)
3266 : : {
3267 : 896 : int num_sets_raw = list_length(groupingSets);
3268 : 896 : int num_empty = 0;
4025 bruce@momjian.us 3269 : 896 : int num_sets = 0; /* distinct sets */
4032 andres@anarazel.de 3270 : 896 : int num_chains = 0;
3271 : 896 : List *result = NIL;
3272 : : List **results;
3273 : : List **orig_sets;
3274 : : Bitmapset **set_masks;
3275 : : int *chains;
3276 : : short **adjacency;
3277 : : short *adjacency_buf;
3278 : : BipartiteMatchState *state;
3279 : : int i;
3280 : : int j;
3281 : : int j_size;
3282 : 896 : ListCell *lc1 = list_head(groupingSets);
3283 : : ListCell *lc;
3284 : :
3285 : : /*
3286 : : * Start by stripping out empty sets. The algorithm doesn't require this,
3287 : : * but the planner currently needs all empty sets to be returned in the
3288 : : * first list, so we strip them here and add them back after.
3289 : : */
3290 [ + + + + ]: 1486 : while (lc1 && lfirst(lc1) == NIL)
3291 : : {
3292 : 590 : ++num_empty;
2511 tgl@sss.pgh.pa.us 3293 : 590 : lc1 = lnext(groupingSets, lc1);
3294 : : }
3295 : :
3296 : : /* bail out now if it turns out that all we had were empty sets. */
4032 andres@anarazel.de 3297 [ + + ]: 896 : if (!lc1)
3298 : 65 : return list_make1(groupingSets);
3299 : :
3300 : : /*----------
3301 : : * We don't strictly need to remove duplicate sets here, but if we don't,
3302 : : * they tend to become scattered through the result, which is a bit
3303 : : * confusing (and irritating if we ever decide to optimize them out).
3304 : : * So we remove them here and add them back after.
3305 : : *
3306 : : * For each non-duplicate set, we fill in the following:
3307 : : *
3308 : : * orig_sets[i] = list of the original set lists
3309 : : * set_masks[i] = bitmapset for testing inclusion
3310 : : * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
3311 : : *
3312 : : * chains[i] will be the result group this set is assigned to.
3313 : : *
3314 : : * We index all of these from 1 rather than 0 because it is convenient
3315 : : * to leave 0 free for the NIL node in the graph algorithm.
3316 : : *----------
3317 : : */
4025 bruce@momjian.us 3318 : 831 : orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
4032 andres@anarazel.de 3319 : 831 : set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
3320 : 831 : adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
3321 : 831 : adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
3322 : :
3323 : 831 : j_size = 0;
3324 : 831 : j = 0;
3325 : 831 : i = 1;
3326 : :
2511 tgl@sss.pgh.pa.us 3327 [ + - + + : 2861 : for_each_cell(lc, groupingSets, lc1)
+ + ]
3328 : : {
3189 3329 : 2030 : List *candidate = (List *) lfirst(lc);
4032 andres@anarazel.de 3330 : 2030 : Bitmapset *candidate_set = NULL;
3331 : : ListCell *lc2;
3332 : 2030 : int dup_of = 0;
3333 : :
3334 [ + - + + : 4827 : foreach(lc2, candidate)
+ + ]
3335 : : {
3336 : 2797 : candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
3337 : : }
3338 : :
3339 : : /* we can only be a dup if we're the same length as a previous set */
3340 [ + + ]: 2030 : if (j_size == list_length(candidate))
3341 : : {
3342 : : int k;
3343 : :
3344 [ + + ]: 1828 : for (k = j; k < i; ++k)
3345 : : {
3346 [ + + ]: 1169 : if (bms_equal(set_masks[k], candidate_set))
3347 : : {
3348 : 129 : dup_of = k;
3349 : 129 : break;
3350 : : }
3351 : : }
3352 : : }
3353 [ + - ]: 1242 : else if (j_size < list_length(candidate))
3354 : : {
3355 : 1242 : j_size = list_length(candidate);
3356 : 1242 : j = i;
3357 : : }
3358 : :
3359 [ + + ]: 2030 : if (dup_of > 0)
3360 : : {
3361 : 129 : orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
3362 : 129 : bms_free(candidate_set);
3363 : : }
3364 : : else
3365 : : {
3366 : : int k;
4025 bruce@momjian.us 3367 : 1901 : int n_adj = 0;
3368 : :
4032 andres@anarazel.de 3369 : 1901 : orig_sets[i] = list_make1(candidate);
3370 : 1901 : set_masks[i] = candidate_set;
3371 : :
3372 : : /* fill in adjacency list; no need to compare equal-size sets */
3373 : :
3374 [ + + ]: 2973 : for (k = j - 1; k > 0; --k)
3375 : : {
3376 [ + + ]: 1072 : if (bms_is_subset(set_masks[k], candidate_set))
3377 : 937 : adjacency_buf[++n_adj] = k;
3378 : : }
3379 : :
3380 [ + + ]: 1901 : if (n_adj > 0)
3381 : : {
3382 : 513 : adjacency_buf[0] = n_adj;
3383 : 513 : adjacency[i] = palloc((n_adj + 1) * sizeof(short));
3384 : 513 : memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
3385 : : }
3386 : : else
3387 : 1388 : adjacency[i] = NULL;
3388 : :
3389 : 1901 : ++i;
3390 : : }
3391 : : }
3392 : :
3393 : 831 : num_sets = i - 1;
3394 : :
3395 : : /*
3396 : : * Apply the graph matching algorithm to do the work.
3397 : : */
3398 : 831 : state = BipartiteMatch(num_sets, num_sets, adjacency);
3399 : :
3400 : : /*
3401 : : * Now, the state->pair* fields have the info we need to assign sets to
3402 : : * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
3403 : : * pair_vu[v] = u (both will be true, but we check both so that we can do
3404 : : * it in one pass)
3405 : : */
3406 : 831 : chains = palloc0((num_sets + 1) * sizeof(int));
3407 : :
3408 [ + + ]: 2732 : for (i = 1; i <= num_sets; ++i)
3409 : : {
4025 bruce@momjian.us 3410 : 1901 : int u = state->pair_vu[i];
3411 : 1901 : int v = state->pair_uv[i];
3412 : :
4032 andres@anarazel.de 3413 [ + + - + ]: 1901 : if (u > 0 && u < i)
4032 andres@anarazel.de 3414 :UBC 0 : chains[i] = chains[u];
4032 andres@anarazel.de 3415 [ + + + - ]:CBC 1901 : else if (v > 0 && v < i)
3416 : 491 : chains[i] = chains[v];
3417 : : else
3418 : 1410 : chains[i] = ++num_chains;
3419 : : }
3420 : :
3421 : : /* build result lists. */
4025 bruce@momjian.us 3422 : 831 : results = palloc0((num_chains + 1) * sizeof(List *));
3423 : :
4032 andres@anarazel.de 3424 [ + + ]: 2732 : for (i = 1; i <= num_sets; ++i)
3425 : : {
4025 bruce@momjian.us 3426 : 1901 : int c = chains[i];
3427 : :
4032 andres@anarazel.de 3428 [ - + ]: 1901 : Assert(c > 0);
3429 : :
3430 : 1901 : results[c] = list_concat(results[c], orig_sets[i]);
3431 : : }
3432 : :
3433 : : /* push any empty sets back on the first list. */
3434 [ + + ]: 1306 : while (num_empty-- > 0)
3435 : 475 : results[1] = lcons(NIL, results[1]);
3436 : :
3437 : : /* make result list */
3438 [ + + ]: 2241 : for (i = 1; i <= num_chains; ++i)
3439 : 1410 : result = lappend(result, results[i]);
3440 : :
3441 : : /*
3442 : : * Free all the things.
3443 : : *
3444 : : * (This is over-fussy for small sets but for large sets we could have
3445 : : * tied up a nontrivial amount of memory.)
3446 : : */
3447 : 831 : BipartiteMatchFree(state);
3448 : 831 : pfree(results);
3449 : 831 : pfree(chains);
3450 [ + + ]: 2732 : for (i = 1; i <= num_sets; ++i)
3451 [ + + ]: 1901 : if (adjacency[i])
3452 : 513 : pfree(adjacency[i]);
3453 : 831 : pfree(adjacency);
3454 : 831 : pfree(adjacency_buf);
3455 : 831 : pfree(orig_sets);
3456 [ + + ]: 2732 : for (i = 1; i <= num_sets; ++i)
3457 : 1901 : bms_free(set_masks[i]);
3458 : 831 : pfree(set_masks);
3459 : :
3460 : 831 : return result;
3461 : : }
3462 : :
3463 : : /*
3464 : : * Reorder the elements of a list of grouping sets such that they have correct
3465 : : * prefix relationships. Also inserts the GroupingSetData annotations.
3466 : : *
3467 : : * The input must be ordered with smallest sets first; the result is returned
3468 : : * with largest sets first. Note that the result shares no list substructure
3469 : : * with the input, so it's safe for the caller to modify it later.
3470 : : *
3471 : : * If we're passed in a sortclause, we follow its order of columns to the
3472 : : * extent possible, to minimize the chance that we add unnecessary sorts.
3473 : : * (We're trying here to ensure that GROUPING SETS ((a,b,c),(c)) ORDER BY c,b,a
3474 : : * gets implemented in one pass.)
3475 : : */
3476 : : static List *
1348 pg@bowt.ie 3477 : 1475 : reorder_grouping_sets(List *groupingSets, List *sortclause)
3478 : : {
3479 : : ListCell *lc;
4032 andres@anarazel.de 3480 : 1475 : List *previous = NIL;
3481 : 1475 : List *result = NIL;
3482 : :
1348 pg@bowt.ie 3483 [ + - + + : 4095 : foreach(lc, groupingSets)
+ + ]
3484 : : {
3189 tgl@sss.pgh.pa.us 3485 : 2620 : List *candidate = (List *) lfirst(lc);
4025 bruce@momjian.us 3486 : 2620 : List *new_elems = list_difference_int(candidate, previous);
3351 rhodiumtoad@postgres 3487 : 2620 : GroupingSetData *gs = makeNode(GroupingSetData);
3488 : :
2526 3489 [ + + + + ]: 2764 : while (list_length(sortclause) > list_length(previous) &&
3490 : : new_elems != NIL)
3491 : : {
3492 : 244 : SortGroupClause *sc = list_nth(sortclause, list_length(previous));
3493 : 244 : int ref = sc->tleSortGroupRef;
3494 : :
3495 [ + + ]: 244 : if (list_member_int(new_elems, ref))
3496 : : {
3497 : 144 : previous = lappend_int(previous, ref);
3498 : 144 : new_elems = list_delete_int(new_elems, ref);
3499 : : }
3500 : : else
3501 : : {
3502 : : /* diverged from the sortclause; give up on it */
3503 : 100 : sortclause = NIL;
3504 : 100 : break;
3505 : : }
3506 : : }
3507 : :
3508 : 2620 : previous = list_concat(previous, new_elems);
3509 : :
3351 3510 : 2620 : gs->set = list_copy(previous);
3511 : 2620 : result = lcons(gs, result);
3512 : : }
3513 : :
4032 andres@anarazel.de 3514 : 1475 : list_free(previous);
3515 : :
3516 : 1475 : return result;
3517 : : }
3518 : :
3519 : : /*
3520 : : * has_volatile_pathkey
3521 : : * Returns true if any PathKey in 'keys' has an EquivalenceClass
3522 : : * containing a volatile function. Otherwise returns false.
3523 : : */
3524 : : static bool
1229 drowley@postgresql.o 3525 : 2217 : has_volatile_pathkey(List *keys)
3526 : : {
3527 : : ListCell *lc;
3528 : :
3529 [ + + + + : 4556 : foreach(lc, keys)
+ + ]
3530 : : {
3531 : 2352 : PathKey *pathkey = lfirst_node(PathKey, lc);
3532 : :
3533 [ + + ]: 2352 : if (pathkey->pk_eclass->ec_has_volatile)
3534 : 13 : return true;
3535 : : }
3536 : :
3537 : 2204 : return false;
3538 : : }
3539 : :
3540 : : /*
3541 : : * adjust_group_pathkeys_for_groupagg
3542 : : * Add pathkeys to root->group_pathkeys to reflect the best set of
3543 : : * pre-ordered input for ordered aggregates.
3544 : : *
3545 : : * We define "best" as the pathkeys that suit the largest number of
3546 : : * aggregate functions. We find these by looking at the first ORDER BY /
3547 : : * DISTINCT aggregate and take the pathkeys for that before searching for
3548 : : * other aggregates that require the same or a more strict variation of the
3549 : : * same pathkeys. We then repeat that process for any remaining aggregates
3550 : : * with different pathkeys and if we find another set of pathkeys that suits a
3551 : : * larger number of aggregates then we select those pathkeys instead.
3552 : : *
3553 : : * When the best pathkeys are found we also mark each Aggref that can use
3554 : : * those pathkeys as aggpresorted = true.
3555 : : *
3556 : : * Note: When an aggregate function's ORDER BY / DISTINCT clause contains any
3557 : : * volatile functions, we never make use of these pathkeys. We want to ensure
3558 : : * that sorts using volatile functions are done independently in each Aggref
3559 : : * rather than once at the query level. If we were to allow this then Aggrefs
3560 : : * with compatible sort orders would all transition their rows in the same
3561 : : * order if those pathkeys were deemed to be the best pathkeys to sort on.
3562 : : * Whereas, if some other set of Aggref's pathkeys happened to be deemed
3563 : : * better pathkeys to sort on, then the volatile function Aggrefs would be
3564 : : * left to perform their sorts individually. To avoid this inconsistent
3565 : : * behavior which could make Aggref results depend on what other Aggrefs the
3566 : : * query contains, we always force Aggrefs with volatile functions to perform
3567 : : * their own sorts.
3568 : : */
3569 : : static void
1228 tgl@sss.pgh.pa.us 3570 : 1881 : adjust_group_pathkeys_for_groupagg(PlannerInfo *root)
3571 : : {
3572 : 1881 : List *grouppathkeys = root->group_pathkeys;
3573 : : List *bestpathkeys;
3574 : : Bitmapset *bestaggs;
3575 : : Bitmapset *unprocessed_aggs;
3576 : : ListCell *lc;
3577 : : int i;
3578 : :
3579 : : /* Shouldn't be here if there are grouping sets */
3580 [ - + ]: 1881 : Assert(root->parse->groupingSets == NIL);
3581 : : /* Shouldn't be here unless there are some ordered aggregates */
3582 [ - + ]: 1881 : Assert(root->numOrderedAggs > 0);
3583 : :
3584 : : /* Do nothing if disabled */
3585 [ + + ]: 1881 : if (!enable_presorted_aggregate)
3586 : 5 : return;
3587 : :
3588 : : /*
3589 : : * Make a first pass over all AggInfos to collect a Bitmapset containing
3590 : : * the indexes of all AggInfos to be processed below.
3591 : : */
1397 drowley@postgresql.o 3592 : 1876 : unprocessed_aggs = NULL;
3593 [ + - + + : 4318 : foreach(lc, root->agginfos)
+ + ]
3594 : : {
3595 : 2442 : AggInfo *agginfo = lfirst_node(AggInfo, lc);
3596 : 2442 : Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3597 : :
3598 [ + + ]: 2442 : if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
3599 : 214 : continue;
3600 : :
3601 : : /* Skip unless there's a DISTINCT or ORDER BY clause */
405 3602 [ + + + + ]: 2228 : if (aggref->aggdistinct == NIL && aggref->aggorder == NIL)
3603 : 248 : continue;
3604 : :
3605 : : /* Additional safety checks are needed if there's a FILTER clause */
3606 [ + + ]: 1980 : if (aggref->aggfilter != NULL)
3607 : : {
3608 : : ListCell *lc2;
3609 : 43 : bool allow_presort = true;
3610 : :
3611 : : /*
3612 : : * When the Aggref has a FILTER clause, it's possible that the
3613 : : * filter removes rows that cannot be sorted because the
3614 : : * expression to sort by results in an error during its
3615 : : * evaluation. This is a problem for presorting as that happens
3616 : : * before the FILTER, whereas without presorting, the Aggregate
3617 : : * node will apply the FILTER *before* sorting. So that we never
3618 : : * try to sort anything that might error, here we aim to skip over
3619 : : * any Aggrefs with arguments with expressions which, when
3620 : : * evaluated, could cause an ERROR. Vars and Consts are ok. There
3621 : : * may be more cases that should be allowed, but more thought
3622 : : * needs to be given. Err on the side of caution.
3623 : : */
3624 [ + - + + : 83 : foreach(lc2, aggref->args)
+ + ]
3625 : : {
3626 : 58 : TargetEntry *tle = (TargetEntry *) lfirst(lc2);
3627 : 58 : Expr *expr = tle->expr;
3628 : :
3629 [ + + ]: 68 : while (IsA(expr, RelabelType))
3630 : 10 : expr = (Expr *) (castNode(RelabelType, expr))->arg;
3631 : :
3632 : : /* Common case, Vars and Consts are ok */
3633 [ + + + + ]: 58 : if (IsA(expr, Var) || IsA(expr, Const))
3634 : 40 : continue;
3635 : :
3636 : : /* Unsupported. Don't try to presort for this Aggref */
3637 : 18 : allow_presort = false;
3638 : 18 : break;
3639 : : }
3640 : :
3641 : : /* Skip unsupported Aggrefs */
3642 [ + + ]: 43 : if (!allow_presort)
3643 : 18 : continue;
3644 : : }
3645 : :
3646 : 1962 : unprocessed_aggs = bms_add_member(unprocessed_aggs,
3647 : : foreach_current_index(lc));
3648 : : }
3649 : :
3650 : : /*
3651 : : * Now process all the unprocessed_aggs to find the best set of pathkeys
3652 : : * for the given set of aggregates.
3653 : : *
3654 : : * On the first outer loop here 'bestaggs' will be empty. We'll populate
3655 : : * this during the first loop using the pathkeys for the very first
3656 : : * AggInfo then taking any stronger pathkeys from any other AggInfos with
3657 : : * a more strict set of compatible pathkeys. Once the outer loop is
3658 : : * complete, we mark off all the aggregates with compatible pathkeys then
3659 : : * remove those from the unprocessed_aggs and repeat the process to try to
3660 : : * find another set of pathkeys that are suitable for a larger number of
3661 : : * aggregates. The outer loop will stop when there are not enough
3662 : : * unprocessed aggregates for it to be possible to find a set of pathkeys
3663 : : * to suit a larger number of aggregates.
3664 : : */
1397 3665 : 1876 : bestpathkeys = NIL;
3666 : 1876 : bestaggs = NULL;
3667 [ + + ]: 3703 : while (bms_num_members(unprocessed_aggs) > bms_num_members(bestaggs))
3668 : : {
3669 : 1827 : Bitmapset *aggindexes = NULL;
3670 : 1827 : List *currpathkeys = NIL;
3671 : :
3672 : 1827 : i = -1;
3673 [ + + ]: 4044 : while ((i = bms_next_member(unprocessed_aggs, i)) >= 0)
3674 : : {
3675 : 2217 : AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3676 : 2217 : Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
3677 : : List *sortlist;
3678 : : List *pathkeys;
3679 : :
3680 [ + + ]: 2217 : if (aggref->aggdistinct != NIL)
3681 : 599 : sortlist = aggref->aggdistinct;
3682 : : else
3683 : 1618 : sortlist = aggref->aggorder;
3684 : :
1229 3685 : 2217 : pathkeys = make_pathkeys_for_sortclauses(root, sortlist,
3686 : : aggref->args);
3687 : :
3688 : : /*
3689 : : * Ignore Aggrefs which have volatile functions in their ORDER BY
3690 : : * or DISTINCT clause.
3691 : : */
3692 [ + + ]: 2217 : if (has_volatile_pathkey(pathkeys))
3693 : : {
3694 : 13 : unprocessed_aggs = bms_del_member(unprocessed_aggs, i);
3695 : 13 : continue;
3696 : : }
3697 : :
3698 : : /*
3699 : : * When not set yet, take the pathkeys from the first unprocessed
3700 : : * aggregate.
3701 : : */
1397 3702 [ + + ]: 2204 : if (currpathkeys == NIL)
3703 : : {
1229 3704 : 1824 : currpathkeys = pathkeys;
3705 : :
3706 : : /* include the GROUP BY pathkeys, if they exist */
1397 3707 [ + + ]: 1824 : if (grouppathkeys != NIL)
3708 : 226 : currpathkeys = append_pathkeys(list_copy(grouppathkeys),
3709 : : currpathkeys);
3710 : :
3711 : : /* record that we found pathkeys for this aggregate */
3712 : 1824 : aggindexes = bms_add_member(aggindexes, i);
3713 : : }
3714 : : else
3715 : : {
3716 : : /* now look for a stronger set of matching pathkeys */
3717 : :
3718 : : /* include the GROUP BY pathkeys, if they exist */
3719 [ + + ]: 380 : if (grouppathkeys != NIL)
3720 : 240 : pathkeys = append_pathkeys(list_copy(grouppathkeys),
3721 : : pathkeys);
3722 : :
3723 : : /* are 'pathkeys' compatible or better than 'currpathkeys'? */
3724 [ + + + - ]: 380 : switch (compare_pathkeys(currpathkeys, pathkeys))
3725 : : {
3726 : 10 : case PATHKEYS_BETTER2:
3727 : : /* 'pathkeys' are stronger, use these ones instead */
3728 : 10 : currpathkeys = pathkeys;
3729 : : pg_fallthrough;
3730 : :
3731 : 55 : case PATHKEYS_BETTER1:
3732 : : /* 'pathkeys' are less strict */
3733 : : pg_fallthrough;
3734 : :
3735 : : case PATHKEYS_EQUAL:
3736 : : /* mark this aggregate as covered by 'currpathkeys' */
3737 : 55 : aggindexes = bms_add_member(aggindexes, i);
3738 : 55 : break;
3739 : :
3740 : 325 : case PATHKEYS_DIFFERENT:
3741 : 325 : break;
3742 : : }
3743 : : }
3744 : : }
3745 : :
3746 : : /* remove the aggregates that we've just processed */
3747 : 1827 : unprocessed_aggs = bms_del_members(unprocessed_aggs, aggindexes);
3748 : :
3749 : : /*
3750 : : * If this pass included more aggregates than the previous best then
3751 : : * use these ones as the best set.
3752 : : */
3753 [ + + ]: 1827 : if (bms_num_members(aggindexes) > bms_num_members(bestaggs))
3754 : : {
3755 : 1739 : bestaggs = aggindexes;
3756 : 1739 : bestpathkeys = currpathkeys;
3757 : : }
3758 : : }
3759 : :
3760 : : /*
3761 : : * If we found any ordered aggregates, update root->group_pathkeys to add
3762 : : * the best set of aggregate pathkeys. Note that bestpathkeys includes
3763 : : * the original GROUP BY pathkeys already.
3764 : : */
1228 tgl@sss.pgh.pa.us 3765 [ + + ]: 1876 : if (bestpathkeys != NIL)
3766 : 1689 : root->group_pathkeys = bestpathkeys;
3767 : :
3768 : : /*
3769 : : * Now that we've found the best set of aggregates we can set the
3770 : : * presorted flag to indicate to the executor that it needn't bother
3771 : : * performing a sort for these Aggrefs. We're able to do this now as
3772 : : * there's no chance of a Hash Aggregate plan as create_grouping_paths
3773 : : * will not mark the GROUP BY as GROUPING_CAN_USE_HASH due to the presence
3774 : : * of ordered aggregates.
3775 : : */
1397 drowley@postgresql.o 3776 : 1876 : i = -1;
3777 [ + + ]: 3645 : while ((i = bms_next_member(bestaggs, i)) >= 0)
3778 : : {
3779 : 1769 : AggInfo *agginfo = list_nth_node(AggInfo, root->agginfos, i);
3780 : :
3781 [ + - + + : 3553 : foreach(lc, agginfo->aggrefs)
+ + ]
3782 : : {
3783 : 1784 : Aggref *aggref = lfirst_node(Aggref, lc);
3784 : :
3785 : 1784 : aggref->aggpresorted = true;
3786 : : }
3787 : : }
3788 : : }
3789 : :
3790 : : /*
3791 : : * Compute query_pathkeys and other pathkeys during plan generation
3792 : : */
3793 : : static void
4779 tgl@sss.pgh.pa.us 3794 : 392058 : standard_qp_callback(PlannerInfo *root, void *extra)
3795 : : {
3796 : 392058 : Query *parse = root->parse;
3797 : 392058 : standard_qp_extra *qp_extra = (standard_qp_extra *) extra;
2621 3798 : 392058 : List *tlist = root->processed_tlist;
4779 3799 : 392058 : List *activeWindows = qp_extra->activeWindows;
3800 : :
3801 : : /*
3802 : : * Calculate pathkeys that represent grouping/ordering and/or ordered
3803 : : * aggregate requirements.
3804 : : */
1228 3805 [ + + ]: 392058 : if (qp_extra->gset_data)
3806 : : {
3807 : : /*
3808 : : * With grouping sets, just use the first RollupData's groupClause. We
3809 : : * don't make any effort to optimize grouping clauses when there are
3810 : : * grouping sets, nor can we combine aggregate ordering keys with
3811 : : * grouping.
3812 : : */
3813 : 901 : List *rollups = qp_extra->gset_data->rollups;
3814 [ + + ]: 901 : List *groupClause = (rollups ? linitial_node(RollupData, rollups)->groupClause : NIL);
3815 : :
3816 [ + - ]: 901 : if (grouping_is_sortable(groupClause))
3817 : : {
3818 : : bool sortable;
3819 : :
3820 : : /*
3821 : : * The groupClause is logically below the grouping step. So if
3822 : : * there is an RTE entry for the grouping step, we need to remove
3823 : : * its RT index from the sort expressions before we make PathKeys
3824 : : * for them.
3825 : : */
627 rguo@postgresql.org 3826 : 901 : root->group_pathkeys =
3827 : 901 : make_pathkeys_for_sortclauses_extended(root,
3828 : : &groupClause,
3829 : : tlist,
3830 : : false,
3831 : 901 : parse->hasGroupRTE,
3832 : : &sortable,
3833 : : false);
3834 [ - + ]: 901 : Assert(sortable);
1228 tgl@sss.pgh.pa.us 3835 : 901 : root->num_groupby_pathkeys = list_length(root->group_pathkeys);
3836 : : }
3837 : : else
3838 : : {
1228 tgl@sss.pgh.pa.us 3839 :UBC 0 : root->group_pathkeys = NIL;
3840 : 0 : root->num_groupby_pathkeys = 0;
3841 : : }
3842 : : }
1228 tgl@sss.pgh.pa.us 3843 [ + + + + ]:CBC 391157 : else if (parse->groupClause || root->numOrderedAggs > 0)
3844 : 5175 : {
3845 : : /*
3846 : : * With a plain GROUP BY list, we can remove any grouping items that
3847 : : * are proven redundant by EquivalenceClass processing. For example,
3848 : : * we can remove y given "WHERE x = y GROUP BY x, y". These aren't
3849 : : * especially common cases, but they're nearly free to detect. Note
3850 : : * that we remove redundant items from processed_groupClause but not
3851 : : * the original parse->groupClause.
3852 : : */
3853 : : bool sortable;
3854 : :
3855 : : /*
3856 : : * Convert group clauses into pathkeys. Set the ec_sortref field of
3857 : : * EquivalenceClass'es if it's not set yet.
3858 : : */
3859 : 5175 : root->group_pathkeys =
3860 : 5175 : make_pathkeys_for_sortclauses_extended(root,
3861 : : &root->processed_groupClause,
3862 : : tlist,
3863 : : true,
3864 : : false,
3865 : : &sortable,
3866 : : true);
3867 [ - + ]: 5175 : if (!sortable)
3868 : : {
3869 : : /* Can't sort; no point in considering aggregate ordering either */
1228 tgl@sss.pgh.pa.us 3870 :UBC 0 : root->group_pathkeys = NIL;
3871 : 0 : root->num_groupby_pathkeys = 0;
3872 : : }
3873 : : else
3874 : : {
1228 tgl@sss.pgh.pa.us 3875 :CBC 5175 : root->num_groupby_pathkeys = list_length(root->group_pathkeys);
3876 : : /* If we have ordered aggs, consider adding onto group_pathkeys */
3877 [ + + ]: 5175 : if (root->numOrderedAggs > 0)
3878 : 1881 : adjust_group_pathkeys_for_groupagg(root);
3879 : : }
3880 : : }
3881 : : else
3882 : : {
4779 3883 : 385982 : root->group_pathkeys = NIL;
1397 drowley@postgresql.o 3884 : 385982 : root->num_groupby_pathkeys = 0;
3885 : : }
3886 : :
3887 : : /* We consider only the first (bottom) window in pathkeys logic */
4779 tgl@sss.pgh.pa.us 3888 [ + + ]: 392058 : if (activeWindows != NIL)
3889 : : {
3189 3890 : 2232 : WindowClause *wc = linitial_node(WindowClause, activeWindows);
3891 : :
4779 3892 : 2232 : root->window_pathkeys = make_pathkeys_for_window(root,
3893 : : wc,
3894 : : tlist);
3895 : : }
3896 : : else
3897 : 389826 : root->window_pathkeys = NIL;
3898 : :
3899 : : /*
3900 : : * As with GROUP BY, we can discard any DISTINCT items that are proven
3901 : : * redundant by EquivalenceClass processing. The non-redundant list is
3902 : : * kept in root->processed_distinctClause, leaving the original
3903 : : * parse->distinctClause alone.
3904 : : */
1228 3905 [ + + ]: 392058 : if (parse->distinctClause)
3906 : : {
3907 : : bool sortable;
3908 : :
3909 : : /* Make a copy since pathkey processing can modify the list */
3910 : 1967 : root->processed_distinctClause = list_copy(parse->distinctClause);
4779 3911 : 1967 : root->distinct_pathkeys =
1228 3912 : 1967 : make_pathkeys_for_sortclauses_extended(root,
3913 : : &root->processed_distinctClause,
3914 : : tlist,
3915 : : true,
3916 : : false,
3917 : : &sortable,
3918 : : false);
3919 [ + + ]: 1967 : if (!sortable)
3920 : 5 : root->distinct_pathkeys = NIL;
3921 : : }
3922 : : else
4779 3923 : 390091 : root->distinct_pathkeys = NIL;
3924 : :
3925 : 392058 : root->sort_pathkeys =
3926 : 392058 : make_pathkeys_for_sortclauses(root,
3927 : : parse->sortClause,
3928 : : tlist);
3929 : :
3930 : : /* setting setop_pathkeys might be useful to the union planner */
527 3931 [ + + ]: 392058 : if (qp_extra->setop != NULL)
3932 : : {
3933 : : List *groupClauses;
3934 : : bool sortable;
3935 : :
739 rhaas@postgresql.org 3936 : 10473 : groupClauses = generate_setop_child_grouplist(qp_extra->setop, tlist);
3937 : :
3938 : 10473 : root->setop_pathkeys =
3939 : 10473 : make_pathkeys_for_sortclauses_extended(root,
3940 : : &groupClauses,
3941 : : tlist,
3942 : : false,
3943 : : false,
3944 : : &sortable,
3945 : : false);
3946 [ + + ]: 10473 : if (!sortable)
3947 : 120 : root->setop_pathkeys = NIL;
3948 : : }
3949 : : else
3950 : 381585 : root->setop_pathkeys = NIL;
3951 : :
3952 : : /*
3953 : : * Figure out whether we want a sorted result from query_planner.
3954 : : *
3955 : : * If we have a sortable GROUP BY clause, then we want a result sorted
3956 : : * properly for grouping. Otherwise, if we have window functions to
3957 : : * evaluate, we try to sort for the first window. Otherwise, if there's a
3958 : : * sortable DISTINCT clause that's more rigorous than the ORDER BY clause,
3959 : : * we try to produce output that's sufficiently well sorted for the
3960 : : * DISTINCT. Otherwise, if there is an ORDER BY clause, we want to sort
3961 : : * by the ORDER BY clause. Otherwise, if we're a subquery being planned
3962 : : * for a set operation which can benefit from presorted results and have a
3963 : : * sortable targetlist, we want to sort by the target list.
3964 : : *
3965 : : * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a superset
3966 : : * of GROUP BY, it would be tempting to request sort by ORDER BY --- but
3967 : : * that might just leave us failing to exploit an available sort order at
3968 : : * all. Needs more thought. The choice for DISTINCT versus ORDER BY is
3969 : : * much easier, since we know that the parser ensured that one is a
3970 : : * superset of the other.
3971 : : */
4779 tgl@sss.pgh.pa.us 3972 [ + + ]: 392058 : if (root->group_pathkeys)
3973 : 5689 : root->query_pathkeys = root->group_pathkeys;
3974 [ + + ]: 386369 : else if (root->window_pathkeys)
3975 : 1787 : root->query_pathkeys = root->window_pathkeys;
3976 [ + + ]: 769164 : else if (list_length(root->distinct_pathkeys) >
3977 : 384582 : list_length(root->sort_pathkeys))
3978 : 1597 : root->query_pathkeys = root->distinct_pathkeys;
3979 [ + + ]: 382985 : else if (root->sort_pathkeys)
3980 : 56694 : root->query_pathkeys = root->sort_pathkeys;
739 rhaas@postgresql.org 3981 [ + + ]: 326291 : else if (root->setop_pathkeys != NIL)
3982 : 9493 : root->query_pathkeys = root->setop_pathkeys;
3983 : : else
4779 tgl@sss.pgh.pa.us 3984 : 316798 : root->query_pathkeys = NIL;
3985 : 392058 : }
3986 : :
3987 : : /*
3988 : : * Estimate number of groups produced by grouping clauses (1 if not grouping)
3989 : : *
3990 : : * path_rows: number of output rows from scan/join step
3991 : : * gd: grouping sets data including list of grouping sets and their clauses
3992 : : * target_list: target list containing group clause references
3993 : : *
3994 : : * If doing grouping sets, we also annotate the gsets data with the estimates
3995 : : * for each set and each individual rollup list, with a view to later
3996 : : * determining whether some combination of them could be hashed instead.
3997 : : */
3998 : : static double
3736 3999 : 41243 : get_number_of_groups(PlannerInfo *root,
4000 : : double path_rows,
4001 : : grouping_sets_data *gd,
4002 : : List *target_list)
4003 : : {
5953 4004 : 41243 : Query *parse = root->parse;
4005 : : double dNumGroups;
4006 : :
3736 4007 [ + + ]: 41243 : if (parse->groupClause)
4008 : : {
4009 : : List *groupExprs;
4010 : :
4011 [ + + ]: 8729 : if (parse->groupingSets)
4012 : : {
4013 : : /* Add up the estimates for each grouping set */
4014 : : ListCell *lc;
4015 : :
3300 bruce@momjian.us 4016 [ - + ]: 836 : Assert(gd); /* keep Coverity happy */
4017 : :
3736 tgl@sss.pgh.pa.us 4018 : 836 : dNumGroups = 0;
4019 : :
3351 rhodiumtoad@postgres 4020 [ + + + + : 2246 : foreach(lc, gd->rollups)
+ + ]
4021 : : {
3189 tgl@sss.pgh.pa.us 4022 : 1410 : RollupData *rollup = lfirst_node(RollupData, lc);
4023 : : ListCell *lc2;
4024 : : ListCell *lc3;
4025 : :
3351 rhodiumtoad@postgres 4026 : 1410 : groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
4027 : : target_list);
4028 : :
4029 : 1410 : rollup->numGroups = 0.0;
4030 : :
1333 drowley@postgresql.o 4031 : 3915 : forboth(lc2, rollup->gsets, lc3, rollup->gsets_data)
[ + - + +
+ - + + +
+ + - +
+ ]
4032 : : {
4033 : 2505 : List *gset = (List *) lfirst(lc2);
4034 : 2505 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc3);
3351 rhodiumtoad@postgres 4035 : 2505 : double numGroups = estimate_num_groups(root,
4036 : : groupExprs,
4037 : : path_rows,
4038 : : &gset,
4039 : : NULL);
4040 : :
4041 : 2505 : gs->numGroups = numGroups;
4042 : 2505 : rollup->numGroups += numGroups;
4043 : : }
4044 : :
4045 : 1410 : dNumGroups += rollup->numGroups;
4046 : : }
4047 : :
4048 [ + + ]: 836 : if (gd->hash_sets_idx)
4049 : : {
4050 : : ListCell *lc2;
4051 : :
4052 : 29 : gd->dNumHashGroups = 0;
4053 : :
4054 : 29 : groupExprs = get_sortgrouplist_exprs(parse->groupClause,
4055 : : target_list);
4056 : :
4057 : 63 : forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
[ + - + +
+ - + + +
+ + - +
+ ]
4058 : : {
4059 : 34 : List *gset = (List *) lfirst(lc);
3189 tgl@sss.pgh.pa.us 4060 : 34 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc2);
3351 rhodiumtoad@postgres 4061 : 34 : double numGroups = estimate_num_groups(root,
4062 : : groupExprs,
4063 : : path_rows,
4064 : : &gset,
4065 : : NULL);
4066 : :
4067 : 34 : gs->numGroups = numGroups;
4068 : 34 : gd->dNumHashGroups += numGroups;
4069 : : }
4070 : :
4071 : 29 : dNumGroups += gd->dNumHashGroups;
4072 : : }
4073 : : }
4074 : : else
4075 : : {
4076 : : /* Plain GROUP BY -- estimate based on optimized groupClause */
1228 tgl@sss.pgh.pa.us 4077 : 7893 : groupExprs = get_sortgrouplist_exprs(root->processed_groupClause,
4078 : : target_list);
4079 : :
3736 4080 : 7893 : dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
4081 : : NULL, NULL);
4082 : : }
4083 : : }
4084 [ + + ]: 32514 : else if (parse->groupingSets)
4085 : : {
4086 : : /* Empty grouping sets ... one result row for each one */
4087 : 50 : dNumGroups = list_length(parse->groupingSets);
4088 : : }
4089 [ - + - - ]: 32464 : else if (parse->hasAggs || root->hasHavingQual)
4090 : : {
4091 : : /* Plain aggregation, one result row */
4092 : 32464 : dNumGroups = 1;
4093 : : }
4094 : : else
4095 : : {
4096 : : /* Not grouping */
3736 tgl@sss.pgh.pa.us 4097 :UBC 0 : dNumGroups = 1;
4098 : : }
4099 : :
3736 tgl@sss.pgh.pa.us 4100 :CBC 41243 : return dNumGroups;
4101 : : }
4102 : :
4103 : : /*
4104 : : * create_grouping_paths
4105 : : *
4106 : : * Build a new upperrel containing Paths for grouping and/or aggregation.
4107 : : * Along the way, we also build an upperrel for Paths which are partially
4108 : : * grouped and/or aggregated. A partially grouped and/or aggregated path
4109 : : * needs a FinalizeAggregate node to complete the aggregation. Currently,
4110 : : * the only partially grouped paths we build are also partial paths; that
4111 : : * is, they need a Gather and then a FinalizeAggregate.
4112 : : *
4113 : : * input_rel: contains the source-data Paths
4114 : : * target: the pathtarget for the result Paths to compute
4115 : : * gd: grouping sets data including list of grouping sets and their clauses
4116 : : *
4117 : : * Note: all Paths in input_rel are expected to return the target computed
4118 : : * by make_group_input_target.
4119 : : */
4120 : : static RelOptInfo *
4121 : 34247 : create_grouping_paths(PlannerInfo *root,
4122 : : RelOptInfo *input_rel,
4123 : : PathTarget *target,
4124 : : bool target_parallel_safe,
4125 : : grouping_sets_data *gd)
4126 : : {
4127 : 34247 : Query *parse = root->parse;
4128 : : RelOptInfo *grouped_rel;
4129 : : RelOptInfo *partially_grouped_rel;
4130 : : AggClauseCosts agg_costs;
4131 : :
2013 heikki.linnakangas@i 4132 [ + - + - : 205482 : MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
+ - + - +
+ ]
4133 : 34247 : get_agg_clause_costs(root, AGGSPLIT_SIMPLE, &agg_costs);
4134 : :
4135 : : /*
4136 : : * Create grouping relation to hold fully aggregated grouping and/or
4137 : : * aggregation paths.
4138 : : */
2991 rhaas@postgresql.org 4139 : 34247 : grouped_rel = make_grouping_rel(root, input_rel, target,
4140 : : target_parallel_safe, parse->havingQual);
4141 : :
4142 : : /*
4143 : : * Create either paths for a degenerate grouping or paths for ordinary
4144 : : * grouping, as appropriate.
4145 : : */
2998 4146 [ + + ]: 34247 : if (is_degenerate_grouping(root))
2993 4147 : 35 : create_degenerate_grouping_paths(root, input_rel, grouped_rel);
4148 : : else
4149 : : {
4150 : 34212 : int flags = 0;
4151 : : GroupPathExtraData extra;
4152 : :
4153 : : /*
4154 : : * Determine whether it's possible to perform sort-based
4155 : : * implementations of grouping. (Note that if processed_groupClause
4156 : : * is empty, grouping_is_sortable() is trivially true, and all the
4157 : : * pathkeys_contained_in() tests will succeed too, so that we'll
4158 : : * consider every surviving input path.)
4159 : : *
4160 : : * If we have grouping sets, we might be able to sort some but not all
4161 : : * of them; in this case, we need can_sort to be true as long as we
4162 : : * must consider any sorted-input plan.
4163 : : */
4164 [ + + + + ]: 34212 : if ((gd && gd->rollups != NIL)
1228 tgl@sss.pgh.pa.us 4165 [ + + ]: 33331 : || grouping_is_sortable(root->processed_groupClause))
2993 rhaas@postgresql.org 4166 : 34207 : flags |= GROUPING_CAN_USE_SORT;
4167 : :
4168 : : /*
4169 : : * Determine whether we should consider hash-based implementations of
4170 : : * grouping.
4171 : : *
4172 : : * Hashed aggregation only applies if we're grouping. If we have
4173 : : * grouping sets, some groups might be hashable but others not; in
4174 : : * this case we set can_hash true as long as there is nothing globally
4175 : : * preventing us from hashing (and we should therefore consider plans
4176 : : * with hashes).
4177 : : *
4178 : : * Executor doesn't support hashed aggregation with DISTINCT or ORDER
4179 : : * BY aggregates. (Doing so would imply storing *all* the input
4180 : : * values in the hash table, and/or running many sorts in parallel,
4181 : : * either of which seems like a certain loser.) We similarly don't
4182 : : * support ordered-set aggregates in hashed aggregation, but that case
4183 : : * is also included in the numOrderedAggs count.
4184 : : *
4185 : : * Note: grouping_is_hashable() is much more expensive to check than
4186 : : * the other gating conditions, so we want to do it last.
4187 : : */
4188 [ + + ]: 34212 : if ((parse->groupClause != NIL &&
2013 heikki.linnakangas@i 4189 [ + + + + : 8419 : root->numOrderedAggs == 0 &&
+ + ]
1228 tgl@sss.pgh.pa.us 4190 : 4101 : (gd ? gd->any_hashable : grouping_is_hashable(root->processed_groupClause))))
2993 rhaas@postgresql.org 4191 : 4098 : flags |= GROUPING_CAN_USE_HASH;
4192 : :
4193 : : /*
4194 : : * Determine whether partial aggregation is possible.
4195 : : */
2013 heikki.linnakangas@i 4196 [ + + ]: 34212 : if (can_partial_agg(root))
2993 rhaas@postgresql.org 4197 : 30083 : flags |= GROUPING_CAN_PARTIAL_AGG;
4198 : :
2991 4199 : 34212 : extra.flags = flags;
4200 : 34212 : extra.target_parallel_safe = target_parallel_safe;
4201 : 34212 : extra.havingQual = parse->havingQual;
4202 : 34212 : extra.targetList = parse->targetList;
4203 : 34212 : extra.partial_costs_set = false;
4204 : :
4205 : : /*
4206 : : * Determine whether partitionwise aggregation is in theory possible.
4207 : : * It can be disabled by the user, and for now, we don't try to
4208 : : * support grouping sets. create_ordinary_grouping_paths() will check
4209 : : * additional conditions, such as whether input_rel is partitioned.
4210 : : */
4211 [ + + + + ]: 34212 : if (enable_partitionwise_aggregate && !parse->groupingSets)
4212 : 580 : extra.patype = PARTITIONWISE_AGGREGATE_FULL;
4213 : : else
4214 : 33632 : extra.patype = PARTITIONWISE_AGGREGATE_NONE;
4215 : :
2993 4216 : 34212 : create_ordinary_grouping_paths(root, input_rel, grouped_rel,
4217 : : &agg_costs, gd, &extra,
4218 : : &partially_grouped_rel);
4219 : : }
4220 : :
2998 4221 : 34243 : set_cheapest(grouped_rel);
4222 : 34243 : return grouped_rel;
4223 : : }
4224 : :
4225 : : /*
4226 : : * make_grouping_rel
4227 : : *
4228 : : * Create a new grouping rel and set basic properties.
4229 : : *
4230 : : * input_rel represents the underlying scan/join relation.
4231 : : * target is the output expected from the grouping relation.
4232 : : */
4233 : : static RelOptInfo *
2991 4234 : 36042 : make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
4235 : : PathTarget *target, bool target_parallel_safe,
4236 : : Node *havingQual)
4237 : : {
4238 : : RelOptInfo *grouped_rel;
4239 : :
4240 [ + + + + : 36042 : if (IS_OTHER_REL(input_rel))
- + ]
4241 : : {
4242 : 1795 : grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG,
4243 : : input_rel->relids);
4244 : 1795 : grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
4245 : : }
4246 : : else
4247 : : {
4248 : : /*
4249 : : * By tradition, the relids set for the main grouping relation is
4250 : : * NULL. (This could be changed, but might require adjustments
4251 : : * elsewhere.)
4252 : : */
4253 : 34247 : grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
4254 : : }
4255 : :
4256 : : /* Set target. */
4257 : 36042 : grouped_rel->reltarget = target;
4258 : :
4259 : : /*
4260 : : * If the input relation is not parallel-safe, then the grouped relation
4261 : : * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
4262 : : * target list and HAVING quals are parallel-safe.
4263 : : */
4264 [ + + + + : 59060 : if (input_rel->consider_parallel && target_parallel_safe &&
+ + ]
179 peter@eisentraut.org 4265 :GNC 23018 : is_parallel_safe(root, havingQual))
2991 rhaas@postgresql.org 4266 :CBC 22993 : grouped_rel->consider_parallel = true;
4267 : :
4268 : : /* Assume that the same path generation strategies are allowed */
122 rhaas@postgresql.org 4269 :GNC 36042 : grouped_rel->pgs_mask = input_rel->pgs_mask;
4270 : :
4271 : : /*
4272 : : * If the input rel belongs to a single FDW, so does the grouped rel.
4273 : : */
2991 rhaas@postgresql.org 4274 :CBC 36042 : grouped_rel->serverid = input_rel->serverid;
4275 : 36042 : grouped_rel->userid = input_rel->userid;
4276 : 36042 : grouped_rel->useridiscurrent = input_rel->useridiscurrent;
4277 : 36042 : grouped_rel->fdwroutine = input_rel->fdwroutine;
4278 : :
4279 : 36042 : return grouped_rel;
4280 : : }
4281 : :
4282 : : /*
4283 : : * is_degenerate_grouping
4284 : : *
4285 : : * A degenerate grouping is one in which the query has a HAVING qual and/or
4286 : : * grouping sets, but no aggregates and no GROUP BY (which implies that the
4287 : : * grouping sets are all empty).
4288 : : */
4289 : : static bool
2998 4290 : 34247 : is_degenerate_grouping(PlannerInfo *root)
4291 : : {
4292 : 34247 : Query *parse = root->parse;
4293 : :
4294 [ + + ]: 33105 : return (root->hasHavingQual || parse->groupingSets) &&
4295 [ + + + + : 67352 : !parse->hasAggs && parse->groupClause == NIL;
+ + ]
4296 : : }
4297 : :
4298 : : /*
4299 : : * create_degenerate_grouping_paths
4300 : : *
4301 : : * When the grouping is degenerate (see is_degenerate_grouping), we are
4302 : : * supposed to emit either zero or one row for each grouping set depending on
4303 : : * whether HAVING succeeds. Furthermore, there cannot be any variables in
4304 : : * either HAVING or the targetlist, so we actually do not need the FROM table
4305 : : * at all! We can just throw away the plan-so-far and generate a Result node.
4306 : : * This is a sufficiently unusual corner case that it's not worth contorting
4307 : : * the structure of this module to avoid having to generate the earlier paths
4308 : : * in the first place.
4309 : : */
4310 : : static void
4311 : 35 : create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
4312 : : RelOptInfo *grouped_rel)
4313 : : {
4314 : 35 : Query *parse = root->parse;
4315 : : int nrows;
4316 : : Path *path;
4317 : :
4318 : 35 : nrows = list_length(parse->groupingSets);
4319 [ + + ]: 35 : if (nrows > 1)
4320 : : {
4321 : : /*
4322 : : * Doesn't seem worthwhile writing code to cons up a generate_series
4323 : : * or a values scan to emit multiple rows. Instead just make N clones
4324 : : * and append them. (With a volatile HAVING clause, this means you
4325 : : * might get between 0 and N output rows. Offhand I think that's
4326 : : * desired.)
4327 : : */
109 rhaas@postgresql.org 4328 :GNC 10 : AppendPathInput append = {0};
4329 : :
2998 rhaas@postgresql.org 4330 [ + + ]:GBC 30 : while (--nrows >= 0)
4331 : : {
4332 : : path = (Path *)
2679 tgl@sss.pgh.pa.us 4333 : 20 : create_group_result_path(root, grouped_rel,
4334 : 20 : grouped_rel->reltarget,
4335 : 20 : (List *) parse->havingQual);
109 rhaas@postgresql.org 4336 :GNC 20 : append.subpaths = lappend(append.subpaths, path);
4337 : : }
4338 : : path = (Path *)
2975 alvherre@alvh.no-ip. 4339 :GBC 10 : create_append_path(root,
4340 : : grouped_rel,
4341 : : append,
4342 : : NIL,
4343 : : NULL,
4344 : : 0,
4345 : : false,
4346 : : -1);
4347 : : }
4348 : : else
4349 : : {
4350 : : /* No grouping sets, or just one, so one output row */
4351 : : path = (Path *)
2679 tgl@sss.pgh.pa.us 4352 :CBC 25 : create_group_result_path(root, grouped_rel,
4353 : 25 : grouped_rel->reltarget,
4354 : 25 : (List *) parse->havingQual);
4355 : : }
4356 : :
2998 rhaas@postgresql.org 4357 : 35 : add_path(grouped_rel, path);
4358 : 35 : }
4359 : :
4360 : : /*
4361 : : * create_ordinary_grouping_paths
4362 : : *
4363 : : * Create grouping paths for the ordinary (that is, non-degenerate) case.
4364 : : *
4365 : : * We need to consider sorted and hashed aggregation in the same function,
4366 : : * because otherwise (1) it would be harder to throw an appropriate error
4367 : : * message if neither way works, and (2) we should not allow hashtable size
4368 : : * considerations to dissuade us from using hashing if sorting is not possible.
4369 : : *
4370 : : * *partially_grouped_rel_p will be set to the partially grouped rel which this
4371 : : * function creates, or to NULL if it doesn't create one.
4372 : : */
4373 : : static void
4374 : 36007 : create_ordinary_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
4375 : : RelOptInfo *grouped_rel,
4376 : : const AggClauseCosts *agg_costs,
4377 : : grouping_sets_data *gd,
4378 : : GroupPathExtraData *extra,
4379 : : RelOptInfo **partially_grouped_rel_p)
4380 : : {
2993 4381 : 36007 : RelOptInfo *partially_grouped_rel = NULL;
2991 4382 : 36007 : PartitionwiseAggregateType patype = PARTITIONWISE_AGGREGATE_NONE;
4383 : :
4384 : : /*
4385 : : * If this is the topmost grouping relation or if the parent relation is
4386 : : * doing some form of partitionwise aggregation, then we may be able to do
4387 : : * it at this level also. However, if the input relation is not
4388 : : * partitioned, partitionwise aggregate is impossible.
4389 : : */
4390 [ + + ]: 36007 : if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
2641 tgl@sss.pgh.pa.us 4391 [ + + + - : 2375 : IS_PARTITIONED_REL(input_rel))
+ + + - +
+ ]
4392 : : {
4393 : : /*
4394 : : * If this is the topmost relation or if the parent relation is doing
4395 : : * full partitionwise aggregation, then we can do full partitionwise
4396 : : * aggregation provided that the GROUP BY clause contains all of the
4397 : : * partitioning columns at this level and the collation used by GROUP
4398 : : * BY matches the partitioning collation. Otherwise, we can do at
4399 : : * most partial partitionwise aggregation. But if partial aggregation
4400 : : * is not supported in general then we can't use it for partitionwise
4401 : : * aggregation either.
4402 : : *
4403 : : * Check parse->groupClause not processed_groupClause, because it's
4404 : : * okay if some of the partitioning columns were proved redundant.
4405 : : */
2991 rhaas@postgresql.org 4406 [ + + + + ]: 1360 : if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
4407 : 640 : group_by_has_partkey(input_rel, extra->targetList,
4408 : 640 : root->parse->groupClause))
4409 : 404 : patype = PARTITIONWISE_AGGREGATE_FULL;
4410 [ + + ]: 316 : else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4411 : 281 : patype = PARTITIONWISE_AGGREGATE_PARTIAL;
4412 : : else
4413 : 35 : patype = PARTITIONWISE_AGGREGATE_NONE;
4414 : : }
4415 : :
4416 : : /*
4417 : : * Before generating paths for grouped_rel, we first generate any possible
4418 : : * partially grouped paths; that way, later code can easily consider both
4419 : : * parallel and non-parallel approaches to grouping.
4420 : : */
4421 [ + + ]: 36007 : if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
4422 : : {
4423 : : bool force_rel_creation;
4424 : :
4425 : : /*
4426 : : * If we're doing partitionwise aggregation at this level, force
4427 : : * creation of a partially_grouped_rel so we can add partitionwise
4428 : : * paths to it.
4429 : : */
4430 : 31818 : force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
4431 : :
4432 : : partially_grouped_rel =
2993 4433 : 31818 : create_partial_grouping_paths(root,
4434 : : grouped_rel,
4435 : : input_rel,
4436 : : gd,
4437 : : extra,
4438 : : force_rel_creation);
4439 : : }
4440 : :
4441 : : /* Set out parameter. */
2991 4442 : 36007 : *partially_grouped_rel_p = partially_grouped_rel;
4443 : :
4444 : : /* Apply partitionwise aggregation technique, if possible. */
4445 [ + + ]: 36007 : if (patype != PARTITIONWISE_AGGREGATE_NONE)
4446 : 685 : create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
4447 : : partially_grouped_rel, agg_costs,
4448 : : gd, patype, extra);
4449 : :
4450 : : /* If we are doing partial aggregation only, return. */
4451 [ + + ]: 36007 : if (extra->patype == PARTITIONWISE_AGGREGATE_PARTIAL)
4452 : : {
4453 [ - + ]: 713 : Assert(partially_grouped_rel);
4454 : :
4455 [ + - ]: 713 : if (partially_grouped_rel->pathlist)
4456 : 713 : set_cheapest(partially_grouped_rel);
4457 : :
4458 : 713 : return;
4459 : : }
4460 : :
4461 : : /* Gather any partially grouped partial paths. */
4462 [ + + + + ]: 35294 : if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
2993 4463 : 2324 : gather_grouping_paths(root, partially_grouped_rel);
4464 : :
4465 : : /* Now choose the best path(s) for partially_grouped_rel. */
234 rguo@postgresql.org 4466 [ + + + - ]:GNC 35294 : if (partially_grouped_rel && partially_grouped_rel->pathlist)
4467 : 2492 : set_cheapest(partially_grouped_rel);
4468 : :
4469 : : /* Build final grouping paths */
2993 rhaas@postgresql.org 4470 :CBC 35294 : add_paths_to_grouping_rel(root, input_rel, grouped_rel,
4471 : : partially_grouped_rel, agg_costs, gd,
4472 : : extra);
4473 : :
4474 : : /* Give a helpful error if we failed to find any implementation */
3046 4475 [ + + ]: 35294 : if (grouped_rel->pathlist == NIL)
4476 [ + - ]: 4 : ereport(ERROR,
4477 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4478 : : errmsg("could not implement GROUP BY"),
4479 : : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
4480 : :
4481 : : /*
4482 : : * If there is an FDW that's responsible for all baserels of the query,
4483 : : * let it consider adding ForeignPaths.
4484 : : */
4485 [ + + ]: 35290 : if (grouped_rel->fdwroutine &&
4486 [ + + ]: 170 : grouped_rel->fdwroutine->GetForeignUpperPaths)
4487 : 169 : grouped_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG,
4488 : : input_rel, grouped_rel,
4489 : : extra);
4490 : :
4491 : : /* Let extensions possibly add some more paths */
4492 [ - + ]: 35290 : if (create_upper_paths_hook)
3046 rhaas@postgresql.org 4493 :UBC 0 : (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
4494 : : input_rel, grouped_rel,
4495 : : extra);
4496 : : }
4497 : :
4498 : : /*
4499 : : * For a given input path, consider the possible ways of doing grouping sets on
4500 : : * it, by combinations of hashing and sorting. This can be called multiple
4501 : : * times, so it's important that it not scribble on input. No result is
4502 : : * returned, but any generated paths are added to grouped_rel.
4503 : : */
4504 : : static void
3046 rhaas@postgresql.org 4505 :CBC 1782 : consider_groupingsets_paths(PlannerInfo *root,
4506 : : RelOptInfo *grouped_rel,
4507 : : Path *path,
4508 : : bool is_sorted,
4509 : : bool can_hash,
4510 : : grouping_sets_data *gd,
4511 : : const AggClauseCosts *agg_costs,
4512 : : double dNumGroups)
4513 : : {
4514 : 1782 : Query *parse = root->parse;
1770 tgl@sss.pgh.pa.us 4515 : 1782 : Size hash_mem_limit = get_hash_memory_limit();
4516 : :
4517 : : /*
4518 : : * If we're not being offered sorted input, then only consider plans that
4519 : : * can be done entirely by hashing.
4520 : : *
4521 : : * We can hash everything if it looks like it'll fit in hash_mem. But if
4522 : : * the input is actually sorted despite not being advertised as such, we
4523 : : * prefer to make use of that in order to use less memory.
4524 : : *
4525 : : * If none of the grouping sets are sortable, then ignore the hash_mem
4526 : : * limit and generate a path anyway, since otherwise we'll just fail.
4527 : : */
3046 rhaas@postgresql.org 4528 [ + + ]: 1782 : if (!is_sorted)
4529 : : {
4530 : 807 : List *new_rollups = NIL;
4531 : 807 : RollupData *unhashed_rollup = NULL;
4532 : : List *sets_data;
4533 : 807 : List *empty_sets_data = NIL;
4534 : 807 : List *empty_sets = NIL;
4535 : : ListCell *lc;
4536 : 807 : ListCell *l_start = list_head(gd->rollups);
4537 : 807 : AggStrategy strat = AGG_HASHED;
4538 : : double hashsize;
4539 : 807 : double exclude_groups = 0.0;
4540 : :
4541 [ - + ]: 807 : Assert(can_hash);
4542 : :
4543 : : /*
4544 : : * If the input is coincidentally sorted usefully (which can happen
4545 : : * even if is_sorted is false, since that only means that our caller
4546 : : * has set up the sorting for us), then save some hashtable space by
4547 : : * making use of that. But we need to watch out for degenerate cases:
4548 : : *
4549 : : * 1) If there are any empty grouping sets, then group_pathkeys might
4550 : : * be NIL if all non-empty grouping sets are unsortable. In this case,
4551 : : * there will be a rollup containing only empty groups, and the
4552 : : * pathkeys_contained_in test is vacuously true; this is ok.
4553 : : *
4554 : : * XXX: the above relies on the fact that group_pathkeys is generated
4555 : : * from the first rollup. If we add the ability to consider multiple
4556 : : * sort orders for grouping input, this assumption might fail.
4557 : : *
4558 : : * 2) If there are no empty sets and only unsortable sets, then the
4559 : : * rollups list will be empty (and thus l_start == NULL), and
4560 : : * group_pathkeys will be NIL; we must ensure that the vacuously-true
4561 : : * pathkeys_contained_in test doesn't cause us to crash.
4562 : : */
2992 rhodiumtoad@postgres 4563 [ + + + + ]: 1609 : if (l_start != NULL &&
4564 : 802 : pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
4565 : : {
3046 rhaas@postgresql.org 4566 : 40 : unhashed_rollup = lfirst_node(RollupData, l_start);
4567 : 40 : exclude_groups = unhashed_rollup->numGroups;
2511 tgl@sss.pgh.pa.us 4568 : 40 : l_start = lnext(gd->rollups, l_start);
4569 : : }
4570 : :
2013 heikki.linnakangas@i 4571 : 807 : hashsize = estimate_hashagg_tablesize(root,
4572 : : path,
4573 : : agg_costs,
4574 : : dNumGroups - exclude_groups);
4575 : :
4576 : : /*
4577 : : * gd->rollups is empty if we have only unsortable columns to work
4578 : : * with. Override hash_mem in that case; otherwise, we'll rely on the
4579 : : * sorted-input case to generate usable mixed paths.
4580 : : */
1770 tgl@sss.pgh.pa.us 4581 [ + + + - ]: 807 : if (hashsize > hash_mem_limit && gd->rollups)
3046 rhaas@postgresql.org 4582 : 15 : return; /* nope, won't fit */
4583 : :
4584 : : /*
4585 : : * We need to burst the existing rollups list into individual grouping
4586 : : * sets and recompute a groupClause for each set.
4587 : : */
4588 : 792 : sets_data = list_copy(gd->unsortable_sets);
4589 : :
2511 tgl@sss.pgh.pa.us 4590 [ + + + + : 2013 : for_each_cell(lc, gd->rollups, l_start)
+ + ]
4591 : : {
3046 rhaas@postgresql.org 4592 : 1241 : RollupData *rollup = lfirst_node(RollupData, lc);
4593 : :
4594 : : /*
4595 : : * If we find an unhashable rollup that's not been skipped by the
4596 : : * "actually sorted" check above, we can't cope; we'd need sorted
4597 : : * input (with a different sort order) but we can't get that here.
4598 : : * So bail out; we'll get a valid path from the is_sorted case
4599 : : * instead.
4600 : : *
4601 : : * The mere presence of empty grouping sets doesn't make a rollup
4602 : : * unhashable (see preprocess_grouping_sets), we handle those
4603 : : * specially below.
4604 : : */
3351 rhodiumtoad@postgres 4605 [ + + ]: 1241 : if (!rollup->hashable)
4606 : 20 : return;
4607 : :
2483 tgl@sss.pgh.pa.us 4608 : 1221 : sets_data = list_concat(sets_data, rollup->gsets_data);
4609 : : }
3351 rhodiumtoad@postgres 4610 [ + - + + : 3053 : foreach(lc, sets_data)
+ + ]
4611 : : {
3189 tgl@sss.pgh.pa.us 4612 : 2281 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
3351 rhodiumtoad@postgres 4613 : 2281 : List *gset = gs->set;
4614 : : RollupData *rollup;
4615 : :
4616 [ + + ]: 2281 : if (gset == NIL)
4617 : : {
4618 : : /* Empty grouping sets can't be hashed. */
4619 : 445 : empty_sets_data = lappend(empty_sets_data, gs);
4620 : 445 : empty_sets = lappend(empty_sets, NIL);
4621 : : }
4622 : : else
4623 : : {
4624 : 1836 : rollup = makeNode(RollupData);
4625 : :
723 akorotkov@postgresql 4626 : 1836 : rollup->groupClause = preprocess_groupclause(root, gset);
3351 rhodiumtoad@postgres 4627 : 1836 : rollup->gsets_data = list_make1(gs);
4628 : 1836 : rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4629 : : rollup->gsets_data,
4630 : : gd->tleref_to_colnum_map);
4631 : 1836 : rollup->numGroups = gs->numGroups;
4632 : 1836 : rollup->hashable = true;
4633 : 1836 : rollup->is_hashed = true;
4634 : 1836 : new_rollups = lappend(new_rollups, rollup);
4635 : : }
4636 : : }
4637 : :
4638 : : /*
4639 : : * If we didn't find anything nonempty to hash, then bail. We'll
4640 : : * generate a path from the is_sorted case.
4641 : : */
4642 [ - + ]: 772 : if (new_rollups == NIL)
3351 rhodiumtoad@postgres 4643 :UBC 0 : return;
4644 : :
4645 : : /*
4646 : : * If there were empty grouping sets they should have been in the
4647 : : * first rollup.
4648 : : */
3351 rhodiumtoad@postgres 4649 [ + + - + ]:CBC 772 : Assert(!unhashed_rollup || !empty_sets);
4650 : :
4651 [ + + ]: 772 : if (unhashed_rollup)
4652 : : {
4653 : 40 : new_rollups = lappend(new_rollups, unhashed_rollup);
4654 : 40 : strat = AGG_MIXED;
4655 : : }
4656 [ + + ]: 732 : else if (empty_sets)
4657 : : {
4658 : 405 : RollupData *rollup = makeNode(RollupData);
4659 : :
4660 : 405 : rollup->groupClause = NIL;
4661 : 405 : rollup->gsets_data = empty_sets_data;
4662 : 405 : rollup->gsets = empty_sets;
4663 : 405 : rollup->numGroups = list_length(empty_sets);
4664 : 405 : rollup->hashable = false;
4665 : 405 : rollup->is_hashed = false;
4666 : 405 : new_rollups = lappend(new_rollups, rollup);
4667 : 405 : strat = AGG_MIXED;
4668 : : }
4669 : :
4670 : 772 : add_path(grouped_rel, (Path *)
4671 : 772 : create_groupingsets_path(root,
4672 : : grouped_rel,
4673 : : path,
4674 : 772 : (List *) parse->havingQual,
4675 : : strat,
4676 : : new_rollups,
4677 : : agg_costs));
4678 : 772 : return;
4679 : : }
4680 : :
4681 : : /*
4682 : : * If we have sorted input but nothing we can do with it, bail.
4683 : : */
1382 tgl@sss.pgh.pa.us 4684 [ - + ]: 975 : if (gd->rollups == NIL)
3351 rhodiumtoad@postgres 4685 :UBC 0 : return;
4686 : :
4687 : : /*
4688 : : * Given sorted input, we try and make two paths: one sorted and one mixed
4689 : : * sort/hash. (We need to try both because hashagg might be disabled, or
4690 : : * some columns might not be sortable.)
4691 : : *
4692 : : * can_hash is passed in as false if some obstacle elsewhere (such as
4693 : : * ordered aggs) means that we shouldn't consider hashing at all.
4694 : : */
3351 rhodiumtoad@postgres 4695 [ + + + - ]:CBC 975 : if (can_hash && gd->any_hashable)
4696 : : {
4697 : 896 : List *rollups = NIL;
4698 : 896 : List *hash_sets = list_copy(gd->unsortable_sets);
1770 tgl@sss.pgh.pa.us 4699 : 896 : double availspace = hash_mem_limit;
4700 : : ListCell *lc;
4701 : :
4702 : : /*
4703 : : * Account first for space needed for groups we can't sort at all.
4704 : : */
2013 heikki.linnakangas@i 4705 : 896 : availspace -= estimate_hashagg_tablesize(root,
4706 : : path,
4707 : : agg_costs,
4708 : : gd->dNumHashGroups);
4709 : :
3351 rhodiumtoad@postgres 4710 [ + - + + ]: 896 : if (availspace > 0 && list_length(gd->rollups) > 1)
4711 : : {
4712 : : double scale;
4713 : 501 : int num_rollups = list_length(gd->rollups);
4714 : : int k_capacity;
4715 : 501 : int *k_weights = palloc(num_rollups * sizeof(int));
4716 : 501 : Bitmapset *hash_items = NULL;
4717 : : int i;
4718 : :
4719 : : /*
4720 : : * We treat this as a knapsack problem: the knapsack capacity
4721 : : * represents hash_mem, the item weights are the estimated memory
4722 : : * usage of the hashtables needed to implement a single rollup,
4723 : : * and we really ought to use the cost saving as the item value;
4724 : : * however, currently the costs assigned to sort nodes don't
4725 : : * reflect the comparison costs well, and so we treat all items as
4726 : : * of equal value (each rollup we hash instead saves us one sort).
4727 : : *
4728 : : * To use the discrete knapsack, we need to scale the values to a
4729 : : * reasonably small bounded range. We choose to allow a 5% error
4730 : : * margin; we have no more than 4096 rollups in the worst possible
4731 : : * case, which with a 5% error margin will require a bit over 42MB
4732 : : * of workspace. (Anyone wanting to plan queries that complex had
4733 : : * better have the memory for it. In more reasonable cases, with
4734 : : * no more than a couple of dozen rollups, the memory usage will
4735 : : * be negligible.)
4736 : : *
4737 : : * k_capacity is naturally bounded, but we clamp the values for
4738 : : * scale and weight (below) to avoid overflows or underflows (or
4739 : : * uselessly trying to use a scale factor less than 1 byte).
4740 : : */
4741 [ + - ]: 501 : scale = Max(availspace / (20.0 * num_rollups), 1.0);
4742 : 501 : k_capacity = (int) floor(availspace / scale);
4743 : :
4744 : : /*
4745 : : * We leave the first rollup out of consideration since it's the
4746 : : * one that matches the input sort order. We assign indexes "i"
4747 : : * to only those entries considered for hashing; the second loop,
4748 : : * below, must use the same condition.
4749 : : */
4750 : 501 : i = 0;
2070 tgl@sss.pgh.pa.us 4751 [ + - + + : 1222 : for_each_from(lc, gd->rollups, 1)
+ + ]
4752 : : {
3189 4753 : 721 : RollupData *rollup = lfirst_node(RollupData, lc);
4754 : :
3351 rhodiumtoad@postgres 4755 [ + - ]: 721 : if (rollup->hashable)
4756 : : {
2013 heikki.linnakangas@i 4757 : 721 : double sz = estimate_hashagg_tablesize(root,
4758 : : path,
4759 : : agg_costs,
4760 : : rollup->numGroups);
4761 : :
4762 : : /*
4763 : : * If sz is enormous, but hash_mem (and hence scale) is
4764 : : * small, avoid integer overflow here.
4765 : : */
3351 rhodiumtoad@postgres 4766 [ + + ]: 721 : k_weights[i] = (int) Min(floor(sz / scale),
4767 : : k_capacity + 1.0);
4768 : 721 : ++i;
4769 : : }
4770 : : }
4771 : :
4772 : : /*
4773 : : * Apply knapsack algorithm; compute the set of items which
4774 : : * maximizes the value stored (in this case the number of sorts
4775 : : * saved) while keeping the total size (approximately) within
4776 : : * capacity.
4777 : : */
4778 [ + - ]: 501 : if (i > 0)
4779 : 501 : hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
4780 : :
4781 [ + - ]: 501 : if (!bms_is_empty(hash_items))
4782 : : {
4783 : 501 : rollups = list_make1(linitial(gd->rollups));
4784 : :
4785 : 501 : i = 0;
2070 tgl@sss.pgh.pa.us 4786 [ + - + + : 1222 : for_each_from(lc, gd->rollups, 1)
+ + ]
4787 : : {
3189 4788 : 721 : RollupData *rollup = lfirst_node(RollupData, lc);
4789 : :
3351 rhodiumtoad@postgres 4790 [ + - ]: 721 : if (rollup->hashable)
4791 : : {
4792 [ + + ]: 721 : if (bms_is_member(i, hash_items))
4793 : 691 : hash_sets = list_concat(hash_sets,
2483 tgl@sss.pgh.pa.us 4794 : 691 : rollup->gsets_data);
4795 : : else
3351 rhodiumtoad@postgres 4796 : 30 : rollups = lappend(rollups, rollup);
4797 : 721 : ++i;
4798 : : }
4799 : : else
3351 rhodiumtoad@postgres 4800 :UBC 0 : rollups = lappend(rollups, rollup);
4801 : : }
4802 : : }
4803 : : }
4804 : :
3351 rhodiumtoad@postgres 4805 [ + + + + ]:CBC 896 : if (!rollups && hash_sets)
4806 : 20 : rollups = list_copy(gd->rollups);
4807 : :
4808 [ + + + + : 1703 : foreach(lc, hash_sets)
+ + ]
4809 : : {
3189 tgl@sss.pgh.pa.us 4810 : 807 : GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
3351 rhodiumtoad@postgres 4811 : 807 : RollupData *rollup = makeNode(RollupData);
4812 : :
4813 [ - + ]: 807 : Assert(gs->set != NIL);
4814 : :
723 akorotkov@postgresql 4815 : 807 : rollup->groupClause = preprocess_groupclause(root, gs->set);
3351 rhodiumtoad@postgres 4816 : 807 : rollup->gsets_data = list_make1(gs);
4817 : 807 : rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
4818 : : rollup->gsets_data,
4819 : : gd->tleref_to_colnum_map);
4820 : 807 : rollup->numGroups = gs->numGroups;
4821 : 807 : rollup->hashable = true;
4822 : 807 : rollup->is_hashed = true;
4823 : 807 : rollups = lcons(rollup, rollups);
4824 : : }
4825 : :
4826 [ + + ]: 896 : if (rollups)
4827 : : {
4828 : 521 : add_path(grouped_rel, (Path *)
4829 : 521 : create_groupingsets_path(root,
4830 : : grouped_rel,
4831 : : path,
4832 : 521 : (List *) parse->havingQual,
4833 : : AGG_MIXED,
4834 : : rollups,
4835 : : agg_costs));
4836 : : }
4837 : : }
4838 : :
4839 : : /*
4840 : : * Now try the simple sorted case.
4841 : : */
4842 [ + + ]: 975 : if (!gd->unsortable_sets)
4843 : 951 : add_path(grouped_rel, (Path *)
4844 : 951 : create_groupingsets_path(root,
4845 : : grouped_rel,
4846 : : path,
4847 : 951 : (List *) parse->havingQual,
4848 : : AGG_SORTED,
4849 : : gd->rollups,
4850 : : agg_costs));
4851 : : }
4852 : :
4853 : : /*
4854 : : * create_window_paths
4855 : : *
4856 : : * Build a new upperrel containing Paths for window-function evaluation.
4857 : : *
4858 : : * input_rel: contains the source-data Paths
4859 : : * input_target: result of make_window_input_target
4860 : : * output_target: what the topmost WindowAggPath should return
4861 : : * wflists: result of find_window_functions
4862 : : * activeWindows: result of select_active_windows
4863 : : *
4864 : : * Note: all Paths in input_rel are expected to return input_target.
4865 : : */
4866 : : static RelOptInfo *
3736 tgl@sss.pgh.pa.us 4867 : 2232 : create_window_paths(PlannerInfo *root,
4868 : : RelOptInfo *input_rel,
4869 : : PathTarget *input_target,
4870 : : PathTarget *output_target,
4871 : : bool output_target_parallel_safe,
4872 : : WindowFuncLists *wflists,
4873 : : List *activeWindows)
4874 : : {
4875 : : RelOptInfo *window_rel;
4876 : : ListCell *lc;
4877 : :
4878 : : /* For now, do all work in the (WINDOW, NULL) upperrel */
4879 : 2232 : window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
4880 : :
4881 : : /*
4882 : : * If the input relation is not parallel-safe, then the window relation
4883 : : * can't be parallel-safe, either. Otherwise, we need to examine the
4884 : : * target list and active windows for non-parallel-safe constructs.
4885 : : */
3005 rhaas@postgresql.org 4886 [ + + - + : 2232 : if (input_rel->consider_parallel && output_target_parallel_safe &&
- - ]
3571 tgl@sss.pgh.pa.us 4887 :UBC 0 : is_parallel_safe(root, (Node *) activeWindows))
3620 rhaas@postgresql.org 4888 : 0 : window_rel->consider_parallel = true;
4889 : :
4890 : : /*
4891 : : * If the input rel belongs to a single FDW, so does the window rel.
4892 : : */
3620 tgl@sss.pgh.pa.us 4893 :CBC 2232 : window_rel->serverid = input_rel->serverid;
3606 4894 : 2232 : window_rel->userid = input_rel->userid;
4895 : 2232 : window_rel->useridiscurrent = input_rel->useridiscurrent;
3620 4896 : 2232 : window_rel->fdwroutine = input_rel->fdwroutine;
4897 : :
4898 : : /*
4899 : : * Consider computing window functions starting from the existing
4900 : : * cheapest-total path (which will likely require a sort) as well as any
4901 : : * existing paths that satisfy or partially satisfy root->window_pathkeys.
4902 : : */
3736 4903 [ + - + + : 4726 : foreach(lc, input_rel->pathlist)
+ + ]
4904 : : {
4905 : 2494 : Path *path = (Path *) lfirst(lc);
4906 : : int presorted_keys;
4907 : :
4908 [ + + + + ]: 2756 : if (path == input_rel->cheapest_total_path ||
2083 drowley@postgresql.o 4909 : 262 : pathkeys_count_contained_in(root->window_pathkeys, path->pathkeys,
4910 : 116 : &presorted_keys) ||
4911 [ + + ]: 116 : presorted_keys > 0)
3736 tgl@sss.pgh.pa.us 4912 : 2399 : create_one_window_path(root,
4913 : : window_rel,
4914 : : path,
4915 : : input_target,
4916 : : output_target,
4917 : : wflists,
4918 : : activeWindows);
4919 : : }
4920 : :
4921 : : /*
4922 : : * If there is an FDW that's responsible for all baserels of the query,
4923 : : * let it consider adding ForeignPaths.
4924 : : */
3620 4925 [ + + ]: 2232 : if (window_rel->fdwroutine &&
4926 [ + - ]: 6 : window_rel->fdwroutine->GetForeignUpperPaths)
4927 : 6 : window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
4928 : : input_rel, window_rel,
4929 : : NULL);
4930 : :
4931 : : /* Let extensions possibly add some more paths */
3700 4932 [ - + ]: 2232 : if (create_upper_paths_hook)
3700 tgl@sss.pgh.pa.us 4933 :UBC 0 : (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
4934 : : input_rel, window_rel, NULL);
4935 : :
4936 : : /* Now choose the best path(s) */
3736 tgl@sss.pgh.pa.us 4937 :CBC 2232 : set_cheapest(window_rel);
4938 : :
4939 : 2232 : return window_rel;
4940 : : }
4941 : :
4942 : : /*
4943 : : * Stack window-function implementation steps atop the given Path, and
4944 : : * add the result to window_rel.
4945 : : *
4946 : : * window_rel: upperrel to contain result
4947 : : * path: input Path to use (must return input_target)
4948 : : * input_target: result of make_window_input_target
4949 : : * output_target: what the topmost WindowAggPath should return
4950 : : * wflists: result of find_window_functions
4951 : : * activeWindows: result of select_active_windows
4952 : : */
4953 : : static void
4954 : 2399 : create_one_window_path(PlannerInfo *root,
4955 : : RelOptInfo *window_rel,
4956 : : Path *path,
4957 : : PathTarget *input_target,
4958 : : PathTarget *output_target,
4959 : : WindowFuncLists *wflists,
4960 : : List *activeWindows)
4961 : : {
4962 : : PathTarget *window_target;
4963 : : ListCell *l;
1513 drowley@postgresql.o 4964 : 2399 : List *topqual = NIL;
4965 : :
4966 : : /*
4967 : : * Since each window clause could require a different sort order, we stack
4968 : : * up a WindowAgg node for each clause, with sort steps between them as
4969 : : * needed. (We assume that select_active_windows chose a good order for
4970 : : * executing the clauses in.)
4971 : : *
4972 : : * input_target should contain all Vars and Aggs needed for the result.
4973 : : * (In some cases we wouldn't need to propagate all of these all the way
4974 : : * to the top, since they might only be needed as inputs to WindowFuncs.
4975 : : * It's probably not worth trying to optimize that though.) It must also
4976 : : * contain all window partitioning and sorting expressions, to ensure
4977 : : * they're computed only once at the bottom of the stack (that's critical
4978 : : * for volatile functions). As we climb up the stack, we'll add outputs
4979 : : * for the WindowFuncs computed at each level.
4980 : : */
3734 tgl@sss.pgh.pa.us 4981 : 2399 : window_target = input_target;
4982 : :
3736 4983 [ + - + + : 4953 : foreach(l, activeWindows)
+ + ]
4984 : : {
3189 4985 : 2554 : WindowClause *wc = lfirst_node(WindowClause, l);
4986 : : List *window_pathkeys;
755 drowley@postgresql.o 4987 : 2554 : List *runcondition = NIL;
4988 : : int presorted_keys;
4989 : : bool is_sorted;
4990 : : bool topwindow;
4991 : : ListCell *lc2;
4992 : :
3736 tgl@sss.pgh.pa.us 4993 : 2554 : window_pathkeys = make_pathkeys_for_window(root,
4994 : : wc,
4995 : : root->processed_tlist);
4996 : :
2083 drowley@postgresql.o 4997 : 2554 : is_sorted = pathkeys_count_contained_in(window_pathkeys,
4998 : : path->pathkeys,
4999 : : &presorted_keys);
5000 : :
5001 : : /* Sort if necessary */
5002 [ + + ]: 2554 : if (!is_sorted)
5003 : : {
5004 : : /*
5005 : : * No presorted keys or incremental sort disabled, just perform a
5006 : : * complete sort.
5007 : : */
5008 [ + + - + ]: 1841 : if (presorted_keys == 0 || !enable_incremental_sort)
5009 : 1790 : path = (Path *) create_sort_path(root, window_rel,
5010 : : path,
5011 : : window_pathkeys,
5012 : : -1.0);
5013 : : else
5014 : : {
5015 : : /*
5016 : : * Since we have presorted keys and incremental sort is
5017 : : * enabled, just use incremental sort.
5018 : : */
5019 : 51 : path = (Path *) create_incremental_sort_path(root,
5020 : : window_rel,
5021 : : path,
5022 : : window_pathkeys,
5023 : : presorted_keys,
5024 : : -1.0);
5025 : : }
5026 : : }
5027 : :
2511 tgl@sss.pgh.pa.us 5028 [ + + ]: 2554 : if (lnext(activeWindows, l))
5029 : : {
5030 : : /*
5031 : : * Add the current WindowFuncs to the output target for this
5032 : : * intermediate WindowAggPath. We must copy window_target to
5033 : : * avoid changing the previous path's target.
5034 : : *
5035 : : * Note: a WindowFunc adds nothing to the target's eval costs; but
5036 : : * we do need to account for the increase in tlist width.
5037 : : */
893 5038 : 155 : int64 tuple_width = window_target->width;
5039 : :
3734 5040 : 155 : window_target = copy_pathtarget(window_target);
5041 [ + - + + : 370 : foreach(lc2, wflists->windowFuncs[wc->winref])
+ + ]
5042 : : {
3337 5043 : 215 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
5044 : :
3734 5045 : 215 : add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
893 5046 : 215 : tuple_width += get_typavgwidth(wfunc->wintype, -1);
5047 : : }
5048 : 155 : window_target->width = clamp_width_est(tuple_width);
5049 : : }
5050 : : else
5051 : : {
5052 : : /* Install the goal target in the topmost WindowAgg */
3734 5053 : 2399 : window_target = output_target;
5054 : : }
5055 : :
5056 : : /* mark the final item in the list as the top-level window */
1513 drowley@postgresql.o 5057 : 2554 : topwindow = foreach_current_index(l) == list_length(activeWindows) - 1;
5058 : :
5059 : : /*
5060 : : * Collect the WindowFuncRunConditions from each WindowFunc and
5061 : : * convert them into OpExprs
5062 : : */
755 5063 [ + - + + : 5841 : foreach(lc2, wflists->windowFuncs[wc->winref])
+ + ]
5064 : : {
5065 : : ListCell *lc3;
5066 : 3287 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
5067 : :
5068 [ + + + + : 3437 : foreach(lc3, wfunc->runCondition)
+ + ]
5069 : : {
5070 : : WindowFuncRunCondition *wfuncrc =
5071 : 150 : lfirst_node(WindowFuncRunCondition, lc3);
5072 : : Expr *opexpr;
5073 : : Expr *leftop;
5074 : : Expr *rightop;
5075 : :
5076 [ + + ]: 150 : if (wfuncrc->wfunc_left)
5077 : : {
5078 : 135 : leftop = (Expr *) copyObject(wfunc);
5079 : 135 : rightop = copyObject(wfuncrc->arg);
5080 : : }
5081 : : else
5082 : : {
5083 : 15 : leftop = copyObject(wfuncrc->arg);
5084 : 15 : rightop = (Expr *) copyObject(wfunc);
5085 : : }
5086 : :
5087 : 150 : opexpr = make_opclause(wfuncrc->opno,
5088 : : BOOLOID,
5089 : : false,
5090 : : leftop,
5091 : : rightop,
5092 : : InvalidOid,
5093 : : wfuncrc->inputcollid);
5094 : :
5095 : 150 : runcondition = lappend(runcondition, opexpr);
5096 : :
5097 [ + + ]: 150 : if (!topwindow)
5098 : 20 : topqual = lappend(topqual, opexpr);
5099 : : }
5100 : : }
5101 : :
5102 : : path = (Path *)
3734 tgl@sss.pgh.pa.us 5103 [ + + ]: 2554 : create_windowagg_path(root, window_rel, path, window_target,
3736 5104 : 2554 : wflists->windowFuncs[wc->winref],
5105 : : runcondition, wc,
5106 : : topwindow ? topqual : NIL, topwindow);
5107 : : }
5108 : :
5109 : 2399 : add_path(window_rel, path);
7720 5110 : 2399 : }
5111 : :
5112 : : /*
5113 : : * create_distinct_paths
5114 : : *
5115 : : * Build a new upperrel containing Paths for SELECT DISTINCT evaluation.
5116 : : *
5117 : : * input_rel: contains the source-data Paths
5118 : : * target: the pathtarget for the result Paths to compute
5119 : : *
5120 : : * Note: input paths should already compute the desired pathtarget, since
5121 : : * Sort/Unique won't project anything.
5122 : : */
5123 : : static RelOptInfo *
843 drowley@postgresql.o 5124 : 1967 : create_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
5125 : : PathTarget *target)
5126 : : {
5127 : : RelOptInfo *distinct_rel;
5128 : :
5129 : : /* For now, do all work in the (DISTINCT, NULL) upperrel */
3736 tgl@sss.pgh.pa.us 5130 : 1967 : distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
5131 : :
5132 : : /*
5133 : : * We don't compute anything at this level, so distinct_rel will be
5134 : : * parallel-safe if the input rel is parallel-safe. In particular, if
5135 : : * there is a DISTINCT ON (...) clause, any path for the input_rel will
5136 : : * output those expressions, and will not be parallel-safe unless those
5137 : : * expressions are parallel-safe.
5138 : : */
3620 rhaas@postgresql.org 5139 : 1967 : distinct_rel->consider_parallel = input_rel->consider_parallel;
5140 : :
5141 : : /*
5142 : : * If the input rel belongs to a single FDW, so does the distinct_rel.
5143 : : */
tgl@sss.pgh.pa.us 5144 : 1967 : distinct_rel->serverid = input_rel->serverid;
3606 5145 : 1967 : distinct_rel->userid = input_rel->userid;
5146 : 1967 : distinct_rel->useridiscurrent = input_rel->useridiscurrent;
3620 5147 : 1967 : distinct_rel->fdwroutine = input_rel->fdwroutine;
5148 : :
5149 : : /* build distinct paths based on input_rel's pathlist */
1742 drowley@postgresql.o 5150 : 1967 : create_final_distinct_paths(root, input_rel, distinct_rel);
5151 : :
5152 : : /* now build distinct paths based on input_rel's partial_pathlist */
843 5153 : 1967 : create_partial_distinct_paths(root, input_rel, distinct_rel, target);
5154 : :
5155 : : /* Give a helpful error if we failed to create any paths */
1742 5156 [ - + ]: 1967 : if (distinct_rel->pathlist == NIL)
1742 drowley@postgresql.o 5157 [ # # ]:UBC 0 : ereport(ERROR,
5158 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5159 : : errmsg("could not implement DISTINCT"),
5160 : : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
5161 : :
5162 : : /*
5163 : : * If there is an FDW that's responsible for all baserels of the query,
5164 : : * let it consider adding ForeignPaths.
5165 : : */
1742 drowley@postgresql.o 5166 [ + + ]:CBC 1967 : if (distinct_rel->fdwroutine &&
5167 [ + - ]: 8 : distinct_rel->fdwroutine->GetForeignUpperPaths)
5168 : 8 : distinct_rel->fdwroutine->GetForeignUpperPaths(root,
5169 : : UPPERREL_DISTINCT,
5170 : : input_rel,
5171 : : distinct_rel,
5172 : : NULL);
5173 : :
5174 : : /* Let extensions possibly add some more paths */
5175 [ - + ]: 1967 : if (create_upper_paths_hook)
1742 drowley@postgresql.o 5176 :UBC 0 : (*create_upper_paths_hook) (root, UPPERREL_DISTINCT, input_rel,
5177 : : distinct_rel, NULL);
5178 : :
5179 : : /* Now choose the best path(s) */
1742 drowley@postgresql.o 5180 :CBC 1967 : set_cheapest(distinct_rel);
5181 : :
5182 : 1967 : return distinct_rel;
5183 : : }
5184 : :
5185 : : /*
5186 : : * create_partial_distinct_paths
5187 : : *
5188 : : * Process 'input_rel' partial paths and add unique/aggregate paths to the
5189 : : * UPPERREL_PARTIAL_DISTINCT rel. For paths created, add Gather/GatherMerge
5190 : : * paths on top and add a final unique/aggregate path to remove any duplicate
5191 : : * produced from combining rows from parallel workers.
5192 : : */
5193 : : static void
5194 : 1967 : create_partial_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
5195 : : RelOptInfo *final_distinct_rel,
5196 : : PathTarget *target)
5197 : : {
5198 : : RelOptInfo *partial_distinct_rel;
5199 : : Query *parse;
5200 : : List *distinctExprs;
5201 : : double numDistinctRows;
5202 : : Path *cheapest_partial_path;
5203 : : ListCell *lc;
5204 : :
5205 : : /* nothing to do when there are no partial paths in the input rel */
5206 [ + + + + ]: 1967 : if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
5207 : 1877 : return;
5208 : :
5209 : 90 : parse = root->parse;
5210 : :
5211 : : /* can't do parallel DISTINCT ON */
5212 [ - + ]: 90 : if (parse->hasDistinctOn)
1742 drowley@postgresql.o 5213 :UBC 0 : return;
5214 : :
1742 drowley@postgresql.o 5215 :CBC 90 : partial_distinct_rel = fetch_upper_rel(root, UPPERREL_PARTIAL_DISTINCT,
5216 : : NULL);
843 5217 : 90 : partial_distinct_rel->reltarget = target;
1742 5218 : 90 : partial_distinct_rel->consider_parallel = input_rel->consider_parallel;
5219 : :
5220 : : /*
5221 : : * If input_rel belongs to a single FDW, so does the partial_distinct_rel.
5222 : : */
5223 : 90 : partial_distinct_rel->serverid = input_rel->serverid;
5224 : 90 : partial_distinct_rel->userid = input_rel->userid;
5225 : 90 : partial_distinct_rel->useridiscurrent = input_rel->useridiscurrent;
5226 : 90 : partial_distinct_rel->fdwroutine = input_rel->fdwroutine;
5227 : :
5228 : 90 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
5229 : :
1228 tgl@sss.pgh.pa.us 5230 : 90 : distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
5231 : : parse->targetList);
5232 : :
5233 : : /* estimate how many distinct rows we'll get from each worker */
1742 drowley@postgresql.o 5234 : 90 : numDistinctRows = estimate_num_groups(root, distinctExprs,
5235 : : cheapest_partial_path->rows,
5236 : : NULL, NULL);
5237 : :
5238 : : /*
5239 : : * Try sorting the cheapest path and incrementally sorting any paths with
5240 : : * presorted keys and put a unique paths atop of those. We'll also
5241 : : * attempt to reorder the required pathkeys to match the input path's
5242 : : * pathkeys as much as possible, in hopes of avoiding a possible need to
5243 : : * re-sort.
5244 : : */
1228 tgl@sss.pgh.pa.us 5245 [ + - ]: 90 : if (grouping_is_sortable(root->processed_distinctClause))
5246 : : {
1742 drowley@postgresql.o 5247 [ + - + + : 193 : foreach(lc, input_rel->partial_pathlist)
+ + ]
5248 : : {
1235 5249 : 103 : Path *input_path = (Path *) lfirst(lc);
5250 : : Path *sorted_path;
550 rguo@postgresql.org 5251 : 103 : List *useful_pathkeys_list = NIL;
5252 : :
5253 : : useful_pathkeys_list =
5254 : 103 : get_useful_pathkeys_for_distinct(root,
5255 : : root->distinct_pathkeys,
5256 : : input_path->pathkeys);
5257 [ - + ]: 103 : Assert(list_length(useful_pathkeys_list) > 0);
5258 : :
5259 [ + - + + : 319 : foreach_node(List, useful_pathkeys, useful_pathkeys_list)
+ + ]
5260 : : {
5261 : 113 : sorted_path = make_ordered_path(root,
5262 : : partial_distinct_rel,
5263 : : input_path,
5264 : : cheapest_partial_path,
5265 : : useful_pathkeys,
5266 : : -1.0);
5267 : :
5268 [ + + ]: 113 : if (sorted_path == NULL)
1235 drowley@postgresql.o 5269 : 8 : continue;
5270 : :
5271 : : /*
5272 : : * An empty distinct_pathkeys means all tuples have the same
5273 : : * value for the DISTINCT clause. See
5274 : : * create_final_distinct_paths()
5275 : : */
550 rguo@postgresql.org 5276 [ + + ]: 105 : if (root->distinct_pathkeys == NIL)
5277 : : {
5278 : : Node *limitCount;
5279 : :
5280 : 5 : limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5281 : : sizeof(int64),
5282 : : Int64GetDatum(1), false,
5283 : : true);
5284 : :
5285 : : /*
5286 : : * Apply a LimitPath onto the partial path to restrict the
5287 : : * tuples from each worker to 1.
5288 : : * create_final_distinct_paths will need to apply an
5289 : : * additional LimitPath to restrict this to a single row
5290 : : * after the Gather node. If the query already has a
5291 : : * LIMIT clause, then we could end up with three Limit
5292 : : * nodes in the final plan. Consolidating the top two of
5293 : : * these could be done, but does not seem worth troubling
5294 : : * over.
5295 : : */
5296 : 5 : add_partial_path(partial_distinct_rel, (Path *)
5297 : 5 : create_limit_path(root, partial_distinct_rel,
5298 : : sorted_path,
5299 : : NULL,
5300 : : limitCount,
5301 : : LIMIT_OPTION_COUNT,
5302 : : 0, 1));
5303 : : }
5304 : : else
5305 : : {
5306 : 100 : add_partial_path(partial_distinct_rel, (Path *)
284 rguo@postgresql.org 5307 :GNC 100 : create_unique_path(root, partial_distinct_rel,
5308 : : sorted_path,
5309 : 100 : list_length(root->distinct_pathkeys),
5310 : : numDistinctRows));
5311 : : }
5312 : : }
5313 : : }
5314 : : }
5315 : :
5316 : : /*
5317 : : * Now try hash aggregate paths, if enabled and hashing is possible. Since
5318 : : * we're not on the hook to ensure we do our best to create at least one
5319 : : * path here, we treat enable_hashagg as a hard off-switch rather than the
5320 : : * slightly softer variant in create_final_distinct_paths.
5321 : : */
1228 tgl@sss.pgh.pa.us 5322 [ + + + - ]:CBC 90 : if (enable_hashagg && grouping_is_hashable(root->processed_distinctClause))
5323 : : {
1742 drowley@postgresql.o 5324 : 65 : add_partial_path(partial_distinct_rel, (Path *)
5325 : 65 : create_agg_path(root,
5326 : : partial_distinct_rel,
5327 : : cheapest_partial_path,
5328 : : cheapest_partial_path->pathtarget,
5329 : : AGG_HASHED,
5330 : : AGGSPLIT_SIMPLE,
5331 : : root->processed_distinctClause,
5332 : : NIL,
5333 : : NULL,
5334 : : numDistinctRows));
5335 : : }
5336 : :
5337 : : /*
5338 : : * If there is an FDW that's responsible for all baserels of the query,
5339 : : * let it consider adding ForeignPaths.
5340 : : */
5341 [ - + ]: 90 : if (partial_distinct_rel->fdwroutine &&
1742 drowley@postgresql.o 5342 [ # # ]:UBC 0 : partial_distinct_rel->fdwroutine->GetForeignUpperPaths)
5343 : 0 : partial_distinct_rel->fdwroutine->GetForeignUpperPaths(root,
5344 : : UPPERREL_PARTIAL_DISTINCT,
5345 : : input_rel,
5346 : : partial_distinct_rel,
5347 : : NULL);
5348 : :
5349 : : /* Let extensions possibly add some more partial paths */
1742 drowley@postgresql.o 5350 [ - + ]:CBC 90 : if (create_upper_paths_hook)
1742 drowley@postgresql.o 5351 :UBC 0 : (*create_upper_paths_hook) (root, UPPERREL_PARTIAL_DISTINCT,
5352 : : input_rel, partial_distinct_rel, NULL);
5353 : :
1742 drowley@postgresql.o 5354 [ + - ]:CBC 90 : if (partial_distinct_rel->partial_pathlist != NIL)
5355 : : {
847 5356 : 90 : generate_useful_gather_paths(root, partial_distinct_rel, true);
1742 5357 : 90 : set_cheapest(partial_distinct_rel);
5358 : :
5359 : : /*
5360 : : * Finally, create paths to distinctify the final result. This step
5361 : : * is needed to remove any duplicates due to combining rows from
5362 : : * parallel workers.
5363 : : */
5364 : 90 : create_final_distinct_paths(root, partial_distinct_rel,
5365 : : final_distinct_rel);
5366 : : }
5367 : : }
5368 : :
5369 : : /*
5370 : : * create_final_distinct_paths
5371 : : * Create distinct paths in 'distinct_rel' based on 'input_rel' pathlist
5372 : : *
5373 : : * input_rel: contains the source-data paths
5374 : : * distinct_rel: destination relation for storing created paths
5375 : : */
5376 : : static RelOptInfo *
5377 : 2057 : create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel,
5378 : : RelOptInfo *distinct_rel)
5379 : : {
5380 : 2057 : Query *parse = root->parse;
5381 : 2057 : Path *cheapest_input_path = input_rel->cheapest_total_path;
5382 : : double numDistinctRows;
5383 : : bool allow_hash;
5384 : :
5385 : : /* Estimate number of distinct rows there will be */
3736 tgl@sss.pgh.pa.us 5386 [ + + + - : 2057 : if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
+ + ]
5387 [ - + ]: 1998 : root->hasHavingQual)
5388 : : {
5389 : : /*
5390 : : * If there was grouping or aggregation, use the number of input rows
5391 : : * as the estimated number of DISTINCT rows (ie, assume the input is
5392 : : * already mostly unique).
5393 : : */
5394 : 59 : numDistinctRows = cheapest_input_path->rows;
5395 : : }
5396 : : else
5397 : : {
5398 : : /*
5399 : : * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
5400 : : */
5401 : : List *distinctExprs;
5402 : :
1228 5403 : 1998 : distinctExprs = get_sortgrouplist_exprs(root->processed_distinctClause,
5404 : : parse->targetList);
3736 5405 : 1998 : numDistinctRows = estimate_num_groups(root, distinctExprs,
5406 : : cheapest_input_path->rows,
5407 : : NULL, NULL);
5408 : : }
5409 : :
5410 : : /*
5411 : : * Consider sort-based implementations of DISTINCT, if possible.
5412 : : */
1228 5413 [ + + ]: 2057 : if (grouping_is_sortable(root->processed_distinctClause))
5414 : : {
5415 : : /*
5416 : : * Firstly, if we have any adequately-presorted paths, just stick a
5417 : : * Unique node on those. We also, consider doing an explicit sort of
5418 : : * the cheapest input path and Unique'ing that. If any paths have
5419 : : * presorted keys then we'll create an incremental sort atop of those
5420 : : * before adding a unique node on the top. We'll also attempt to
5421 : : * reorder the required pathkeys to match the input path's pathkeys as
5422 : : * much as possible, in hopes of avoiding a possible need to re-sort.
5423 : : *
5424 : : * When we have DISTINCT ON, we must sort by the more rigorous of
5425 : : * DISTINCT and ORDER BY, else it won't have the desired behavior.
5426 : : * Also, if we do have to do an explicit sort, we might as well use
5427 : : * the more rigorous ordering to avoid a second sort later. (Note
5428 : : * that the parser will have ensured that one clause is a prefix of
5429 : : * the other.)
5430 : : */
5431 : : List *needed_pathkeys;
5432 : : ListCell *lc;
1235 drowley@postgresql.o 5433 [ + + ]: 2052 : double limittuples = root->distinct_pathkeys == NIL ? 1.0 : -1.0;
5434 : :
3736 tgl@sss.pgh.pa.us 5435 [ + + + + ]: 2238 : if (parse->hasDistinctOn &&
5436 : 186 : list_length(root->distinct_pathkeys) <
5437 : 186 : list_length(root->sort_pathkeys))
5438 : 53 : needed_pathkeys = root->sort_pathkeys;
5439 : : else
5440 : 1999 : needed_pathkeys = root->distinct_pathkeys;
5441 : :
5442 [ + - + + : 5483 : foreach(lc, input_rel->pathlist)
+ + ]
5443 : : {
1235 drowley@postgresql.o 5444 : 3431 : Path *input_path = (Path *) lfirst(lc);
5445 : : Path *sorted_path;
550 rguo@postgresql.org 5446 : 3431 : List *useful_pathkeys_list = NIL;
5447 : :
5448 : : useful_pathkeys_list =
5449 : 3431 : get_useful_pathkeys_for_distinct(root,
5450 : : needed_pathkeys,
5451 : : input_path->pathkeys);
5452 [ - + ]: 3431 : Assert(list_length(useful_pathkeys_list) > 0);
5453 : :
5454 [ + - + + : 10793 : foreach_node(List, useful_pathkeys, useful_pathkeys_list)
+ + ]
5455 : : {
5456 : 3931 : sorted_path = make_ordered_path(root,
5457 : : distinct_rel,
5458 : : input_path,
5459 : : cheapest_input_path,
5460 : : useful_pathkeys,
5461 : : limittuples);
5462 : :
5463 [ + + ]: 3931 : if (sorted_path == NULL)
1235 drowley@postgresql.o 5464 : 531 : continue;
5465 : :
5466 : : /*
5467 : : * distinct_pathkeys may have become empty if all of the
5468 : : * pathkeys were determined to be redundant. If all of the
5469 : : * pathkeys are redundant then each DISTINCT target must only
5470 : : * allow a single value, therefore all resulting tuples must
5471 : : * be identical (or at least indistinguishable by an equality
5472 : : * check). We can uniquify these tuples simply by just taking
5473 : : * the first tuple. All we do here is add a path to do "LIMIT
5474 : : * 1" atop of 'sorted_path'. When doing a DISTINCT ON we may
5475 : : * still have a non-NIL sort_pathkeys list, so we must still
5476 : : * only do this with paths which are correctly sorted by
5477 : : * sort_pathkeys.
5478 : : */
550 rguo@postgresql.org 5479 [ + + ]: 3400 : if (root->distinct_pathkeys == NIL)
5480 : : {
5481 : : Node *limitCount;
5482 : :
5483 : 96 : limitCount = (Node *) makeConst(INT8OID, -1, InvalidOid,
5484 : : sizeof(int64),
5485 : : Int64GetDatum(1), false,
5486 : : true);
5487 : :
5488 : : /*
5489 : : * If the query already has a LIMIT clause, then we could
5490 : : * end up with a duplicate LimitPath in the final plan.
5491 : : * That does not seem worth troubling over too much.
5492 : : */
5493 : 96 : add_path(distinct_rel, (Path *)
5494 : 96 : create_limit_path(root, distinct_rel, sorted_path,
5495 : : NULL, limitCount,
5496 : : LIMIT_OPTION_COUNT, 0, 1));
5497 : : }
5498 : : else
5499 : : {
5500 : 3304 : add_path(distinct_rel, (Path *)
284 rguo@postgresql.org 5501 :GNC 3304 : create_unique_path(root, distinct_rel,
5502 : : sorted_path,
5503 : 3304 : list_length(root->distinct_pathkeys),
5504 : : numDistinctRows));
5505 : : }
5506 : : }
5507 : : }
5508 : : }
5509 : :
5510 : : /*
5511 : : * Consider hash-based implementations of DISTINCT, if possible.
5512 : : *
5513 : : * If we were not able to make any other types of path, we *must* hash or
5514 : : * die trying. If we do have other choices, there are two things that
5515 : : * should prevent selection of hashing: if the query uses DISTINCT ON
5516 : : * (because it won't really have the expected behavior if we hash), or if
5517 : : * enable_hashagg is off.
5518 : : *
5519 : : * Note: grouping_is_hashable() is much more expensive to check than the
5520 : : * other gating conditions, so we want to do it last.
5521 : : */
3736 tgl@sss.pgh.pa.us 5522 [ + + ]:CBC 2057 : if (distinct_rel->pathlist == NIL)
5523 : 5 : allow_hash = true; /* we have no alternatives */
5524 [ + + + + ]: 2052 : else if (parse->hasDistinctOn || !enable_hashagg)
5525 : 311 : allow_hash = false; /* policy-based decision not to hash */
5526 : : else
2133 pg@bowt.ie 5527 : 1741 : allow_hash = true; /* default */
5528 : :
1228 tgl@sss.pgh.pa.us 5529 [ + + + - ]: 2057 : if (allow_hash && grouping_is_hashable(root->processed_distinctClause))
5530 : : {
5531 : : /* Generate hashed aggregate path --- no sort needed */
3736 5532 : 1746 : add_path(distinct_rel, (Path *)
5533 : 1746 : create_agg_path(root,
5534 : : distinct_rel,
5535 : : cheapest_input_path,
5536 : : cheapest_input_path->pathtarget,
5537 : : AGG_HASHED,
5538 : : AGGSPLIT_SIMPLE,
5539 : : root->processed_distinctClause,
5540 : : NIL,
5541 : : NULL,
5542 : : numDistinctRows));
5543 : : }
5544 : :
5545 : 2057 : return distinct_rel;
5546 : : }
5547 : :
5548 : : /*
5549 : : * get_useful_pathkeys_for_distinct
5550 : : * Get useful orderings of pathkeys for distinctClause by reordering
5551 : : * 'needed_pathkeys' to match the given 'path_pathkeys' as much as possible.
5552 : : *
5553 : : * This returns a list of pathkeys that can be useful for DISTINCT or DISTINCT
5554 : : * ON clause. For convenience, it always includes the given 'needed_pathkeys'.
5555 : : */
5556 : : static List *
550 rguo@postgresql.org 5557 : 3534 : get_useful_pathkeys_for_distinct(PlannerInfo *root, List *needed_pathkeys,
5558 : : List *path_pathkeys)
5559 : : {
5560 : 3534 : List *useful_pathkeys_list = NIL;
5561 : 3534 : List *useful_pathkeys = NIL;
5562 : :
5563 : : /* always include the given 'needed_pathkeys' */
5564 : 3534 : useful_pathkeys_list = lappend(useful_pathkeys_list,
5565 : : needed_pathkeys);
5566 : :
5567 [ - + ]: 3534 : if (!enable_distinct_reordering)
550 rguo@postgresql.org 5568 :UBC 0 : return useful_pathkeys_list;
5569 : :
5570 : : /*
5571 : : * Scan the given 'path_pathkeys' and construct a list of PathKey nodes
5572 : : * that match 'needed_pathkeys', but only up to the longest matching
5573 : : * prefix.
5574 : : *
5575 : : * When we have DISTINCT ON, we must ensure that the resulting pathkey
5576 : : * list matches initial distinctClause pathkeys; otherwise, it won't have
5577 : : * the desired behavior.
5578 : : */
550 rguo@postgresql.org 5579 [ + + + + :CBC 8811 : foreach_node(PathKey, pathkey, path_pathkeys)
+ + ]
5580 : : {
5581 : : /*
5582 : : * The PathKey nodes are canonical, so they can be checked for
5583 : : * equality by simple pointer comparison.
5584 : : */
5585 [ + + ]: 1765 : if (!list_member_ptr(needed_pathkeys, pathkey))
5586 : 7 : break;
5587 [ + + ]: 1758 : if (root->parse->hasDistinctOn &&
5588 [ + + ]: 138 : !list_member_ptr(root->distinct_pathkeys, pathkey))
5589 : 15 : break;
5590 : :
5591 : 1743 : useful_pathkeys = lappend(useful_pathkeys, pathkey);
5592 : : }
5593 : :
5594 : : /* If no match at all, no point in reordering needed_pathkeys */
5595 [ + + ]: 3534 : if (useful_pathkeys == NIL)
5596 : 2019 : return useful_pathkeys_list;
5597 : :
5598 : : /*
5599 : : * If not full match, the resulting pathkey list is not useful without
5600 : : * incremental sort.
5601 : : */
5602 [ + + ]: 1515 : if (list_length(useful_pathkeys) < list_length(needed_pathkeys) &&
5603 [ + + ]: 923 : !enable_incremental_sort)
5604 : 48 : return useful_pathkeys_list;
5605 : :
5606 : : /* Append the remaining PathKey nodes in needed_pathkeys */
5607 : 1467 : useful_pathkeys = list_concat_unique_ptr(useful_pathkeys,
5608 : : needed_pathkeys);
5609 : :
5610 : : /*
5611 : : * If the resulting pathkey list is the same as the 'needed_pathkeys',
5612 : : * just drop it.
5613 : : */
5614 [ + + ]: 1467 : if (compare_pathkeys(needed_pathkeys,
5615 : : useful_pathkeys) == PATHKEYS_EQUAL)
5616 : 957 : return useful_pathkeys_list;
5617 : :
5618 : 510 : useful_pathkeys_list = lappend(useful_pathkeys_list,
5619 : : useful_pathkeys);
5620 : :
5621 : 510 : return useful_pathkeys_list;
5622 : : }
5623 : :
5624 : : /*
5625 : : * create_ordered_paths
5626 : : *
5627 : : * Build a new upperrel containing Paths for ORDER BY evaluation.
5628 : : *
5629 : : * All paths in the result must satisfy the ORDER BY ordering.
5630 : : * The only new paths we need consider are an explicit full sort
5631 : : * and incremental sort on the cheapest-total existing path.
5632 : : *
5633 : : * input_rel: contains the source-data Paths
5634 : : * target: the output tlist the result Paths must emit
5635 : : * limit_tuples: estimated bound on the number of output tuples,
5636 : : * or -1 if no LIMIT or couldn't estimate
5637 : : *
5638 : : * XXX This only looks at sort_pathkeys. I wonder if it needs to look at the
5639 : : * other pathkeys (grouping, ...) like generate_useful_gather_paths.
5640 : : */
5641 : : static RelOptInfo *
3736 tgl@sss.pgh.pa.us 5642 : 62200 : create_ordered_paths(PlannerInfo *root,
5643 : : RelOptInfo *input_rel,
5644 : : PathTarget *target,
5645 : : bool target_parallel_safe,
5646 : : double limit_tuples)
5647 : : {
5648 : 62200 : Path *cheapest_input_path = input_rel->cheapest_total_path;
5649 : : RelOptInfo *ordered_rel;
5650 : : ListCell *lc;
5651 : :
5652 : : /* For now, do all work in the (ORDERED, NULL) upperrel */
5653 : 62200 : ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
5654 : :
5655 : : /*
5656 : : * If the input relation is not parallel-safe, then the ordered relation
5657 : : * can't be parallel-safe, either. Otherwise, it's parallel-safe if the
5658 : : * target list is parallel-safe.
5659 : : */
3005 rhaas@postgresql.org 5660 [ + + + + ]: 62200 : if (input_rel->consider_parallel && target_parallel_safe)
3620 5661 : 43540 : ordered_rel->consider_parallel = true;
5662 : :
5663 : : /* Assume that the same path generation strategies are allowed. */
122 rhaas@postgresql.org 5664 :GNC 62200 : ordered_rel->pgs_mask = input_rel->pgs_mask;
5665 : :
5666 : : /*
5667 : : * If the input rel belongs to a single FDW, so does the ordered_rel.
5668 : : */
3620 tgl@sss.pgh.pa.us 5669 :CBC 62200 : ordered_rel->serverid = input_rel->serverid;
3606 5670 : 62200 : ordered_rel->userid = input_rel->userid;
5671 : 62200 : ordered_rel->useridiscurrent = input_rel->useridiscurrent;
3620 5672 : 62200 : ordered_rel->fdwroutine = input_rel->fdwroutine;
5673 : :
3736 5674 [ + - + + : 157174 : foreach(lc, input_rel->pathlist)
+ + ]
5675 : : {
2245 tomas.vondra@postgre 5676 : 94974 : Path *input_path = (Path *) lfirst(lc);
5677 : : Path *sorted_path;
5678 : : bool is_sorted;
5679 : : int presorted_keys;
5680 : :
5681 : 94974 : is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5682 : : input_path->pathkeys, &presorted_keys);
5683 : :
5684 [ + + ]: 94974 : if (is_sorted)
1261 drowley@postgresql.o 5685 : 37249 : sorted_path = input_path;
5686 : : else
5687 : : {
5688 : : /*
5689 : : * Try at least sorting the cheapest path and also try
5690 : : * incrementally sorting any path which is partially sorted
5691 : : * already (no need to deal with paths which have presorted keys
5692 : : * when incremental sort is disabled unless it's the cheapest
5693 : : * input path).
5694 : : */
5695 [ + + ]: 57725 : if (input_path != cheapest_input_path &&
5696 [ + + + + ]: 4837 : (presorted_keys == 0 || !enable_incremental_sort))
5697 : 1598 : continue;
5698 : :
5699 : : /*
5700 : : * We've no need to consider both a sort and incremental sort.
5701 : : * We'll just do a sort if there are no presorted keys and an
5702 : : * incremental sort when there are presorted keys.
5703 : : */
5704 [ + + + + ]: 56127 : if (presorted_keys == 0 || !enable_incremental_sort)
2245 tomas.vondra@postgre 5705 : 52431 : sorted_path = (Path *) create_sort_path(root,
5706 : : ordered_rel,
5707 : : input_path,
5708 : : root->sort_pathkeys,
5709 : : limit_tuples);
5710 : : else
1261 drowley@postgresql.o 5711 : 3696 : sorted_path = (Path *) create_incremental_sort_path(root,
5712 : : ordered_rel,
5713 : : input_path,
5714 : : root->sort_pathkeys,
5715 : : presorted_keys,
5716 : : limit_tuples);
5717 : : }
5718 : :
5719 : : /*
5720 : : * If the pathtarget of the result path has different expressions from
5721 : : * the target to be applied, a projection step is needed.
5722 : : */
633 rguo@postgresql.org 5723 [ + + ]: 93376 : if (!equal(sorted_path->pathtarget->exprs, target->exprs))
1261 drowley@postgresql.o 5724 : 288 : sorted_path = apply_projection_to_path(root, ordered_rel,
5725 : : sorted_path, target);
5726 : :
5727 : 93376 : add_path(ordered_rel, sorted_path);
5728 : : }
5729 : :
5730 : : /*
5731 : : * generate_gather_paths() will have already generated a simple Gather
5732 : : * path for the best parallel path, if any, and the loop above will have
5733 : : * considered sorting it. Similarly, generate_gather_paths() will also
5734 : : * have generated order-preserving Gather Merge plans which can be used
5735 : : * without sorting if they happen to match the sort_pathkeys, and the loop
5736 : : * above will have handled those as well. However, there's one more
5737 : : * possibility: it may make sense to sort the cheapest partial path or
5738 : : * incrementally sort any partial path that is partially sorted according
5739 : : * to the required output order and then use Gather Merge.
5740 : : */
3369 rhaas@postgresql.org 5741 [ + + + + ]: 62200 : if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
5742 [ + + ]: 43420 : input_rel->partial_pathlist != NIL)
5743 : : {
5744 : : Path *cheapest_partial_path;
5745 : :
5746 : 2418 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
5747 : :
850 drowley@postgresql.o 5748 [ + - + + : 5391 : foreach(lc, input_rel->partial_pathlist)
+ + ]
5749 : : {
5750 : 2973 : Path *input_path = (Path *) lfirst(lc);
5751 : : Path *sorted_path;
5752 : : bool is_sorted;
5753 : : int presorted_keys;
5754 : : double total_groups;
5755 : :
5756 : 2973 : is_sorted = pathkeys_count_contained_in(root->sort_pathkeys,
5757 : : input_path->pathkeys,
5758 : : &presorted_keys);
5759 : :
5760 [ + + ]: 2973 : if (is_sorted)
5761 : 476 : continue;
5762 : :
5763 : : /*
5764 : : * Try at least sorting the cheapest path and also try
5765 : : * incrementally sorting any path which is partially sorted
5766 : : * already (no need to deal with paths which have presorted keys
5767 : : * when incremental sort is disabled unless it's the cheapest
5768 : : * partial path).
5769 : : */
5770 [ + + ]: 2497 : if (input_path != cheapest_partial_path &&
5771 [ + - - + ]: 101 : (presorted_keys == 0 || !enable_incremental_sort))
850 drowley@postgresql.o 5772 :UBC 0 : continue;
5773 : :
5774 : : /*
5775 : : * We've no need to consider both a sort and incremental sort.
5776 : : * We'll just do a sort if there are no presorted keys and an
5777 : : * incremental sort when there are presorted keys.
5778 : : */
850 drowley@postgresql.o 5779 [ + + + + ]:CBC 2497 : if (presorted_keys == 0 || !enable_incremental_sort)
5780 : 2381 : sorted_path = (Path *) create_sort_path(root,
5781 : : ordered_rel,
5782 : : input_path,
5783 : : root->sort_pathkeys,
5784 : : limit_tuples);
5785 : : else
2244 tomas.vondra@postgre 5786 : 116 : sorted_path = (Path *) create_incremental_sort_path(root,
5787 : : ordered_rel,
5788 : : input_path,
5789 : : root->sort_pathkeys,
5790 : : presorted_keys,
5791 : : limit_tuples);
676 rguo@postgresql.org 5792 : 2497 : total_groups = compute_gather_rows(sorted_path);
5793 : : sorted_path = (Path *)
850 drowley@postgresql.o 5794 : 2497 : create_gather_merge_path(root, ordered_rel,
5795 : : sorted_path,
5796 : : sorted_path->pathtarget,
5797 : : root->sort_pathkeys, NULL,
5798 : : &total_groups);
5799 : :
5800 : : /*
5801 : : * If the pathtarget of the result path has different expressions
5802 : : * from the target to be applied, a projection step is needed.
5803 : : */
633 rguo@postgresql.org 5804 [ + + ]: 2497 : if (!equal(sorted_path->pathtarget->exprs, target->exprs))
850 drowley@postgresql.o 5805 : 5 : sorted_path = apply_projection_to_path(root, ordered_rel,
5806 : : sorted_path, target);
5807 : :
5808 : 2497 : add_path(ordered_rel, sorted_path);
5809 : : }
5810 : : }
5811 : :
5812 : : /*
5813 : : * If there is an FDW that's responsible for all baserels of the query,
5814 : : * let it consider adding ForeignPaths.
5815 : : */
3620 tgl@sss.pgh.pa.us 5816 [ + + ]: 62200 : if (ordered_rel->fdwroutine &&
5817 [ + + ]: 197 : ordered_rel->fdwroutine->GetForeignUpperPaths)
5818 : 189 : ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
5819 : : input_rel, ordered_rel,
5820 : : NULL);
5821 : :
5822 : : /* Let extensions possibly add some more paths */
3700 5823 [ - + ]: 62200 : if (create_upper_paths_hook)
3700 tgl@sss.pgh.pa.us 5824 :UBC 0 : (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
5825 : : input_rel, ordered_rel, NULL);
5826 : :
5827 : : /*
5828 : : * No need to bother with set_cheapest here; grouping_planner does not
5829 : : * need us to do it.
5830 : : */
3736 tgl@sss.pgh.pa.us 5831 [ - + ]:CBC 62200 : Assert(ordered_rel->pathlist != NIL);
5832 : :
5833 : 62200 : return ordered_rel;
5834 : : }
5835 : :
5836 : :
5837 : : /*
5838 : : * make_group_input_target
5839 : : * Generate appropriate PathTarget for initial input to grouping nodes.
5840 : : *
5841 : : * If there is grouping or aggregation, the scan/join subplan cannot emit
5842 : : * the query's final targetlist; for example, it certainly can't emit any
5843 : : * aggregate function calls. This routine generates the correct target
5844 : : * for the scan/join subplan.
5845 : : *
5846 : : * The query target list passed from the parser already contains entries
5847 : : * for all ORDER BY and GROUP BY expressions, but it will not have entries
5848 : : * for variables used only in HAVING clauses; so we need to add those
5849 : : * variables to the subplan target list. Also, we flatten all expressions
5850 : : * except GROUP BY items into their component variables; other expressions
5851 : : * will be computed by the upper plan nodes rather than by the subplan.
5852 : : * For example, given a query like
5853 : : * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
5854 : : * we want to pass this targetlist to the subplan:
5855 : : * a+b,c,d
5856 : : * where the a+b target will be used by the Sort/Group steps, and the
5857 : : * other targets will be used for computing the final results.
5858 : : *
5859 : : * 'final_target' is the query's final target list (in PathTarget form)
5860 : : *
5861 : : * The result is the PathTarget to be computed by the Paths returned from
5862 : : * query_planner().
5863 : : */
5864 : : static PathTarget *
3732 5865 : 34247 : make_group_input_target(PlannerInfo *root, PathTarget *final_target)
5866 : : {
7664 5867 : 34247 : Query *parse = root->parse;
5868 : : PathTarget *input_target;
5869 : : List *non_group_cols;
5870 : : List *non_group_vars;
5871 : : int i;
5872 : : ListCell *lc;
5873 : :
5874 : : /*
5875 : : * We must build a target containing all grouping columns, plus any other
5876 : : * Vars mentioned in the query's targetlist and HAVING qual.
5877 : : */
3732 5878 : 34247 : input_target = create_empty_pathtarget();
5432 5879 : 34247 : non_group_cols = NIL;
5880 : :
3732 5881 : 34247 : i = 0;
5882 [ + + + + : 86082 : foreach(lc, final_target->exprs)
+ + ]
5883 : : {
5884 : 51835 : Expr *expr = (Expr *) lfirst(lc);
3638 5885 [ + - ]: 51835 : Index sgref = get_pathtarget_sortgroupref(final_target, i);
5886 : :
1228 5887 [ + + + + : 60011 : if (sgref && root->processed_groupClause &&
+ + ]
5888 : 8176 : get_sortgroupref_clause_noerr(sgref,
5889 : : root->processed_groupClause) != NULL)
5890 : : {
5891 : : /*
5892 : : * It's a grouping column, so add it to the input target as-is.
5893 : : *
5894 : : * Note that the target is logically below the grouping step. So
5895 : : * with grouping sets we need to remove the RT index of the
5896 : : * grouping step if there is any from the target expression.
5897 : : */
627 rguo@postgresql.org 5898 [ + - + + ]: 6660 : if (parse->hasGroupRTE && parse->groupingSets != NIL)
5899 : : {
5900 [ - + ]: 1803 : Assert(root->group_rtindex > 0);
5901 : : expr = (Expr *)
5902 : 1803 : remove_nulling_relids((Node *) expr,
5903 : 1803 : bms_make_singleton(root->group_rtindex),
5904 : : NULL);
5905 : : }
3732 tgl@sss.pgh.pa.us 5906 : 6660 : add_column_to_pathtarget(input_target, expr, sgref);
5907 : : }
5908 : : else
5909 : : {
5910 : : /*
5911 : : * Non-grouping column, so just remember the expression for later
5912 : : * call to pull_var_clause.
5913 : : */
5914 : 45175 : non_group_cols = lappend(non_group_cols, expr);
5915 : : }
5916 : :
5917 : 51835 : i++;
5918 : : }
5919 : :
5920 : : /*
5921 : : * If there's a HAVING clause, we'll need the Vars it uses, too.
5922 : : */
5432 5923 [ + + ]: 34247 : if (parse->havingQual)
5924 : 841 : non_group_cols = lappend(non_group_cols, parse->havingQual);
5925 : :
5926 : : /*
5927 : : * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
5928 : : * add them to the input target if not already present. (A Var used
5929 : : * directly as a GROUP BY item will be present already.) Note this
5930 : : * includes Vars used in resjunk items, so we are covering the needs of
5931 : : * ORDER BY and window specifications. Vars used within Aggrefs and
5932 : : * WindowFuncs will be pulled out here, too.
5933 : : *
5934 : : * Note that the target is logically below the grouping step. So with
5935 : : * grouping sets we need to remove the RT index of the grouping step if
5936 : : * there is any from the non-group Vars.
5937 : : */
5938 : 34247 : non_group_vars = pull_var_clause((Node *) non_group_cols,
5939 : : PVC_RECURSE_AGGREGATES |
5940 : : PVC_RECURSE_WINDOWFUNCS |
5941 : : PVC_INCLUDE_PLACEHOLDERS);
627 rguo@postgresql.org 5942 [ + + + + ]: 34247 : if (parse->hasGroupRTE && parse->groupingSets != NIL)
5943 : : {
5944 [ - + ]: 836 : Assert(root->group_rtindex > 0);
5945 : : non_group_vars = (List *)
5946 : 836 : remove_nulling_relids((Node *) non_group_vars,
5947 : 836 : bms_make_singleton(root->group_rtindex),
5948 : : NULL);
5949 : : }
3732 tgl@sss.pgh.pa.us 5950 : 34247 : add_new_columns_to_pathtarget(input_target, non_group_vars);
5951 : :
5952 : : /* clean up cruft */
5432 5953 : 34247 : list_free(non_group_vars);
5954 : 34247 : list_free(non_group_cols);
5955 : :
5956 : : /* XXX this causes some redundant cost calculation ... */
3732 5957 : 34247 : return set_pathtarget_cost_width(root, input_target);
5958 : : }
5959 : :
5960 : : /*
5961 : : * make_partial_grouping_target
5962 : : * Generate appropriate PathTarget for output of partial aggregate
5963 : : * (or partial grouping, if there are no aggregates) nodes.
5964 : : *
5965 : : * A partial aggregation node needs to emit all the same aggregates that
5966 : : * a regular aggregation node would, plus any aggregates used in HAVING;
5967 : : * except that the Aggref nodes should be marked as partial aggregates.
5968 : : *
5969 : : * In addition, we'd better emit any Vars and PlaceHolderVars that are
5970 : : * used outside of Aggrefs in the aggregation tlist and HAVING. (Presumably,
5971 : : * these would be Vars that are grouped by or used in grouping expressions.)
5972 : : *
5973 : : * grouping_target is the tlist to be emitted by the topmost aggregation step.
5974 : : * havingQual represents the HAVING clause.
5975 : : */
5976 : : static PathTarget *
2998 rhaas@postgresql.org 5977 : 3205 : make_partial_grouping_target(PlannerInfo *root,
5978 : : PathTarget *grouping_target,
5979 : : Node *havingQual)
5980 : : {
5981 : : PathTarget *partial_target;
5982 : : List *non_group_cols;
5983 : : List *non_group_exprs;
5984 : : int i;
5985 : : ListCell *lc;
5986 : :
3625 tgl@sss.pgh.pa.us 5987 : 3205 : partial_target = create_empty_pathtarget();
3722 rhaas@postgresql.org 5988 : 3205 : non_group_cols = NIL;
5989 : :
5990 : 3205 : i = 0;
3625 tgl@sss.pgh.pa.us 5991 [ + - + + : 10561 : foreach(lc, grouping_target->exprs)
+ + ]
5992 : : {
3722 rhaas@postgresql.org 5993 : 7356 : Expr *expr = (Expr *) lfirst(lc);
3625 tgl@sss.pgh.pa.us 5994 [ + - ]: 7356 : Index sgref = get_pathtarget_sortgroupref(grouping_target, i);
5995 : :
1228 5996 [ + + + + : 11288 : if (sgref && root->processed_groupClause &&
+ + ]
5997 : 3932 : get_sortgroupref_clause_noerr(sgref,
5998 : : root->processed_groupClause) != NULL)
5999 : : {
6000 : : /*
6001 : : * It's a grouping column, so add it to the partial_target as-is.
6002 : : * (This allows the upper agg step to repeat the grouping calcs.)
6003 : : */
3625 6004 : 2330 : add_column_to_pathtarget(partial_target, expr, sgref);
6005 : : }
6006 : : else
6007 : : {
6008 : : /*
6009 : : * Non-grouping column, so just remember the expression for later
6010 : : * call to pull_var_clause.
6011 : : */
3722 rhaas@postgresql.org 6012 : 5026 : non_group_cols = lappend(non_group_cols, expr);
6013 : : }
6014 : :
6015 : 7356 : i++;
6016 : : }
6017 : :
6018 : : /*
6019 : : * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
6020 : : */
2998 6021 [ + + ]: 3205 : if (havingQual)
6022 : 729 : non_group_cols = lappend(non_group_cols, havingQual);
6023 : :
6024 : : /*
6025 : : * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
6026 : : * non-group cols (plus HAVING), and add them to the partial_target if not
6027 : : * already present. (An expression used directly as a GROUP BY item will
6028 : : * be present already.) Note this includes Vars used in resjunk items, so
6029 : : * we are covering the needs of ORDER BY and window specifications.
6030 : : */
3722 6031 : 3205 : non_group_exprs = pull_var_clause((Node *) non_group_cols,
6032 : : PVC_INCLUDE_AGGREGATES |
6033 : : PVC_RECURSE_WINDOWFUNCS |
6034 : : PVC_INCLUDE_PLACEHOLDERS);
6035 : :
3625 tgl@sss.pgh.pa.us 6036 : 3205 : add_new_columns_to_pathtarget(partial_target, non_group_exprs);
6037 : :
6038 : : /*
6039 : : * Adjust Aggrefs to put them in partial mode. At this point all Aggrefs
6040 : : * are at the top level of the target list, so we can just scan the list
6041 : : * rather than recursing through the expression trees.
6042 : : */
6043 [ + - + + : 11075 : foreach(lc, partial_target->exprs)
+ + ]
6044 : : {
6045 : 7870 : Aggref *aggref = (Aggref *) lfirst(lc);
6046 : :
6047 [ + + ]: 7870 : if (IsA(aggref, Aggref))
6048 : : {
6049 : : Aggref *newaggref;
6050 : :
6051 : : /*
6052 : : * We shouldn't need to copy the substructure of the Aggref node,
6053 : : * but flat-copy the node itself to avoid damaging other trees.
6054 : : */
6055 : 5515 : newaggref = makeNode(Aggref);
6056 : 5515 : memcpy(newaggref, aggref, sizeof(Aggref));
6057 : :
6058 : : /* For now, assume serialization is required */
6059 : 5515 : mark_partial_aggref(newaggref, AGGSPLIT_INITIAL_SERIAL);
6060 : :
6061 : 5515 : lfirst(lc) = newaggref;
6062 : : }
6063 : : }
6064 : :
6065 : : /* clean up cruft */
3722 rhaas@postgresql.org 6066 : 3205 : list_free(non_group_exprs);
6067 : 3205 : list_free(non_group_cols);
6068 : :
6069 : : /* XXX this causes some redundant cost calculation ... */
3625 tgl@sss.pgh.pa.us 6070 : 3205 : return set_pathtarget_cost_width(root, partial_target);
6071 : : }
6072 : :
6073 : : /*
6074 : : * mark_partial_aggref
6075 : : * Adjust an Aggref to make it represent a partial-aggregation step.
6076 : : *
6077 : : * The Aggref node is modified in-place; caller must do any copying required.
6078 : : */
6079 : : void
6080 : 15317 : mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
6081 : : {
6082 : : /* aggtranstype should be computed by this point */
6083 [ - + ]: 15317 : Assert(OidIsValid(agg->aggtranstype));
6084 : : /* ... but aggsplit should still be as the parser left it */
6085 [ - + ]: 15317 : Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
6086 : :
6087 : : /* Mark the Aggref with the intended partial-aggregation mode */
6088 : 15317 : agg->aggsplit = aggsplit;
6089 : :
6090 : : /*
6091 : : * Adjust result type if needed. Normally, a partial aggregate returns
6092 : : * the aggregate's transition type; but if that's INTERNAL and we're
6093 : : * serializing, it returns BYTEA instead.
6094 : : */
6095 [ + + ]: 15317 : if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
6096 : : {
6097 [ + + + - ]: 13418 : if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
6098 : 261 : agg->aggtype = BYTEAOID;
6099 : : else
6100 : 13157 : agg->aggtype = agg->aggtranstype;
6101 : : }
3722 rhaas@postgresql.org 6102 : 15317 : }
6103 : :
6104 : : /*
6105 : : * postprocess_setop_tlist
6106 : : * Fix up targetlist returned by plan_set_operations().
6107 : : *
6108 : : * We need to transpose sort key info from the orig_tlist into new_tlist.
6109 : : * NOTE: this would not be good enough if we supported resjunk sort keys
6110 : : * for results of set operations --- then, we'd need to project a whole
6111 : : * new tlist to evaluate the resjunk columns. For now, just ereport if we
6112 : : * find any resjunk columns in orig_tlist.
6113 : : */
6114 : : static List *
9333 tgl@sss.pgh.pa.us 6115 : 4970 : postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
6116 : : {
6117 : : ListCell *l;
8039 neilc@samurai.com 6118 : 4970 : ListCell *orig_tlist_item = list_head(orig_tlist);
6119 : :
9333 tgl@sss.pgh.pa.us 6120 [ + + + + : 19271 : foreach(l, new_tlist)
+ + ]
6121 : : {
3189 6122 : 14301 : TargetEntry *new_tle = lfirst_node(TargetEntry, l);
6123 : : TargetEntry *orig_tle;
6124 : :
6125 : : /* ignore resjunk columns in setop result */
7724 6126 [ - + ]: 14301 : if (new_tle->resjunk)
9333 tgl@sss.pgh.pa.us 6127 :UBC 0 : continue;
6128 : :
8039 neilc@samurai.com 6129 [ - + ]:CBC 14301 : Assert(orig_tlist_item != NULL);
3189 tgl@sss.pgh.pa.us 6130 : 14301 : orig_tle = lfirst_node(TargetEntry, orig_tlist_item);
2511 6131 : 14301 : orig_tlist_item = lnext(orig_tlist, orig_tlist_item);
7532 bruce@momjian.us 6132 [ - + ]: 14301 : if (orig_tle->resjunk) /* should not happen */
8345 tgl@sss.pgh.pa.us 6133 [ # # ]:UBC 0 : elog(ERROR, "resjunk output columns are not implemented");
7724 tgl@sss.pgh.pa.us 6134 [ - + ]:CBC 14301 : Assert(new_tle->resno == orig_tle->resno);
6135 : 14301 : new_tle->ressortgroupref = orig_tle->ressortgroupref;
6136 : : }
8039 neilc@samurai.com 6137 [ - + ]: 4970 : if (orig_tlist_item != NULL)
8345 tgl@sss.pgh.pa.us 6138 [ # # ]:UBC 0 : elog(ERROR, "resjunk output columns are not implemented");
9333 tgl@sss.pgh.pa.us 6139 :CBC 4970 : return new_tlist;
6140 : : }
6141 : :
6142 : : /*
6143 : : * optimize_window_clauses
6144 : : * Call each WindowFunc's prosupport function to see if we're able to
6145 : : * make any adjustments to any of the WindowClause's so that the executor
6146 : : * can execute the window functions in a more optimal way.
6147 : : *
6148 : : * Currently we only allow adjustments to the WindowClause's frameOptions. We
6149 : : * may allow more things to be done here in the future.
6150 : : */
6151 : : static void
1254 drowley@postgresql.o 6152 : 2232 : optimize_window_clauses(PlannerInfo *root, WindowFuncLists *wflists)
6153 : : {
6154 : 2232 : List *windowClause = root->parse->windowClause;
6155 : : ListCell *lc;
6156 : :
6157 [ + - + + : 4669 : foreach(lc, windowClause)
+ + ]
6158 : : {
6159 : 2437 : WindowClause *wc = lfirst_node(WindowClause, lc);
6160 : : ListCell *lc2;
6161 : 2437 : int optimizedFrameOptions = 0;
6162 : :
6163 [ - + ]: 2437 : Assert(wc->winref <= wflists->maxWinRef);
6164 : :
6165 : : /* skip any WindowClauses that have no WindowFuncs */
6166 [ + + ]: 2437 : if (wflists->windowFuncs[wc->winref] == NIL)
6167 : 20 : continue;
6168 : :
6169 [ + - + + : 2960 : foreach(lc2, wflists->windowFuncs[wc->winref])
+ + ]
6170 : : {
6171 : : SupportRequestOptimizeWindowClause req;
6172 : : SupportRequestOptimizeWindowClause *res;
6173 : 2452 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
6174 : : Oid prosupport;
6175 : :
6176 : 2452 : prosupport = get_func_support(wfunc->winfnoid);
6177 : :
6178 : : /* Check if there's a support function for 'wfunc' */
6179 [ + + ]: 2452 : if (!OidIsValid(prosupport))
6180 : 1909 : break; /* can't optimize this WindowClause */
6181 : :
6182 : 730 : req.type = T_SupportRequestOptimizeWindowClause;
6183 : 730 : req.window_clause = wc;
6184 : 730 : req.window_func = wfunc;
6185 : 730 : req.frameOptions = wc->frameOptions;
6186 : :
6187 : : /* call the support function */
6188 : : res = (SupportRequestOptimizeWindowClause *)
6189 : 730 : DatumGetPointer(OidFunctionCall1(prosupport,
6190 : : PointerGetDatum(&req)));
6191 : :
6192 : : /*
6193 : : * Skip to next WindowClause if the support function does not
6194 : : * support this request type.
6195 : : */
6196 [ + + ]: 730 : if (res == NULL)
6197 : 187 : break;
6198 : :
6199 : : /*
6200 : : * Save these frameOptions for the first WindowFunc for this
6201 : : * WindowClause.
6202 : : */
6203 [ + + ]: 543 : if (foreach_current_index(lc2) == 0)
6204 : 523 : optimizedFrameOptions = res->frameOptions;
6205 : :
6206 : : /*
6207 : : * On subsequent WindowFuncs, if the frameOptions are not the same
6208 : : * then we're unable to optimize the frameOptions for this
6209 : : * WindowClause.
6210 : : */
6211 [ - + ]: 20 : else if (optimizedFrameOptions != res->frameOptions)
1254 drowley@postgresql.o 6212 :UBC 0 : break; /* skip to the next WindowClause, if any */
6213 : : }
6214 : :
6215 : : /* adjust the frameOptions if all WindowFunc's agree that it's ok */
1254 drowley@postgresql.o 6216 [ + + + - ]:CBC 2417 : if (lc2 == NULL && wc->frameOptions != optimizedFrameOptions)
6217 : : {
6218 : : ListCell *lc3;
6219 : :
6220 : : /* apply the new frame options */
6221 : 508 : wc->frameOptions = optimizedFrameOptions;
6222 : :
6223 : : /*
6224 : : * We now check to see if changing the frameOptions has caused
6225 : : * this WindowClause to be a duplicate of some other WindowClause.
6226 : : * This can only happen if we have multiple WindowClauses, so
6227 : : * don't bother if there's only 1.
6228 : : */
6229 [ + + ]: 508 : if (list_length(windowClause) == 1)
6230 : 433 : continue;
6231 : :
6232 : : /*
6233 : : * Do the duplicate check and reuse the existing WindowClause if
6234 : : * we find a duplicate.
6235 : : */
6236 [ + - + + : 190 : foreach(lc3, windowClause)
+ + ]
6237 : : {
6238 : 145 : WindowClause *existing_wc = lfirst_node(WindowClause, lc3);
6239 : :
6240 : : /* skip over the WindowClause we're currently editing */
6241 [ + + ]: 145 : if (existing_wc == wc)
6242 : 45 : continue;
6243 : :
6244 : : /*
6245 : : * Perform the same duplicate check that is done in
6246 : : * transformWindowFuncCall.
6247 : : */
6248 [ + - + + ]: 200 : if (equal(wc->partitionClause, existing_wc->partitionClause) &&
6249 : 100 : equal(wc->orderClause, existing_wc->orderClause) &&
6250 [ + + + - ]: 100 : wc->frameOptions == existing_wc->frameOptions &&
6251 [ + - ]: 60 : equal(wc->startOffset, existing_wc->startOffset) &&
6252 : 30 : equal(wc->endOffset, existing_wc->endOffset))
6253 : : {
6254 : : ListCell *lc4;
6255 : :
6256 : : /*
6257 : : * Now move each WindowFunc in 'wc' into 'existing_wc'.
6258 : : * This required adjusting each WindowFunc's winref and
6259 : : * moving the WindowFuncs in 'wc' to the list of
6260 : : * WindowFuncs in 'existing_wc'.
6261 : : */
6262 [ + - + + : 65 : foreach(lc4, wflists->windowFuncs[wc->winref])
+ + ]
6263 : : {
6264 : 35 : WindowFunc *wfunc = lfirst_node(WindowFunc, lc4);
6265 : :
6266 : 35 : wfunc->winref = existing_wc->winref;
6267 : : }
6268 : :
6269 : : /* move list items */
6270 : 60 : wflists->windowFuncs[existing_wc->winref] = list_concat(wflists->windowFuncs[existing_wc->winref],
6271 : 30 : wflists->windowFuncs[wc->winref]);
6272 : 30 : wflists->windowFuncs[wc->winref] = NIL;
6273 : :
6274 : : /*
6275 : : * transformWindowFuncCall() should have made sure there
6276 : : * are no other duplicates, so we needn't bother looking
6277 : : * any further.
6278 : : */
6279 : 30 : break;
6280 : : }
6281 : : }
6282 : : }
6283 : : }
6284 : 2232 : }
6285 : :
6286 : : /*
6287 : : * select_active_windows
6288 : : * Create a list of the "active" window clauses (ie, those referenced
6289 : : * by non-deleted WindowFuncs) in the order they are to be executed.
6290 : : */
6291 : : static List *
6362 tgl@sss.pgh.pa.us 6292 : 2232 : select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
6293 : : {
2815 rhodiumtoad@postgres 6294 : 2232 : List *windowClause = root->parse->windowClause;
6295 : 2232 : List *result = NIL;
6296 : : ListCell *lc;
6297 : 2232 : int nActive = 0;
171 michael@paquier.xyz 6298 :GNC 2232 : WindowClauseSortData *actives = palloc_array(WindowClauseSortData,
6299 : : list_length(windowClause));
6300 : :
6301 : : /* First, construct an array of the active windows */
2815 rhodiumtoad@postgres 6302 [ + - + + :CBC 4669 : foreach(lc, windowClause)
+ + ]
6303 : : {
3189 tgl@sss.pgh.pa.us 6304 : 2437 : WindowClause *wc = lfirst_node(WindowClause, lc);
6305 : :
6306 : : /* It's only active if wflists shows some related WindowFuncs */
6362 6307 [ - + ]: 2437 : Assert(wc->winref <= wflists->maxWinRef);
2815 rhodiumtoad@postgres 6308 [ + + ]: 2437 : if (wflists->windowFuncs[wc->winref] == NIL)
6309 : 50 : continue;
6310 : :
6311 : 2387 : actives[nActive].wc = wc; /* original clause */
6312 : :
6313 : : /*
6314 : : * For sorting, we want the list of partition keys followed by the
6315 : : * list of sort keys. But pathkeys construction will remove duplicates
6316 : : * between the two, so we can as well (even though we can't detect all
6317 : : * of the duplicates, since some may come from ECs - that might mean
6318 : : * we miss optimization chances here). We must, however, ensure that
6319 : : * the order of entries is preserved with respect to the ones we do
6320 : : * keep.
6321 : : *
6322 : : * partitionClause and orderClause had their own duplicates removed in
6323 : : * parse analysis, so we're only concerned here with removing
6324 : : * orderClause entries that also appear in partitionClause.
6325 : : */
6326 : 4774 : actives[nActive].uniqueOrder =
6327 : 2387 : list_concat_unique(list_copy(wc->partitionClause),
6328 : 2387 : wc->orderClause);
6329 : 2387 : nActive++;
6330 : : }
6331 : :
6332 : : /*
6333 : : * Sort active windows by their partitioning/ordering clauses, ignoring
6334 : : * any framing clauses, so that the windows that need the same sorting are
6335 : : * adjacent in the list. When we come to generate paths, this will avoid
6336 : : * inserting additional Sort nodes.
6337 : : *
6338 : : * This is how we implement a specific requirement from the SQL standard,
6339 : : * which says that when two or more windows are order-equivalent (i.e.
6340 : : * have matching partition and order clauses, even if their names or
6341 : : * framing clauses differ), then all peer rows must be presented in the
6342 : : * same order in all of them. If we allowed multiple sort nodes for such
6343 : : * cases, we'd risk having the peer rows end up in different orders in
6344 : : * equivalent windows due to sort instability. (See General Rule 4 of
6345 : : * <window clause> in SQL2008 - SQL2016.)
6346 : : *
6347 : : * Additionally, if the entire list of clauses of one window is a prefix
6348 : : * of another, put first the window with stronger sorting requirements.
6349 : : * This way we will first sort for stronger window, and won't have to sort
6350 : : * again for the weaker one.
6351 : : */
6352 : 2232 : qsort(actives, nActive, sizeof(WindowClauseSortData), common_prefix_cmp);
6353 : :
6354 : : /* build ordered list of the original WindowClause nodes */
6355 [ + + ]: 4619 : for (int i = 0; i < nActive; i++)
6356 : 2387 : result = lappend(result, actives[i].wc);
6357 : :
6358 : 2232 : pfree(actives);
6359 : :
6360 : 2232 : return result;
6361 : : }
6362 : :
6363 : : /*
6364 : : * name_active_windows
6365 : : * Ensure all active windows have unique names.
6366 : : *
6367 : : * The parser will have checked that user-assigned window names are unique
6368 : : * within the Query. Here we assign made-up names to any unnamed
6369 : : * WindowClauses for the benefit of EXPLAIN. (We don't want to do this
6370 : : * at parse time, because it'd mess up decompilation of views.)
6371 : : *
6372 : : * activeWindows: result of select_active_windows
6373 : : */
6374 : : static void
445 tgl@sss.pgh.pa.us 6375 : 2232 : name_active_windows(List *activeWindows)
6376 : : {
6377 : 2232 : int next_n = 1;
6378 : : char newname[16];
6379 : : ListCell *lc;
6380 : :
6381 [ + - + + : 4619 : foreach(lc, activeWindows)
+ + ]
6382 : : {
6383 : 2387 : WindowClause *wc = lfirst_node(WindowClause, lc);
6384 : :
6385 : : /* Nothing to do if it has a name already. */
6386 [ + + ]: 2387 : if (wc->name)
6387 : 480 : continue;
6388 : :
6389 : : /* Select a name not currently present in the list. */
6390 : : for (;;)
6391 : 5 : {
6392 : : ListCell *lc2;
6393 : :
6394 : 1912 : snprintf(newname, sizeof(newname), "w%d", next_n++);
6395 [ + - + + : 4114 : foreach(lc2, activeWindows)
+ + ]
6396 : : {
6397 : 2207 : WindowClause *wc2 = lfirst_node(WindowClause, lc2);
6398 : :
6399 [ + + + + ]: 2207 : if (wc2->name && strcmp(wc2->name, newname) == 0)
6400 : 5 : break; /* matched */
6401 : : }
6402 [ + + ]: 1912 : if (lc2 == NULL)
6403 : 1907 : break; /* reached the end with no match */
6404 : : }
6405 : 1907 : wc->name = pstrdup(newname);
6406 : : }
6407 : 2232 : }
6408 : :
6409 : : /*
6410 : : * common_prefix_cmp
6411 : : * QSort comparison function for WindowClauseSortData
6412 : : *
6413 : : * Sort the windows by the required sorting clauses. First, compare the sort
6414 : : * clauses themselves. Second, if one window's clauses are a prefix of another
6415 : : * one's clauses, put the window with more sort clauses first.
6416 : : *
6417 : : * We purposefully sort by the highest tleSortGroupRef first. Since
6418 : : * tleSortGroupRefs are assigned for the query's DISTINCT and ORDER BY first
6419 : : * and because here we sort the lowest tleSortGroupRefs last, if a
6420 : : * WindowClause is sharing a tleSortGroupRef with the query's DISTINCT or
6421 : : * ORDER BY clause, this makes it more likely that the final WindowAgg will
6422 : : * provide presorted input for the query's DISTINCT or ORDER BY clause, thus
6423 : : * reducing the total number of sorts required for the query.
6424 : : */
6425 : : static int
2815 rhodiumtoad@postgres 6426 : 170 : common_prefix_cmp(const void *a, const void *b)
6427 : : {
6428 : 170 : const WindowClauseSortData *wcsa = a;
6429 : 170 : const WindowClauseSortData *wcsb = b;
6430 : : ListCell *item_a;
6431 : : ListCell *item_b;
6432 : :
6433 : 305 : forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
[ + + + +
+ + + + +
+ + + +
+ ]
6434 : : {
6435 : 220 : SortGroupClause *sca = lfirst_node(SortGroupClause, item_a);
6436 : 220 : SortGroupClause *scb = lfirst_node(SortGroupClause, item_b);
6437 : :
6438 [ + + ]: 220 : if (sca->tleSortGroupRef > scb->tleSortGroupRef)
6439 : 85 : return -1;
6440 [ + + ]: 210 : else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
6441 : 55 : return 1;
6442 [ - + ]: 155 : else if (sca->sortop > scb->sortop)
2815 rhodiumtoad@postgres 6443 :UBC 0 : return -1;
2815 rhodiumtoad@postgres 6444 [ + + ]:CBC 155 : else if (sca->sortop < scb->sortop)
6445 : 20 : return 1;
6446 [ - + - - ]: 135 : else if (sca->nulls_first && !scb->nulls_first)
2815 rhodiumtoad@postgres 6447 :UBC 0 : return -1;
2815 rhodiumtoad@postgres 6448 [ + - - + ]:CBC 135 : else if (!sca->nulls_first && scb->nulls_first)
2815 rhodiumtoad@postgres 6449 :UBC 0 : return 1;
6450 : : /* no need to compare eqop, since it is fully determined by sortop */
6451 : : }
6452 : :
2815 rhodiumtoad@postgres 6453 [ + + ]:CBC 85 : if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
6454 : 5 : return -1;
6455 [ + + ]: 80 : else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
6456 : 25 : return 1;
6457 : :
6458 : 55 : return 0;
6459 : : }
6460 : :
6461 : : /*
6462 : : * make_window_input_target
6463 : : * Generate appropriate PathTarget for initial input to WindowAgg nodes.
6464 : : *
6465 : : * When the query has window functions, this function computes the desired
6466 : : * target to be computed by the node just below the first WindowAgg.
6467 : : * This tlist must contain all values needed to evaluate the window functions,
6468 : : * compute the final target list, and perform any required final sort step.
6469 : : * If multiple WindowAggs are needed, each intermediate one adds its window
6470 : : * function results onto this base tlist; only the topmost WindowAgg computes
6471 : : * the actual desired target list.
6472 : : *
6473 : : * This function is much like make_group_input_target, though not quite enough
6474 : : * like it to share code. As in that function, we flatten most expressions
6475 : : * into their component variables. But we do not want to flatten window
6476 : : * PARTITION BY/ORDER BY clauses, since that might result in multiple
6477 : : * evaluations of them, which would be bad (possibly even resulting in
6478 : : * inconsistent answers, if they contain volatile functions).
6479 : : * Also, we must not flatten GROUP BY clauses that were left unflattened by
6480 : : * make_group_input_target, because we may no longer have access to the
6481 : : * individual Vars in them.
6482 : : *
6483 : : * Another key difference from make_group_input_target is that we don't
6484 : : * flatten Aggref expressions, since those are to be computed below the
6485 : : * window functions and just referenced like Vars above that.
6486 : : *
6487 : : * 'final_target' is the query's final target list (in PathTarget form)
6488 : : * 'activeWindows' is the list of active windows previously identified by
6489 : : * select_active_windows.
6490 : : *
6491 : : * The result is the PathTarget to be computed by the plan node immediately
6492 : : * below the first WindowAgg node.
6493 : : */
6494 : : static PathTarget *
3734 tgl@sss.pgh.pa.us 6495 : 2232 : make_window_input_target(PlannerInfo *root,
6496 : : PathTarget *final_target,
6497 : : List *activeWindows)
6498 : : {
6499 : : PathTarget *input_target;
6500 : : Bitmapset *sgrefs;
6501 : : List *flattenable_cols;
6502 : : List *flattenable_vars;
6503 : : int i;
6504 : : ListCell *lc;
6505 : :
1228 6506 [ - + ]: 2232 : Assert(root->parse->hasWindowFuncs);
6507 : :
6508 : : /*
6509 : : * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
6510 : : * into a bitmapset for convenient reference below.
6511 : : */
5007 6512 : 2232 : sgrefs = NULL;
6270 6513 [ + - + + : 4619 : foreach(lc, activeWindows)
+ + ]
6514 : : {
3189 6515 : 2387 : WindowClause *wc = lfirst_node(WindowClause, lc);
6516 : : ListCell *lc2;
6517 : :
6270 6518 [ + + + + : 3009 : foreach(lc2, wc->partitionClause)
+ + ]
6519 : : {
3189 6520 : 622 : SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc2);
6521 : :
6270 6522 : 622 : sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
6523 : : }
6524 [ + + + + : 4307 : foreach(lc2, wc->orderClause)
+ + ]
6525 : : {
3189 6526 : 1920 : SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc2);
6527 : :
6270 6528 : 1920 : sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
6529 : : }
6530 : : }
6531 : :
6532 : : /* Add in sortgroupref numbers of GROUP BY clauses, too */
1228 6533 [ + + + + : 2388 : foreach(lc, root->processed_groupClause)
+ + ]
6534 : : {
3189 6535 : 156 : SortGroupClause *grpcl = lfirst_node(SortGroupClause, lc);
6536 : :
5007 6537 : 156 : sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
6538 : : }
6539 : :
6540 : : /*
6541 : : * Construct a target containing all the non-flattenable targetlist items,
6542 : : * and save aside the others for a moment.
6543 : : */
3732 6544 : 2232 : input_target = create_empty_pathtarget();
5007 6545 : 2232 : flattenable_cols = NIL;
6546 : :
3732 6547 : 2232 : i = 0;
6548 [ + - + + : 9369 : foreach(lc, final_target->exprs)
+ + ]
6549 : : {
6550 : 7137 : Expr *expr = (Expr *) lfirst(lc);
3638 6551 [ + - ]: 7137 : Index sgref = get_pathtarget_sortgroupref(final_target, i);
6552 : :
6553 : : /*
6554 : : * Don't want to deconstruct window clauses or GROUP BY items. (Note
6555 : : * that such items can't contain window functions, so it's okay to
6556 : : * compute them below the WindowAgg nodes.)
6557 : : */
3732 6558 [ + + + + ]: 7137 : if (sgref != 0 && bms_is_member(sgref, sgrefs))
6559 : : {
6560 : : /*
6561 : : * Don't want to deconstruct this value, so add it to the input
6562 : : * target as-is.
6563 : : */
6564 : 2404 : add_column_to_pathtarget(input_target, expr, sgref);
6565 : : }
6566 : : else
6567 : : {
6568 : : /*
6569 : : * Column is to be flattened, so just remember the expression for
6570 : : * later call to pull_var_clause.
6571 : : */
6572 : 4733 : flattenable_cols = lappend(flattenable_cols, expr);
6573 : : }
6574 : :
6575 : 7137 : i++;
6576 : : }
6577 : :
6578 : : /*
6579 : : * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
6580 : : * add them to the input target if not already present. (Some might be
6581 : : * there already because they're used directly as window/group clauses.)
6582 : : *
6583 : : * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
6584 : : * Aggrefs are placed in the Agg node's tlist and not left to be computed
6585 : : * at higher levels. On the other hand, we should recurse into
6586 : : * WindowFuncs to make sure their input expressions are available.
6587 : : */
5007 6588 : 2232 : flattenable_vars = pull_var_clause((Node *) flattenable_cols,
6589 : : PVC_INCLUDE_AGGREGATES |
6590 : : PVC_RECURSE_WINDOWFUNCS |
6591 : : PVC_INCLUDE_PLACEHOLDERS);
3732 6592 : 2232 : add_new_columns_to_pathtarget(input_target, flattenable_vars);
6593 : :
6594 : : /* clean up cruft */
5007 6595 : 2232 : list_free(flattenable_vars);
6596 : 2232 : list_free(flattenable_cols);
6597 : :
6598 : : /* XXX this causes some redundant cost calculation ... */
3732 6599 : 2232 : return set_pathtarget_cost_width(root, input_target);
6600 : : }
6601 : :
6602 : : /*
6603 : : * make_pathkeys_for_window
6604 : : * Create a pathkeys list describing the required input ordering
6605 : : * for the given WindowClause.
6606 : : *
6607 : : * Modifies wc's partitionClause to remove any clauses which are deemed
6608 : : * redundant by the pathkey logic.
6609 : : *
6610 : : * The required ordering is first the PARTITION keys, then the ORDER keys.
6611 : : * In the future we might try to implement windowing using hashing, in which
6612 : : * case the ordering could be relaxed, but for now we always sort.
6613 : : */
6614 : : static List *
6362 6615 : 4786 : make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
6616 : : List *tlist)
6617 : : {
1062 drowley@postgresql.o 6618 : 4786 : List *window_pathkeys = NIL;
6619 : :
6620 : : /* Throw error if can't sort */
6362 tgl@sss.pgh.pa.us 6621 [ - + ]: 4786 : if (!grouping_is_sortable(wc->partitionClause))
6362 tgl@sss.pgh.pa.us 6622 [ # # ]:UBC 0 : ereport(ERROR,
6623 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6624 : : errmsg("could not implement window PARTITION BY"),
6625 : : errdetail("Window partitioning columns must be of sortable datatypes.")));
6362 tgl@sss.pgh.pa.us 6626 [ - + ]:CBC 4786 : if (!grouping_is_sortable(wc->orderClause))
6362 tgl@sss.pgh.pa.us 6627 [ # # ]:UBC 0 : ereport(ERROR,
6628 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6629 : : errmsg("could not implement window ORDER BY"),
6630 : : errdetail("Window ordering columns must be of sortable datatypes.")));
6631 : :
6632 : : /*
6633 : : * First fetch the pathkeys for the PARTITION BY clause. We can safely
6634 : : * remove any clauses from the wc->partitionClause for redundant pathkeys.
6635 : : */
1062 drowley@postgresql.o 6636 [ + + ]:CBC 4786 : if (wc->partitionClause != NIL)
6637 : : {
6638 : : bool sortable;
6639 : :
6640 : 1088 : window_pathkeys = make_pathkeys_for_sortclauses_extended(root,
6641 : : &wc->partitionClause,
6642 : : tlist,
6643 : : true,
6644 : : false,
6645 : : &sortable,
6646 : : false);
6647 : :
6648 [ - + ]: 1088 : Assert(sortable);
6649 : : }
6650 : :
6651 : : /*
6652 : : * In principle, we could also consider removing redundant ORDER BY items
6653 : : * too as doing so does not alter the result of peer row checks done by
6654 : : * the executor. However, we must *not* remove the ordering column for
6655 : : * RANGE OFFSET cases, as the executor needs that for in_range tests even
6656 : : * if it's known to be equal to some partitioning column.
6657 : : */
6658 [ + + ]: 4786 : if (wc->orderClause != NIL)
6659 : : {
6660 : : List *orderby_pathkeys;
6661 : :
6662 : 3754 : orderby_pathkeys = make_pathkeys_for_sortclauses(root,
6663 : : wc->orderClause,
6664 : : tlist);
6665 : :
6666 : : /* Okay, make the combined pathkeys */
6667 [ + + ]: 3754 : if (window_pathkeys != NIL)
6668 : 781 : window_pathkeys = append_pathkeys(window_pathkeys, orderby_pathkeys);
6669 : : else
6670 : 2973 : window_pathkeys = orderby_pathkeys;
6671 : : }
6672 : :
6362 tgl@sss.pgh.pa.us 6673 : 4786 : return window_pathkeys;
6674 : : }
6675 : :
6676 : : /*
6677 : : * make_sort_input_target
6678 : : * Generate appropriate PathTarget for initial input to Sort step.
6679 : : *
6680 : : * If the query has ORDER BY, this function chooses the target to be computed
6681 : : * by the node just below the Sort (and DISTINCT, if any, since Unique can't
6682 : : * project) steps. This might or might not be identical to the query's final
6683 : : * output target.
6684 : : *
6685 : : * The main argument for keeping the sort-input tlist the same as the final
6686 : : * is that we avoid a separate projection node (which will be needed if
6687 : : * they're different, because Sort can't project). However, there are also
6688 : : * advantages to postponing tlist evaluation till after the Sort: it ensures
6689 : : * a consistent order of evaluation for any volatile functions in the tlist,
6690 : : * and if there's also a LIMIT, we can stop the query without ever computing
6691 : : * tlist functions for later rows, which is beneficial for both volatile and
6692 : : * expensive functions.
6693 : : *
6694 : : * Our current policy is to postpone volatile expressions till after the sort
6695 : : * unconditionally (assuming that that's possible, ie they are in plain tlist
6696 : : * columns and not ORDER BY/GROUP BY/DISTINCT columns). We also prefer to
6697 : : * postpone set-returning expressions, because running them beforehand would
6698 : : * bloat the sort dataset, and because it might cause unexpected output order
6699 : : * if the sort isn't stable. However there's a constraint on that: all SRFs
6700 : : * in the tlist should be evaluated at the same plan step, so that they can
6701 : : * run in sync in nodeProjectSet. So if any SRFs are in sort columns, we
6702 : : * mustn't postpone any SRFs. (Note that in principle that policy should
6703 : : * probably get applied to the group/window input targetlists too, but we
6704 : : * have not done that historically.) Lastly, expensive expressions are
6705 : : * postponed if there is a LIMIT, or if root->tuple_fraction shows that
6706 : : * partial evaluation of the query is possible (if neither is true, we expect
6707 : : * to have to evaluate the expressions for every row anyway), or if there are
6708 : : * any volatile or set-returning expressions (since once we've put in a
6709 : : * projection at all, it won't cost any more to postpone more stuff).
6710 : : *
6711 : : * Another issue that could potentially be considered here is that
6712 : : * evaluating tlist expressions could result in data that's either wider
6713 : : * or narrower than the input Vars, thus changing the volume of data that
6714 : : * has to go through the Sort. However, we usually have only a very bad
6715 : : * idea of the output width of any expression more complex than a Var,
6716 : : * so for now it seems too risky to try to optimize on that basis.
6717 : : *
6718 : : * Note that if we do produce a modified sort-input target, and then the
6719 : : * query ends up not using an explicit Sort, no particular harm is done:
6720 : : * we'll initially use the modified target for the preceding path nodes,
6721 : : * but then change them to the final target with apply_projection_to_path.
6722 : : * Moreover, in such a case the guarantees about evaluation order of
6723 : : * volatile functions still hold, since the rows are sorted already.
6724 : : *
6725 : : * This function has some things in common with make_group_input_target and
6726 : : * make_window_input_target, though the detailed rules for what to do are
6727 : : * different. We never flatten/postpone any grouping or ordering columns;
6728 : : * those are needed before the sort. If we do flatten a particular
6729 : : * expression, we leave Aggref and WindowFunc nodes alone, since those were
6730 : : * computed earlier.
6731 : : *
6732 : : * 'final_target' is the query's final target list (in PathTarget form)
6733 : : * 'have_postponed_srfs' is an output argument, see below
6734 : : *
6735 : : * The result is the PathTarget to be computed by the plan node immediately
6736 : : * below the Sort step (and the Distinct step, if any). This will be
6737 : : * exactly final_target if we decide a projection step wouldn't be helpful.
6738 : : *
6739 : : * In addition, *have_postponed_srfs is set to true if we choose to postpone
6740 : : * any set-returning functions to after the Sort.
6741 : : */
6742 : : static PathTarget *
3732 6743 : 58931 : make_sort_input_target(PlannerInfo *root,
6744 : : PathTarget *final_target,
6745 : : bool *have_postponed_srfs)
6746 : : {
6747 : 58931 : Query *parse = root->parse;
6748 : : PathTarget *input_target;
6749 : : int ncols;
6750 : : bool *col_is_srf;
6751 : : bool *postpone_col;
6752 : : bool have_srf;
6753 : : bool have_volatile;
6754 : : bool have_expensive;
6755 : : bool have_srf_sortcols;
6756 : : bool postpone_srfs;
6757 : : List *postponable_cols;
6758 : : List *postponable_vars;
6759 : : int i;
6760 : : ListCell *lc;
6761 : :
6762 : : /* Shouldn't get here unless query has ORDER BY */
6763 [ - + ]: 58931 : Assert(parse->sortClause);
6764 : :
3265 6765 : 58931 : *have_postponed_srfs = false; /* default result */
6766 : :
6767 : : /* Inspect tlist and collect per-column information */
3732 6768 : 58931 : ncols = list_length(final_target->exprs);
3718 6769 : 58931 : col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
3732 6770 : 58931 : postpone_col = (bool *) palloc0(ncols * sizeof(bool));
3718 6771 : 58931 : have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
6772 : :
3732 6773 : 58931 : i = 0;
6774 [ + - + + : 343154 : foreach(lc, final_target->exprs)
+ + ]
6775 : : {
6776 : 284223 : Expr *expr = (Expr *) lfirst(lc);
6777 : :
6778 : : /*
6779 : : * If the column has a sortgroupref, assume it has to be evaluated
6780 : : * before sorting. Generally such columns would be ORDER BY, GROUP
6781 : : * BY, etc targets. One exception is columns that were removed from
6782 : : * GROUP BY by remove_useless_groupby_columns() ... but those would
6783 : : * only be Vars anyway. There don't seem to be any cases where it
6784 : : * would be worth the trouble to double-check.
6785 : : */
3638 6786 [ + - + + ]: 284223 : if (get_pathtarget_sortgroupref(final_target, i) == 0)
6787 : : {
6788 : : /*
6789 : : * Check for SRF or volatile functions. Check the SRF case first
6790 : : * because we must know whether we have any postponed SRFs.
6791 : : */
3546 6792 [ + + + + ]: 200930 : if (parse->hasTargetSRFs &&
6793 : 180 : expression_returns_set((Node *) expr))
6794 : : {
6795 : : /* We'll decide below whether these are postponable */
3718 6796 : 80 : col_is_srf[i] = true;
3732 6797 : 80 : have_srf = true;
6798 : : }
6799 [ + + ]: 200670 : else if (contain_volatile_functions((Node *) expr))
6800 : : {
6801 : : /* Unconditionally postpone */
6802 : 185 : postpone_col[i] = true;
6803 : 185 : have_volatile = true;
6804 : : }
6805 : : else
6806 : : {
6807 : : /*
6808 : : * Else check the cost. XXX it's annoying to have to do this
6809 : : * when set_pathtarget_cost_width() just did it. Refactor to
6810 : : * allow sharing the work?
6811 : : */
6812 : : QualCost cost;
6813 : :
6814 : 200485 : cost_qual_eval_node(&cost, (Node *) expr, root);
6815 : :
6816 : : /*
6817 : : * We arbitrarily define "expensive" as "more than 10X
6818 : : * cpu_operator_cost". Note this will take in any PL function
6819 : : * with default cost.
6820 : : */
6821 [ + + ]: 200485 : if (cost.per_tuple > 10 * cpu_operator_cost)
6822 : : {
6823 : 14350 : postpone_col[i] = true;
6824 : 14350 : have_expensive = true;
6825 : : }
6826 : : }
6827 : : }
6828 : : else
6829 : : {
6830 : : /* For sortgroupref cols, just check if any contain SRFs */
3718 6831 [ + + ]: 83473 : if (!have_srf_sortcols &&
3546 6832 [ + + + + ]: 83730 : parse->hasTargetSRFs &&
3718 6833 : 277 : expression_returns_set((Node *) expr))
6834 : 122 : have_srf_sortcols = true;
6835 : : }
6836 : :
3732 6837 : 284223 : i++;
6838 : : }
6839 : :
6840 : : /*
6841 : : * We can postpone SRFs if we have some but none are in sortgroupref cols.
6842 : : */
3718 6843 [ + + + + ]: 58931 : postpone_srfs = (have_srf && !have_srf_sortcols);
6844 : :
6845 : : /*
6846 : : * If we don't need a post-sort projection, just return final_target.
6847 : : */
6848 [ + + + + ]: 58931 : if (!(postpone_srfs || have_volatile ||
3732 6849 [ + + ]: 58698 : (have_expensive &&
6850 [ + + + - ]: 8596 : (parse->limitCount || root->tuple_fraction > 0))))
6851 : 58668 : return final_target;
6852 : :
6853 : : /*
6854 : : * Report whether the post-sort projection will contain set-returning
6855 : : * functions. This is important because it affects whether the Sort can
6856 : : * rely on the query's LIMIT (if any) to bound the number of rows it needs
6857 : : * to return.
6858 : : */
3718 6859 : 263 : *have_postponed_srfs = postpone_srfs;
6860 : :
6861 : : /*
6862 : : * Construct the sort-input target, taking all non-postponable columns and
6863 : : * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
6864 : : * the postponable ones.
6865 : : */
3732 6866 : 263 : input_target = create_empty_pathtarget();
6867 : 263 : postponable_cols = NIL;
6868 : :
6869 : 263 : i = 0;
6870 [ + - + + : 1855 : foreach(lc, final_target->exprs)
+ + ]
6871 : : {
6872 : 1592 : Expr *expr = (Expr *) lfirst(lc);
6873 : :
3718 6874 [ + + + + : 1592 : if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
+ + ]
3732 6875 : 315 : postponable_cols = lappend(postponable_cols, expr);
6876 : : else
6877 : 1277 : add_column_to_pathtarget(input_target, expr,
3265 6878 [ + - ]: 1277 : get_pathtarget_sortgroupref(final_target, i));
6879 : :
3732 6880 : 1592 : i++;
6881 : : }
6882 : :
6883 : : /*
6884 : : * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
6885 : : * postponable columns, and add them to the sort-input target if not
6886 : : * already present. (Some might be there already.) We mustn't
6887 : : * deconstruct Aggrefs or WindowFuncs here, since the projection node
6888 : : * would be unable to recompute them.
6889 : : */
6890 : 263 : postponable_vars = pull_var_clause((Node *) postponable_cols,
6891 : : PVC_INCLUDE_AGGREGATES |
6892 : : PVC_INCLUDE_WINDOWFUNCS |
6893 : : PVC_INCLUDE_PLACEHOLDERS);
6894 : 263 : add_new_columns_to_pathtarget(input_target, postponable_vars);
6895 : :
6896 : : /* clean up cruft */
6897 : 263 : list_free(postponable_vars);
6898 : 263 : list_free(postponable_cols);
6899 : :
6900 : : /* XXX this represents even more redundant cost calculation ... */
6901 : 263 : return set_pathtarget_cost_width(root, input_target);
6902 : : }
6903 : :
6904 : : /*
6905 : : * get_cheapest_fractional_path
6906 : : * Find the cheapest path for retrieving a specified fraction of all
6907 : : * the tuples expected to be returned by the given relation.
6908 : : *
6909 : : * Do not consider parameterized paths. If the caller needs a path for upper
6910 : : * rel, it can't have parameterized paths. If the caller needs an append
6911 : : * subpath, it could become limited by the treatment of similar
6912 : : * parameterization of all the subpaths.
6913 : : *
6914 : : * We interpret tuple_fraction the same way as grouping_planner.
6915 : : *
6916 : : * We assume set_cheapest() has been run on the given rel.
6917 : : */
6918 : : Path *
3736 6919 : 364342 : get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
6920 : : {
6921 : 364342 : Path *best_path = rel->cheapest_total_path;
6922 : : ListCell *l;
6923 : :
6924 : : /* If all tuples will be retrieved, just return the cheapest-total path */
6925 [ + + ]: 364342 : if (tuple_fraction <= 0.0)
6926 : 357314 : return best_path;
6927 : :
6928 : : /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
3717 6929 [ + + + + ]: 7028 : if (tuple_fraction >= 1.0 && best_path->rows > 0)
3736 6930 : 3064 : tuple_fraction /= best_path->rows;
6931 : :
6932 [ + - + + : 17773 : foreach(l, rel->pathlist)
+ + ]
6933 : : {
6934 : 10745 : Path *path = (Path *) lfirst(l);
6935 : :
446 akorotkov@postgresql 6936 [ + + ]: 10745 : if (path->param_info)
6937 : 166 : continue;
6938 : :
3736 tgl@sss.pgh.pa.us 6939 [ + + + + ]: 14130 : if (path == rel->cheapest_total_path ||
3265 6940 : 3551 : compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
3736 6941 : 10258 : continue;
6942 : :
6943 : 321 : best_path = path;
6944 : : }
6945 : :
6946 : 7028 : return best_path;
6947 : : }
6948 : :
6949 : : /*
6950 : : * adjust_paths_for_srfs
6951 : : * Fix up the Paths of the given upperrel to handle tSRFs properly.
6952 : : *
6953 : : * The executor can only handle set-returning functions that appear at the
6954 : : * top level of the targetlist of a ProjectSet plan node. If we have any SRFs
6955 : : * that are not at top level, we need to split up the evaluation into multiple
6956 : : * plan levels in which each level satisfies this constraint. This function
6957 : : * modifies each Path of an upperrel that (might) compute any SRFs in its
6958 : : * output tlist to insert appropriate projection steps.
6959 : : *
6960 : : * The given targets and targets_contain_srfs lists are from
6961 : : * split_pathtarget_at_srfs(). We assume the existing Paths emit the first
6962 : : * target in targets.
6963 : : */
6964 : : static void
3419 andres@anarazel.de 6965 : 10895 : adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
6966 : : List *targets, List *targets_contain_srfs)
6967 : : {
6968 : : ListCell *lc;
6969 : :
6970 [ - + ]: 10895 : Assert(list_length(targets) == list_length(targets_contain_srfs));
6971 [ - + ]: 10895 : Assert(!linitial_int(targets_contain_srfs));
6972 : :
6973 : : /* If no SRFs appear at this plan level, nothing to do */
6974 [ + + ]: 10895 : if (list_length(targets) == 1)
6975 : 491 : return;
6976 : :
6977 : : /*
6978 : : * Stack SRF-evaluation nodes atop each path for the rel.
6979 : : *
6980 : : * In principle we should re-run set_cheapest() here to identify the
6981 : : * cheapest path, but it seems unlikely that adding the same tlist eval
6982 : : * costs to all the paths would change that, so we don't bother. Instead,
6983 : : * just assume that the cheapest-startup and cheapest-total paths remain
6984 : : * so. (There should be no parameterized paths anymore, so we needn't
6985 : : * worry about updating cheapest_parameterized_paths.)
6986 : : */
6987 [ + - + + : 20838 : foreach(lc, rel->pathlist)
+ + ]
6988 : : {
6989 : 10434 : Path *subpath = (Path *) lfirst(lc);
6990 : 10434 : Path *newpath = subpath;
6991 : : ListCell *lc1,
6992 : : *lc2;
6993 : :
6994 [ - + ]: 10434 : Assert(subpath->param_info == NULL);
6995 : 32087 : forboth(lc1, targets, lc2, targets_contain_srfs)
[ + - + +
+ - + + +
+ + - +
+ ]
6996 : : {
3189 tgl@sss.pgh.pa.us 6997 : 21653 : PathTarget *thistarget = lfirst_node(PathTarget, lc1);
3419 andres@anarazel.de 6998 : 21653 : bool contains_srfs = (bool) lfirst_int(lc2);
6999 : :
7000 : : /* If this level doesn't contain SRFs, do regular projection */
7001 [ + + ]: 21653 : if (contains_srfs)
7002 : 10484 : newpath = (Path *) create_set_projection_path(root,
7003 : : rel,
7004 : : newpath,
7005 : : thistarget);
7006 : : else
7007 : 11169 : newpath = (Path *) apply_projection_to_path(root,
7008 : : rel,
7009 : : newpath,
7010 : : thistarget);
7011 : : }
7012 : 10434 : lfirst(lc) = newpath;
7013 [ + + ]: 10434 : if (subpath == rel->cheapest_startup_path)
7014 : 239 : rel->cheapest_startup_path = newpath;
7015 [ + + ]: 10434 : if (subpath == rel->cheapest_total_path)
7016 : 239 : rel->cheapest_total_path = newpath;
7017 : : }
7018 : :
7019 : : /* Likewise for partial paths, if any */
3046 rhaas@postgresql.org 7020 [ + + + + : 10419 : foreach(lc, rel->partial_pathlist)
+ + ]
7021 : : {
7022 : 15 : Path *subpath = (Path *) lfirst(lc);
7023 : 15 : Path *newpath = subpath;
7024 : : ListCell *lc1,
7025 : : *lc2;
7026 : :
7027 [ - + ]: 15 : Assert(subpath->param_info == NULL);
7028 : 60 : forboth(lc1, targets, lc2, targets_contain_srfs)
[ + - + +
+ - + + +
+ + - +
+ ]
7029 : : {
7030 : 45 : PathTarget *thistarget = lfirst_node(PathTarget, lc1);
7031 : 45 : bool contains_srfs = (bool) lfirst_int(lc2);
7032 : :
7033 : : /* If this level doesn't contain SRFs, do regular projection */
7034 [ + + ]: 45 : if (contains_srfs)
7035 : 15 : newpath = (Path *) create_set_projection_path(root,
7036 : : rel,
7037 : : newpath,
7038 : : thistarget);
7039 : : else
7040 : : {
7041 : : /* avoid apply_projection_to_path, in case of multiple refs */
7042 : 30 : newpath = (Path *) create_projection_path(root,
7043 : : rel,
7044 : : newpath,
7045 : : thistarget);
7046 : : }
7047 : : }
7048 : 15 : lfirst(lc) = newpath;
7049 : : }
7050 : : }
7051 : :
7052 : : /*
7053 : : * expression_planner
7054 : : * Perform planner's transformations on a standalone expression.
7055 : : *
7056 : : * Various utility commands need to evaluate expressions that are not part
7057 : : * of a plannable query. They can do so using the executor's regular
7058 : : * expression-execution machinery, but first the expression has to be fed
7059 : : * through here to transform it from parser output to something executable.
7060 : : *
7061 : : * Currently, we disallow sublinks in standalone expressions, so there's no
7062 : : * real "planning" involved here. (That might not always be true though.)
7063 : : * What we must do is run eval_const_expressions to ensure that any function
7064 : : * calls are converted to positional notation and function default arguments
7065 : : * get inserted. The fact that constant subexpressions get simplified is a
7066 : : * side-effect that is useful when the expression will get evaluated more than
7067 : : * once. Also, we must fix operator function IDs.
7068 : : *
7069 : : * This does not return any information about dependencies of the expression.
7070 : : * Hence callers should use the results only for the duration of the current
7071 : : * query. Callers that would like to cache the results for longer should use
7072 : : * expression_planner_with_deps, probably via the plancache.
7073 : : *
7074 : : * Note: this must not make any damaging changes to the passed-in expression
7075 : : * tree. (It would actually be okay to apply fix_opfuncids to it, but since
7076 : : * we first do an expression_tree_mutator-based walk, what is returned will
7077 : : * be a new node tree.) The result is constructed in the current memory
7078 : : * context; beware that this can leak a lot of additional stuff there, too.
7079 : : */
7080 : : Expr *
7081 : 137559 : expression_planner(Expr *expr)
7082 : : {
7083 : : Node *result;
7084 : :
7085 : : /*
7086 : : * Convert named-argument function calls, insert default arguments and
7087 : : * simplify constant subexprs
7088 : : */
7089 : 137559 : result = eval_const_expressions(NULL, (Node *) expr);
7090 : :
7091 : : /* Fill in opfuncid values if missing */
7092 : 137539 : fix_opfuncids(result);
7093 : :
7094 : 137539 : return (Expr *) result;
7095 : : }
7096 : :
7097 : : /*
7098 : : * expression_planner_with_deps
7099 : : * Perform planner's transformations on a standalone expression,
7100 : : * returning expression dependency information along with the result.
7101 : : *
7102 : : * This is identical to expression_planner() except that it also returns
7103 : : * information about possible dependencies of the expression, ie identities of
7104 : : * objects whose definitions affect the result. As in a PlannedStmt, these
7105 : : * are expressed as a list of relation Oids and a list of PlanInvalItems.
7106 : : */
7107 : : Expr *
2725 tgl@sss.pgh.pa.us 7108 : 267 : expression_planner_with_deps(Expr *expr,
7109 : : List **relationOids,
7110 : : List **invalItems)
7111 : : {
7112 : : Node *result;
7113 : : PlannerGlobal glob;
7114 : : PlannerInfo root;
7115 : :
7116 : : /* Make up dummy planner state so we can use setrefs machinery */
7117 [ + - + - : 7743 : MemSet(&glob, 0, sizeof(glob));
+ - + - +
+ ]
7118 : 267 : glob.type = T_PlannerGlobal;
7119 : 267 : glob.relationOids = NIL;
7120 : 267 : glob.invalItems = NIL;
7121 : :
7122 [ + - + - : 25098 : MemSet(&root, 0, sizeof(root));
+ - + - +
+ ]
7123 : 267 : root.type = T_PlannerInfo;
7124 : 267 : root.glob = &glob;
7125 : :
7126 : : /*
7127 : : * Convert named-argument function calls, insert default arguments and
7128 : : * simplify constant subexprs. Collect identities of inlined functions
7129 : : * and elided domains, too.
7130 : : */
7131 : 267 : result = eval_const_expressions(&root, (Node *) expr);
7132 : :
7133 : : /* Fill in opfuncid values if missing */
7134 : 267 : fix_opfuncids(result);
7135 : :
7136 : : /*
7137 : : * Now walk the finished expression to find anything else we ought to
7138 : : * record as an expression dependency.
7139 : : */
7140 : 267 : (void) extract_query_dependencies_walker(result, &root);
7141 : :
7142 : 267 : *relationOids = glob.relationOids;
7143 : 267 : *invalItems = glob.invalItems;
7144 : :
7145 : 267 : return (Expr *) result;
7146 : : }
7147 : :
7148 : :
7149 : : /*
7150 : : * plan_cluster_use_sort
7151 : : * Use the planner to decide how CLUSTER should implement sorting
7152 : : *
7153 : : * tableOid is the OID of a table to be clustered on its index indexOid
7154 : : * (which is already known to be a btree index). Decide whether it's
7155 : : * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
7156 : : * Return true to use sorting, false to use an indexscan.
7157 : : *
7158 : : * Note: caller had better already hold some type of lock on the table.
7159 : : */
7160 : : bool
3046 rhaas@postgresql.org 7161 : 144 : plan_cluster_use_sort(Oid tableOid, Oid indexOid)
7162 : : {
7163 : : PlannerInfo *root;
7164 : : Query *query;
7165 : : PlannerGlobal *glob;
7166 : : RangeTblEntry *rte;
7167 : : RelOptInfo *rel;
7168 : : IndexOptInfo *indexInfo;
7169 : : QualCost indexExprCost;
7170 : : Cost comparisonCost;
7171 : : Path *seqScanPath;
7172 : : Path seqScanAndSortPath;
7173 : : IndexPath *indexScanPath;
7174 : : ListCell *lc;
7175 : :
7176 : : /* We can short-circuit the cost comparison if indexscans are disabled */
7177 [ + + ]: 144 : if (!enable_indexscan)
7178 : 20 : return true; /* use sort */
7179 : :
7180 : : /* Set up mostly-dummy planner state */
7181 : 124 : query = makeNode(Query);
7182 : 124 : query->commandType = CMD_SELECT;
7183 : :
7184 : 124 : glob = makeNode(PlannerGlobal);
7185 : :
7186 : 124 : root = makeNode(PlannerInfo);
7187 : 124 : root->parse = query;
7188 : 124 : root->glob = glob;
7189 : 124 : root->query_level = 1;
7190 : 124 : root->planner_cxt = CurrentMemoryContext;
7191 : 124 : root->wt_param_id = -1;
1216 tgl@sss.pgh.pa.us 7192 : 124 : root->join_domains = list_make1(makeNode(JoinDomain));
7193 : :
7194 : : /* Build a minimal RTE for the rel */
3046 rhaas@postgresql.org 7195 : 124 : rte = makeNode(RangeTblEntry);
7196 : 124 : rte->rtekind = RTE_RELATION;
7197 : 124 : rte->relid = tableOid;
7198 : 124 : rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
2799 tgl@sss.pgh.pa.us 7199 : 124 : rte->rellockmode = AccessShareLock;
3046 rhaas@postgresql.org 7200 : 124 : rte->lateral = false;
7201 : 124 : rte->inh = false;
7202 : 124 : rte->inFromCl = true;
7203 : 124 : query->rtable = list_make1(rte);
1271 alvherre@alvh.no-ip. 7204 : 124 : addRTEPermissionInfo(&query->rteperminfos, rte);
7205 : :
7206 : : /* Set up RTE/RelOptInfo arrays */
3046 rhaas@postgresql.org 7207 : 124 : setup_simple_rel_arrays(root);
7208 : :
7209 : : /* Build RelOptInfo */
7210 : 124 : rel = build_simple_rel(root, 1, NULL);
7211 : :
7212 : : /* Locate IndexOptInfo for the target index */
7213 : 124 : indexInfo = NULL;
7214 [ + - + - : 154 : foreach(lc, rel->indexlist)
+ - ]
7215 : : {
7216 : 154 : indexInfo = lfirst_node(IndexOptInfo, lc);
7217 [ + + ]: 154 : if (indexInfo->indexoid == indexOid)
7218 : 124 : break;
7219 : : }
7220 : :
7221 : : /*
7222 : : * It's possible that get_relation_info did not generate an IndexOptInfo
7223 : : * for the desired index; this could happen if it's not yet reached its
7224 : : * indcheckxmin usability horizon, or if it's a system index and we're
7225 : : * ignoring system indexes. In such cases we should tell CLUSTER to not
7226 : : * trust the index contents but use seqscan-and-sort.
7227 : : */
7228 [ - + ]: 124 : if (lc == NULL) /* not in the list? */
3046 rhaas@postgresql.org 7229 :UBC 0 : return true; /* use sort */
7230 : :
7231 : : /*
7232 : : * Rather than doing all the pushups that would be needed to use
7233 : : * set_baserel_size_estimates, just do a quick hack for rows and width.
7234 : : */
3046 rhaas@postgresql.org 7235 :CBC 124 : rel->rows = rel->tuples;
7236 : 124 : rel->reltarget->width = get_relation_data_width(tableOid, NULL);
7237 : :
7238 : 124 : root->total_table_pages = rel->pages;
7239 : :
7240 : : /*
7241 : : * Determine eval cost of the index expressions, if any. We need to
7242 : : * charge twice that amount for each tuple comparison that happens during
7243 : : * the sort, since tuplesort.c will have to re-evaluate the index
7244 : : * expressions each time. (XXX that's pretty inefficient...)
7245 : : */
7246 : 124 : cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
7247 : 124 : comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
7248 : :
7249 : : /* Estimate the cost of seq scan + sort */
7250 : 124 : seqScanPath = create_seqscan_path(root, rel, NULL, 0);
7251 : 124 : cost_sort(&seqScanAndSortPath, root, NIL,
7252 : : seqScanPath->disabled_nodes,
7253 : 124 : seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
7254 : : comparisonCost, maintenance_work_mem, -1.0);
7255 : :
7256 : : /* Estimate the cost of index scan */
7257 : 124 : indexScanPath = create_index_path(root, indexInfo,
7258 : : NIL, NIL, NIL, NIL,
7259 : : ForwardScanDirection, false,
7260 : : NULL, 1.0, false);
7261 : :
7262 : 124 : return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
7263 : : }
7264 : :
7265 : : /*
7266 : : * plan_create_index_workers
7267 : : * Use the planner to decide how many parallel worker processes
7268 : : * CREATE INDEX should request for use
7269 : : *
7270 : : * tableOid is the table on which the index is to be built. indexOid is the
7271 : : * OID of an index to be created or reindexed (which must be an index with
7272 : : * support for parallel builds - currently btree, GIN, or BRIN).
7273 : : *
7274 : : * Return value is the number of parallel worker processes to request. It
7275 : : * may be unsafe to proceed if this is 0. Note that this does not include the
7276 : : * leader participating as a worker (value is always a number of parallel
7277 : : * worker processes).
7278 : : *
7279 : : * Note: caller had better already hold some type of lock on the table and
7280 : : * index.
7281 : : */
7282 : : int
3039 7283 : 23037 : plan_create_index_workers(Oid tableOid, Oid indexOid)
7284 : : {
7285 : : PlannerInfo *root;
7286 : : Query *query;
7287 : : PlannerGlobal *glob;
7288 : : RangeTblEntry *rte;
7289 : : Relation heap;
7290 : : Relation index;
7291 : : RelOptInfo *rel;
7292 : : int parallel_workers;
7293 : : BlockNumber heap_blocks;
7294 : : double reltuples;
7295 : : double allvisfrac;
7296 : :
7297 : : /*
7298 : : * We don't allow performing parallel operation in standalone backend or
7299 : : * when parallelism is disabled.
7300 : : */
2007 tgl@sss.pgh.pa.us 7301 [ + + + + ]: 23037 : if (!IsUnderPostmaster || max_parallel_maintenance_workers == 0)
3039 rhaas@postgresql.org 7302 : 301 : return 0;
7303 : :
7304 : : /* Set up largely-dummy planner state */
7305 : 22736 : query = makeNode(Query);
7306 : 22736 : query->commandType = CMD_SELECT;
7307 : :
7308 : 22736 : glob = makeNode(PlannerGlobal);
7309 : :
7310 : 22736 : root = makeNode(PlannerInfo);
7311 : 22736 : root->parse = query;
7312 : 22736 : root->glob = glob;
7313 : 22736 : root->query_level = 1;
7314 : 22736 : root->planner_cxt = CurrentMemoryContext;
7315 : 22736 : root->wt_param_id = -1;
1216 tgl@sss.pgh.pa.us 7316 : 22736 : root->join_domains = list_make1(makeNode(JoinDomain));
7317 : :
7318 : : /*
7319 : : * Build a minimal RTE.
7320 : : *
7321 : : * Mark the RTE with inh = true. This is a kludge to prevent
7322 : : * get_relation_info() from fetching index info, which is necessary
7323 : : * because it does not expect that any IndexOptInfo is currently
7324 : : * undergoing REINDEX.
7325 : : */
3039 rhaas@postgresql.org 7326 : 22736 : rte = makeNode(RangeTblEntry);
7327 : 22736 : rte->rtekind = RTE_RELATION;
7328 : 22736 : rte->relid = tableOid;
7329 : 22736 : rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
2799 tgl@sss.pgh.pa.us 7330 : 22736 : rte->rellockmode = AccessShareLock;
3039 rhaas@postgresql.org 7331 : 22736 : rte->lateral = false;
7332 : 22736 : rte->inh = true;
7333 : 22736 : rte->inFromCl = true;
7334 : 22736 : query->rtable = list_make1(rte);
1271 alvherre@alvh.no-ip. 7335 : 22736 : addRTEPermissionInfo(&query->rteperminfos, rte);
7336 : :
7337 : : /* Set up RTE/RelOptInfo arrays */
3039 rhaas@postgresql.org 7338 : 22736 : setup_simple_rel_arrays(root);
7339 : :
7340 : : /* Build RelOptInfo */
7341 : 22736 : rel = build_simple_rel(root, 1, NULL);
7342 : :
7343 : : /* Rels are assumed already locked by the caller */
2686 andres@anarazel.de 7344 : 22736 : heap = table_open(tableOid, NoLock);
3039 rhaas@postgresql.org 7345 : 22736 : index = index_open(indexOid, NoLock);
7346 : :
7347 : : /*
7348 : : * Determine if it's safe to proceed.
7349 : : *
7350 : : * Currently, parallel workers can't access the leader's temporary tables.
7351 : : * Furthermore, any index predicate or index expressions must be parallel
7352 : : * safe.
7353 : : */
7354 [ + + ]: 22736 : if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
814 michael@paquier.xyz 7355 [ + + ]: 21342 : !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index)) ||
7356 [ - + ]: 21252 : !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index)))
7357 : : {
3039 rhaas@postgresql.org 7358 : 1484 : parallel_workers = 0;
7359 : 1484 : goto done;
7360 : : }
7361 : :
7362 : : /*
7363 : : * If parallel_workers storage parameter is set for the table, accept that
7364 : : * as the number of parallel worker processes to launch (though still cap
7365 : : * at max_parallel_maintenance_workers). Note that we deliberately do not
7366 : : * consider any other factor when parallel_workers is set. (e.g., memory
7367 : : * use by workers.)
7368 : : */
7369 [ + + ]: 21252 : if (rel->rel_parallel_workers != -1)
7370 : : {
7371 : 57 : parallel_workers = Min(rel->rel_parallel_workers,
7372 : : max_parallel_maintenance_workers);
7373 : 57 : goto done;
7374 : : }
7375 : :
7376 : : /*
7377 : : * Estimate heap relation size ourselves, since rel->pages cannot be
7378 : : * trusted (heap RTE was marked as inheritance parent)
7379 : : */
7380 : 21195 : estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
7381 : :
7382 : : /*
7383 : : * Determine number of workers to scan the heap relation using generic
7384 : : * model
7385 : : */
7386 : 21195 : parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
7387 : : max_parallel_maintenance_workers);
7388 : :
7389 : : /*
7390 : : * Cap workers based on available maintenance_work_mem as needed.
7391 : : *
7392 : : * Note that each tuplesort participant receives an even share of the
7393 : : * total maintenance_work_mem budget. Aim to leave participants
7394 : : * (including the leader as a participant) with no less than 32MB of
7395 : : * memory. This leaves cases where maintenance_work_mem is set to 64MB
7396 : : * immediately past the threshold of being capable of launching a single
7397 : : * parallel worker to sort.
7398 : : */
7399 [ + + ]: 21304 : while (parallel_workers > 0 &&
484 tgl@sss.pgh.pa.us 7400 [ + + ]: 219 : maintenance_work_mem / (parallel_workers + 1) < 32 * 1024)
3039 rhaas@postgresql.org 7401 : 109 : parallel_workers--;
7402 : :
7403 : 21195 : done:
7404 : 22736 : index_close(index, NoLock);
2686 andres@anarazel.de 7405 : 22736 : table_close(heap, NoLock);
7406 : :
3039 rhaas@postgresql.org 7407 : 22736 : return parallel_workers;
7408 : : }
7409 : :
7410 : : /*
7411 : : * add_paths_to_grouping_rel
7412 : : *
7413 : : * Add non-partial paths to grouping relation.
7414 : : */
7415 : : static void
3046 7416 : 35294 : add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
7417 : : RelOptInfo *grouped_rel,
7418 : : RelOptInfo *partially_grouped_rel,
7419 : : const AggClauseCosts *agg_costs,
7420 : : grouping_sets_data *gd,
7421 : : GroupPathExtraData *extra)
7422 : : {
7423 : 35294 : Query *parse = root->parse;
7424 : 35294 : Path *cheapest_path = input_rel->cheapest_total_path;
234 rguo@postgresql.org 7425 :GNC 35294 : Path *cheapest_partially_grouped_path = NULL;
7426 : : ListCell *lc;
2991 rhaas@postgresql.org 7427 :CBC 35294 : bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7428 : 35294 : bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7429 : 35294 : List *havingQual = (List *) extra->havingQual;
7430 : 35294 : AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
234 rguo@postgresql.org 7431 :GNC 35294 : double dNumGroups = 0;
7432 : 35294 : double dNumFinalGroups = 0;
7433 : :
7434 : : /*
7435 : : * Estimate number of groups for non-split aggregation.
7436 : : */
7437 : 35294 : dNumGroups = get_number_of_groups(root,
7438 : : cheapest_path->rows,
7439 : : gd,
7440 : : extra->targetList);
7441 : :
7442 [ + + + - ]: 35294 : if (partially_grouped_rel && partially_grouped_rel->pathlist)
7443 : : {
7444 : 2492 : cheapest_partially_grouped_path =
7445 : : partially_grouped_rel->cheapest_total_path;
7446 : :
7447 : : /*
7448 : : * Estimate number of groups for final phase of partial aggregation.
7449 : : */
7450 : : dNumFinalGroups =
7451 : 2492 : get_number_of_groups(root,
7452 : : cheapest_partially_grouped_path->rows,
7453 : : gd,
7454 : : extra->targetList);
7455 : : }
7456 : :
3046 rhaas@postgresql.org 7457 [ + + ]:CBC 35294 : if (can_sort)
7458 : : {
7459 : : /*
7460 : : * Use any available suitably-sorted path as input, and also consider
7461 : : * sorting the cheapest-total path and incremental sort on any paths
7462 : : * with presorted keys.
7463 : : */
7464 [ + - + + : 73164 : foreach(lc, input_rel->pathlist)
+ + ]
7465 : : {
7466 : : ListCell *lc2;
7467 : 37875 : Path *path = (Path *) lfirst(lc);
860 akorotkov@postgresql 7468 : 37875 : Path *path_save = path;
7469 : 37875 : List *pathkey_orderings = NIL;
7470 : :
7471 : : /* generate alternative group orderings that might be useful */
7472 : 37875 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7473 : :
7474 [ - + ]: 37875 : Assert(list_length(pathkey_orderings) > 0);
7475 : :
7476 [ + - + + : 75867 : foreach(lc2, pathkey_orderings)
+ + ]
7477 : : {
723 7478 : 37992 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7479 : :
7480 : : /* restore the path (we replace it in the loop) */
860 7481 : 37992 : path = path_save;
7482 : :
7483 : 37992 : path = make_ordered_path(root,
7484 : : grouped_rel,
7485 : : path,
7486 : : cheapest_path,
7487 : : info->pathkeys,
7488 : : -1.0);
7489 [ + + ]: 37992 : if (path == NULL)
7490 : 305 : continue;
7491 : :
7492 : : /* Now decide what to stick atop it */
7493 [ + + ]: 37687 : if (parse->groupingSets)
7494 : : {
7495 : 975 : consider_groupingsets_paths(root, grouped_rel,
7496 : : path, true, can_hash,
7497 : : gd, agg_costs, dNumGroups);
7498 : : }
7499 [ + + ]: 36712 : else if (parse->hasAggs)
7500 : : {
7501 : : /*
7502 : : * We have aggregation, possibly with plain GROUP BY. Make
7503 : : * an AggPath.
7504 : : */
1335 tgl@sss.pgh.pa.us 7505 : 36020 : add_path(grouped_rel, (Path *)
7506 : 36020 : create_agg_path(root,
7507 : : grouped_rel,
7508 : : path,
7509 : 36020 : grouped_rel->reltarget,
7510 : 36020 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7511 : : AGGSPLIT_SIMPLE,
7512 : : info->clauses,
7513 : : havingQual,
7514 : : agg_costs,
7515 : : dNumGroups));
7516 : : }
860 akorotkov@postgresql 7517 [ + - ]: 692 : else if (parse->groupClause)
7518 : : {
7519 : : /*
7520 : : * We have GROUP BY without aggregation or grouping sets.
7521 : : * Make a GroupPath.
7522 : : */
1335 tgl@sss.pgh.pa.us 7523 : 692 : add_path(grouped_rel, (Path *)
7524 : 692 : create_group_path(root,
7525 : : grouped_rel,
7526 : : path,
7527 : : info->clauses,
7528 : : havingQual,
7529 : : dNumGroups));
7530 : : }
7531 : : else
7532 : : {
7533 : : /* Other cases should have been handled above */
860 akorotkov@postgresql 7534 :UBC 0 : Assert(false);
7535 : : }
7536 : : }
7537 : : }
7538 : :
7539 : : /*
7540 : : * Instead of operating directly on the input relation, we can
7541 : : * consider finalizing a partially aggregated path.
7542 : : */
860 akorotkov@postgresql 7543 [ + + ]:CBC 35289 : if (partially_grouped_rel != NULL)
7544 : : {
7545 [ + - + + : 6420 : foreach(lc, partially_grouped_rel->pathlist)
+ + ]
7546 : : {
7547 : : ListCell *lc2;
7548 : 3928 : Path *path = (Path *) lfirst(lc);
7549 : 3928 : Path *path_save = path;
7550 : 3928 : List *pathkey_orderings = NIL;
7551 : :
7552 : : /* generate alternative group orderings that might be useful */
7553 : 3928 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7554 : :
7555 [ - + ]: 3928 : Assert(list_length(pathkey_orderings) > 0);
7556 : :
7557 : : /* process all potentially interesting grouping reorderings */
7558 [ + - + + : 7856 : foreach(lc2, pathkey_orderings)
+ + ]
7559 : : {
723 7560 : 3928 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7561 : :
7562 : : /* restore the path (we replace it in the loop) */
860 7563 : 3928 : path = path_save;
7564 : :
7565 : 3928 : path = make_ordered_path(root,
7566 : : grouped_rel,
7567 : : path,
7568 : : cheapest_partially_grouped_path,
7569 : : info->pathkeys,
7570 : : -1.0);
7571 : :
7572 [ + + ]: 3928 : if (path == NULL)
7573 : 172 : continue;
7574 : :
7575 [ + + ]: 3756 : if (parse->hasAggs)
7576 : 3554 : add_path(grouped_rel, (Path *)
7577 : 3554 : create_agg_path(root,
7578 : : grouped_rel,
7579 : : path,
7580 : 3554 : grouped_rel->reltarget,
7581 : 3554 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7582 : : AGGSPLIT_FINAL_DESERIAL,
7583 : : info->clauses,
7584 : : havingQual,
7585 : : agg_final_costs,
7586 : : dNumFinalGroups));
7587 : : else
7588 : 202 : add_path(grouped_rel, (Path *)
7589 : 202 : create_group_path(root,
7590 : : grouped_rel,
7591 : : path,
7592 : : info->clauses,
7593 : : havingQual,
7594 : : dNumFinalGroups));
7595 : :
7596 : : }
7597 : : }
7598 : : }
7599 : : }
7600 : :
3046 rhaas@postgresql.org 7601 [ + + ]: 35294 : if (can_hash)
7602 : : {
7603 [ + + ]: 5120 : if (parse->groupingSets)
7604 : : {
7605 : : /*
7606 : : * Try for a hash-only groupingsets path over unsorted input.
7607 : : */
7608 : 807 : consider_groupingsets_paths(root, grouped_rel,
7609 : : cheapest_path, false, true,
7610 : : gd, agg_costs, dNumGroups);
7611 : : }
7612 : : else
7613 : : {
7614 : : /*
7615 : : * Generate a HashAgg Path. We just need an Agg over the
7616 : : * cheapest-total input path, since input order won't matter.
7617 : : */
2133 pg@bowt.ie 7618 : 4313 : add_path(grouped_rel, (Path *)
7619 : 4313 : create_agg_path(root, grouped_rel,
7620 : : cheapest_path,
7621 : 4313 : grouped_rel->reltarget,
7622 : : AGG_HASHED,
7623 : : AGGSPLIT_SIMPLE,
7624 : : root->processed_groupClause,
7625 : : havingQual,
7626 : : agg_costs,
7627 : : dNumGroups));
7628 : : }
7629 : :
7630 : : /*
7631 : : * Generate a Finalize HashAgg Path atop of the cheapest partially
7632 : : * grouped path, assuming there is one
7633 : : */
2993 rhaas@postgresql.org 7634 [ + + + - ]: 5120 : if (partially_grouped_rel && partially_grouped_rel->pathlist)
7635 : : {
2133 pg@bowt.ie 7636 : 1182 : add_path(grouped_rel, (Path *)
7637 : 1182 : create_agg_path(root,
7638 : : grouped_rel,
7639 : : cheapest_partially_grouped_path,
7640 : 1182 : grouped_rel->reltarget,
7641 : : AGG_HASHED,
7642 : : AGGSPLIT_FINAL_DESERIAL,
7643 : : root->processed_groupClause,
7644 : : havingQual,
7645 : : agg_final_costs,
7646 : : dNumFinalGroups));
7647 : : }
7648 : : }
7649 : :
7650 : : /*
7651 : : * When partitionwise aggregate is used, we might have fully aggregated
7652 : : * paths in the partial pathlist, because add_paths_to_append_rel() will
7653 : : * consider a path for grouped_rel consisting of a Parallel Append of
7654 : : * non-partial paths from each child.
7655 : : */
2991 rhaas@postgresql.org 7656 [ + + ]: 35294 : if (grouped_rel->partial_pathlist != NIL)
7657 : 265 : gather_grouping_paths(root, grouped_rel);
5714 tgl@sss.pgh.pa.us 7658 : 35294 : }
7659 : :
7660 : : /*
7661 : : * create_partial_grouping_paths
7662 : : *
7663 : : * Create a new upper relation representing the result of partial aggregation
7664 : : * and populate it with appropriate paths. Note that we don't finalize the
7665 : : * lists of paths here, so the caller can add additional partial or non-partial
7666 : : * paths and must afterward call gather_grouping_paths and set_cheapest on
7667 : : * the returned upper relation.
7668 : : *
7669 : : * All paths for this new upper relation -- both partial and non-partial --
7670 : : * have been partially aggregated but require a subsequent FinalizeAggregate
7671 : : * step.
7672 : : *
7673 : : * NB: This function is allowed to return NULL if it determines that there is
7674 : : * no real need to create a new RelOptInfo.
7675 : : */
7676 : : static RelOptInfo *
2993 rhaas@postgresql.org 7677 : 31818 : create_partial_grouping_paths(PlannerInfo *root,
7678 : : RelOptInfo *grouped_rel,
7679 : : RelOptInfo *input_rel,
7680 : : grouping_sets_data *gd,
7681 : : GroupPathExtraData *extra,
7682 : : bool force_rel_creation)
7683 : : {
3046 7684 : 31818 : Query *parse = root->parse;
7685 : : RelOptInfo *partially_grouped_rel;
234 rguo@postgresql.org 7686 :GNC 31818 : RelOptInfo *eager_agg_rel = NULL;
2991 rhaas@postgresql.org 7687 :CBC 31818 : AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
7688 : 31818 : AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
7689 : 31818 : Path *cheapest_partial_path = NULL;
7690 : 31818 : Path *cheapest_total_path = NULL;
3046 7691 : 31818 : double dNumPartialGroups = 0;
2991 7692 : 31818 : double dNumPartialPartialGroups = 0;
7693 : : ListCell *lc;
7694 : 31818 : bool can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
7695 : 31818 : bool can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
7696 : :
7697 : : /*
7698 : : * Check whether any partially aggregated paths have been generated
7699 : : * through eager aggregation.
7700 : : */
234 rguo@postgresql.org 7701 [ + + ]:GNC 31818 : if (input_rel->grouped_rel &&
7702 [ + - ]: 777 : !IS_DUMMY_REL(input_rel->grouped_rel) &&
7703 [ + + ]: 777 : input_rel->grouped_rel->pathlist != NIL)
7704 : 727 : eager_agg_rel = input_rel->grouped_rel;
7705 : :
7706 : : /*
7707 : : * Consider whether we should generate partially aggregated non-partial
7708 : : * paths. We can only do this if we have a non-partial path, and only if
7709 : : * the parent of the input rel is performing partial partitionwise
7710 : : * aggregation. (Note that extra->patype is the type of partitionwise
7711 : : * aggregation being used at the parent level, not this level.)
7712 : : */
2991 rhaas@postgresql.org 7713 [ + - ]:CBC 31818 : if (input_rel->pathlist != NIL &&
7714 [ + + ]: 31818 : extra->patype == PARTITIONWISE_AGGREGATE_PARTIAL)
7715 : 713 : cheapest_total_path = input_rel->cheapest_total_path;
7716 : :
7717 : : /*
7718 : : * If parallelism is possible for grouped_rel, then we should consider
7719 : : * generating partially-grouped partial paths. However, if the input rel
7720 : : * has no partial paths, then we can't.
7721 : : */
7722 [ + + + + ]: 31818 : if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
7723 : 2744 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
7724 : :
7725 : : /*
7726 : : * If we can't partially aggregate partial paths, and we can't partially
7727 : : * aggregate non-partial paths, and no partially aggregated paths were
7728 : : * generated by eager aggregation, then don't bother creating the new
7729 : : * RelOptInfo at all, unless the caller specified force_rel_creation.
7730 : : */
7731 [ + + + + ]: 31818 : if (cheapest_total_path == NULL &&
7732 [ + + ]: 28781 : cheapest_partial_path == NULL &&
234 rguo@postgresql.org 7733 :GNC 28694 : eager_agg_rel == NULL &&
2991 rhaas@postgresql.org 7734 [ + + ]:CBC 28694 : !force_rel_creation)
7735 : 28613 : return NULL;
7736 : :
7737 : : /*
7738 : : * Build a new upper relation to represent the result of partially
7739 : : * aggregating the rows from the input relation.
7740 : : */
2993 7741 : 3205 : partially_grouped_rel = fetch_upper_rel(root,
7742 : : UPPERREL_PARTIAL_GROUP_AGG,
7743 : : grouped_rel->relids);
7744 : 3205 : partially_grouped_rel->consider_parallel =
7745 : 3205 : grouped_rel->consider_parallel;
122 rhaas@postgresql.org 7746 :GNC 3205 : partially_grouped_rel->pgs_mask = grouped_rel->pgs_mask;
2991 rhaas@postgresql.org 7747 :CBC 3205 : partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
2993 7748 : 3205 : partially_grouped_rel->serverid = grouped_rel->serverid;
7749 : 3205 : partially_grouped_rel->userid = grouped_rel->userid;
7750 : 3205 : partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
7751 : 3205 : partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
7752 : :
7753 : : /*
7754 : : * Build target list for partial aggregate paths. These paths cannot just
7755 : : * emit the same tlist as regular aggregate paths, because (1) we must
7756 : : * include Vars and Aggrefs needed in HAVING, which might not appear in
7757 : : * the result tlist, and (2) the Aggrefs must be set in partial mode.
7758 : : */
7759 : 3205 : partially_grouped_rel->reltarget =
7760 : 3205 : make_partial_grouping_target(root, grouped_rel->reltarget,
7761 : : extra->havingQual);
7762 : :
2991 7763 [ + + ]: 3205 : if (!extra->partial_costs_set)
7764 : : {
7765 : : /*
7766 : : * Collect statistics about aggregates for estimating costs of
7767 : : * performing aggregation in parallel.
7768 : : */
7769 [ + - + - : 11532 : MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
+ - + - +
+ ]
7770 [ + - + - : 11532 : MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
+ - + - +
+ ]
7771 [ + + ]: 1922 : if (parse->hasAggs)
7772 : : {
7773 : : /* partial phase */
2013 heikki.linnakangas@i 7774 : 1813 : get_agg_clause_costs(root, AGGSPLIT_INITIAL_SERIAL,
7775 : : agg_partial_costs);
7776 : :
7777 : : /* final phase */
7778 : 1813 : get_agg_clause_costs(root, AGGSPLIT_FINAL_DESERIAL,
7779 : : agg_final_costs);
7780 : : }
7781 : :
2991 rhaas@postgresql.org 7782 : 1922 : extra->partial_costs_set = true;
7783 : : }
7784 : :
7785 : : /* Estimate number of partial groups. */
7786 [ + + ]: 3205 : if (cheapest_total_path != NULL)
7787 : : dNumPartialGroups =
7788 : 713 : get_number_of_groups(root,
7789 : : cheapest_total_path->rows,
7790 : : gd,
7791 : : extra->targetList);
7792 [ + + ]: 3205 : if (cheapest_partial_path != NULL)
7793 : : dNumPartialPartialGroups =
7794 : 2744 : get_number_of_groups(root,
7795 : : cheapest_partial_path->rows,
7796 : : gd,
7797 : : extra->targetList);
7798 : :
7799 [ + - + + ]: 3205 : if (can_sort && cheapest_total_path != NULL)
7800 : : {
7801 : : /* This should have been checked previously */
3046 7802 [ + + - + ]: 713 : Assert(parse->hasAggs || parse->groupClause);
7803 : :
7804 : : /*
7805 : : * Use any available suitably-sorted path as input, and also consider
7806 : : * sorting the cheapest partial path.
7807 : : */
2991 7808 [ + - + + : 1426 : foreach(lc, input_rel->pathlist)
+ + ]
7809 : : {
7810 : : ListCell *lc2;
7811 : 713 : Path *path = (Path *) lfirst(lc);
860 akorotkov@postgresql 7812 : 713 : Path *path_save = path;
7813 : 713 : List *pathkey_orderings = NIL;
7814 : :
7815 : : /* generate alternative group orderings that might be useful */
7816 : 713 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7817 : :
7818 [ - + ]: 713 : Assert(list_length(pathkey_orderings) > 0);
7819 : :
7820 : : /* process all potentially interesting grouping reorderings */
7821 [ + - + + : 1426 : foreach(lc2, pathkey_orderings)
+ + ]
7822 : : {
723 7823 : 713 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7824 : :
7825 : : /* restore the path (we replace it in the loop) */
860 7826 : 713 : path = path_save;
7827 : :
7828 : 713 : path = make_ordered_path(root,
7829 : : partially_grouped_rel,
7830 : : path,
7831 : : cheapest_total_path,
7832 : : info->pathkeys,
7833 : : -1.0);
7834 : :
7835 [ - + ]: 713 : if (path == NULL)
860 akorotkov@postgresql 7836 :UBC 0 : continue;
7837 : :
860 akorotkov@postgresql 7838 [ + + ]:CBC 713 : if (parse->hasAggs)
7839 : 653 : add_path(partially_grouped_rel, (Path *)
7840 : 653 : create_agg_path(root,
7841 : : partially_grouped_rel,
7842 : : path,
7843 : 653 : partially_grouped_rel->reltarget,
7844 : 653 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7845 : : AGGSPLIT_INITIAL_SERIAL,
7846 : : info->clauses,
7847 : : NIL,
7848 : : agg_partial_costs,
7849 : : dNumPartialGroups));
7850 : : else
7851 : 60 : add_path(partially_grouped_rel, (Path *)
7852 : 60 : create_group_path(root,
7853 : : partially_grouped_rel,
7854 : : path,
7855 : : info->clauses,
7856 : : NIL,
7857 : : dNumPartialGroups));
7858 : : }
7859 : : }
7860 : : }
7861 : :
2991 rhaas@postgresql.org 7862 [ + - + + ]: 3205 : if (can_sort && cheapest_partial_path != NULL)
7863 : : {
7864 : : /* Similar to above logic, but for partial paths. */
3046 7865 [ + - + + : 5863 : foreach(lc, input_rel->partial_pathlist)
+ + ]
7866 : : {
7867 : : ListCell *lc2;
7868 : 3119 : Path *path = (Path *) lfirst(lc);
860 akorotkov@postgresql 7869 : 3119 : Path *path_save = path;
7870 : 3119 : List *pathkey_orderings = NIL;
7871 : :
7872 : : /* generate alternative group orderings that might be useful */
7873 : 3119 : pathkey_orderings = get_useful_group_keys_orderings(root, path);
7874 : :
7875 [ - + ]: 3119 : Assert(list_length(pathkey_orderings) > 0);
7876 : :
7877 : : /* process all potentially interesting grouping reorderings */
7878 [ + - + + : 6238 : foreach(lc2, pathkey_orderings)
+ + ]
7879 : : {
723 7880 : 3119 : GroupByOrdering *info = (GroupByOrdering *) lfirst(lc2);
7881 : :
7882 : :
7883 : : /* restore the path (we replace it in the loop) */
860 7884 : 3119 : path = path_save;
7885 : :
7886 : 3119 : path = make_ordered_path(root,
7887 : : partially_grouped_rel,
7888 : : path,
7889 : : cheapest_partial_path,
7890 : : info->pathkeys,
7891 : : -1.0);
7892 : :
7893 [ + + ]: 3119 : if (path == NULL)
7894 : 5 : continue;
7895 : :
7896 [ + + ]: 3114 : if (parse->hasAggs)
7897 : 3015 : add_partial_path(partially_grouped_rel, (Path *)
7898 : 3015 : create_agg_path(root,
7899 : : partially_grouped_rel,
7900 : : path,
7901 : 3015 : partially_grouped_rel->reltarget,
7902 : 3015 : parse->groupClause ? AGG_SORTED : AGG_PLAIN,
7903 : : AGGSPLIT_INITIAL_SERIAL,
7904 : : info->clauses,
7905 : : NIL,
7906 : : agg_partial_costs,
7907 : : dNumPartialPartialGroups));
7908 : : else
7909 : 99 : add_partial_path(partially_grouped_rel, (Path *)
7910 : 99 : create_group_path(root,
7911 : : partially_grouped_rel,
7912 : : path,
7913 : : info->clauses,
7914 : : NIL,
7915 : : dNumPartialPartialGroups));
7916 : : }
7917 : : }
7918 : : }
7919 : :
7920 : : /*
7921 : : * Add a partially-grouped HashAgg Path where possible
7922 : : */
2991 rhaas@postgresql.org 7923 [ + + + + ]: 3205 : if (can_hash && cheapest_total_path != NULL)
7924 : : {
7925 : : /* Checked above */
3046 7926 [ + + - + ]: 713 : Assert(parse->hasAggs || parse->groupClause);
7927 : :
2133 pg@bowt.ie 7928 : 713 : add_path(partially_grouped_rel, (Path *)
7929 : 713 : create_agg_path(root,
7930 : : partially_grouped_rel,
7931 : : cheapest_total_path,
7932 : 713 : partially_grouped_rel->reltarget,
7933 : : AGG_HASHED,
7934 : : AGGSPLIT_INITIAL_SERIAL,
7935 : : root->processed_groupClause,
7936 : : NIL,
7937 : : agg_partial_costs,
7938 : : dNumPartialGroups));
7939 : : }
7940 : :
7941 : : /*
7942 : : * Now add a partially-grouped HashAgg partial Path where possible
7943 : : */
2991 rhaas@postgresql.org 7944 [ + + + + ]: 3205 : if (can_hash && cheapest_partial_path != NULL)
7945 : : {
2133 pg@bowt.ie 7946 : 1434 : add_partial_path(partially_grouped_rel, (Path *)
7947 : 1434 : create_agg_path(root,
7948 : : partially_grouped_rel,
7949 : : cheapest_partial_path,
7950 : 1434 : partially_grouped_rel->reltarget,
7951 : : AGG_HASHED,
7952 : : AGGSPLIT_INITIAL_SERIAL,
7953 : : root->processed_groupClause,
7954 : : NIL,
7955 : : agg_partial_costs,
7956 : : dNumPartialPartialGroups));
7957 : : }
7958 : :
7959 : : /*
7960 : : * Add any partially aggregated paths generated by eager aggregation to
7961 : : * the new upper relation after applying projection steps as needed.
7962 : : */
234 rguo@postgresql.org 7963 [ + + ]:GNC 3205 : if (eager_agg_rel)
7964 : : {
7965 : : /* Add the paths */
7966 [ + - + + : 1894 : foreach(lc, eager_agg_rel->pathlist)
+ + ]
7967 : : {
7968 : 1167 : Path *path = (Path *) lfirst(lc);
7969 : :
7970 : : /* Shouldn't have any parameterized paths anymore */
7971 [ - + ]: 1167 : Assert(path->param_info == NULL);
7972 : :
7973 : 1167 : path = (Path *) create_projection_path(root,
7974 : : partially_grouped_rel,
7975 : : path,
7976 : 1167 : partially_grouped_rel->reltarget);
7977 : :
7978 : 1167 : add_path(partially_grouped_rel, path);
7979 : : }
7980 : :
7981 : : /*
7982 : : * Likewise add the partial paths, but only if parallelism is possible
7983 : : * for partially_grouped_rel.
7984 : : */
7985 [ + + ]: 727 : if (partially_grouped_rel->consider_parallel)
7986 : : {
7987 [ + + + + : 1690 : foreach(lc, eager_agg_rel->partial_pathlist)
+ + ]
7988 : : {
7989 : 1010 : Path *path = (Path *) lfirst(lc);
7990 : :
7991 : : /* Shouldn't have any parameterized paths anymore */
7992 [ - + ]: 1010 : Assert(path->param_info == NULL);
7993 : :
7994 : 1010 : path = (Path *) create_projection_path(root,
7995 : : partially_grouped_rel,
7996 : : path,
7997 : 1010 : partially_grouped_rel->reltarget);
7998 : :
7999 : 1010 : add_partial_path(partially_grouped_rel, path);
8000 : : }
8001 : : }
8002 : : }
8003 : :
8004 : : /*
8005 : : * If there is an FDW that's responsible for all baserels of the query,
8006 : : * let it consider adding partially grouped ForeignPaths.
8007 : : */
3015 rhaas@postgresql.org 8008 [ + + ]:CBC 3205 : if (partially_grouped_rel->fdwroutine &&
8009 [ + - ]: 3 : partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
8010 : : {
8011 : 3 : FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
8012 : :
8013 : 3 : fdwroutine->GetForeignUpperPaths(root,
8014 : : UPPERREL_PARTIAL_GROUP_AGG,
8015 : : input_rel, partially_grouped_rel,
8016 : : extra);
8017 : : }
8018 : :
2993 8019 : 3205 : return partially_grouped_rel;
8020 : : }
8021 : :
8022 : : /*
8023 : : * make_ordered_path
8024 : : * Return a path ordered by 'pathkeys' based on the given 'path'. May
8025 : : * return NULL if it doesn't make sense to generate an ordered path in
8026 : : * this case.
8027 : : */
8028 : : static Path *
550 rguo@postgresql.org 8029 : 49796 : make_ordered_path(PlannerInfo *root, RelOptInfo *rel, Path *path,
8030 : : Path *cheapest_path, List *pathkeys, double limit_tuples)
8031 : : {
8032 : : bool is_sorted;
8033 : : int presorted_keys;
8034 : :
8035 : 49796 : is_sorted = pathkeys_count_contained_in(pathkeys,
8036 : : path->pathkeys,
8037 : : &presorted_keys);
8038 : :
8039 [ + + ]: 49796 : if (!is_sorted)
8040 : : {
8041 : : /*
8042 : : * Try at least sorting the cheapest path and also try incrementally
8043 : : * sorting any path which is partially sorted already (no need to deal
8044 : : * with paths which have presorted keys when incremental sort is
8045 : : * disabled unless it's the cheapest input path).
8046 : : */
8047 [ + + ]: 13171 : if (path != cheapest_path &&
8048 [ + + + + ]: 2155 : (presorted_keys == 0 || !enable_incremental_sort))
8049 : 1021 : return NULL;
8050 : :
8051 : : /*
8052 : : * We've no need to consider both a sort and incremental sort. We'll
8053 : : * just do a sort if there are no presorted keys and an incremental
8054 : : * sort when there are presorted keys.
8055 : : */
8056 [ + + + + ]: 12150 : if (presorted_keys == 0 || !enable_incremental_sort)
8057 : 10870 : path = (Path *) create_sort_path(root,
8058 : : rel,
8059 : : path,
8060 : : pathkeys,
8061 : : limit_tuples);
8062 : : else
8063 : 1280 : path = (Path *) create_incremental_sort_path(root,
8064 : : rel,
8065 : : path,
8066 : : pathkeys,
8067 : : presorted_keys,
8068 : : limit_tuples);
8069 : : }
8070 : :
8071 : 48775 : return path;
8072 : : }
8073 : :
8074 : : /*
8075 : : * Generate Gather and Gather Merge paths for a grouping relation or partial
8076 : : * grouping relation.
8077 : : *
8078 : : * generate_useful_gather_paths does most of the work, but we also consider a
8079 : : * special case: we could try sorting the data by the group_pathkeys and then
8080 : : * applying Gather Merge.
8081 : : *
8082 : : * NB: This function shouldn't be used for anything other than a grouped or
8083 : : * partially grouped relation not only because of the fact that it explicitly
8084 : : * references group_pathkeys but we pass "true" as the third argument to
8085 : : * generate_useful_gather_paths().
8086 : : */
8087 : : static void
2993 rhaas@postgresql.org 8088 : 2589 : gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
8089 : : {
8090 : : ListCell *lc;
8091 : : Path *cheapest_partial_path;
8092 : : List *groupby_pathkeys;
8093 : :
8094 : : /*
8095 : : * This occurs after any partial aggregation has taken place, so trim off
8096 : : * any pathkeys added for ORDER BY / DISTINCT aggregates.
8097 : : */
806 drowley@postgresql.o 8098 [ + + ]: 2589 : if (list_length(root->group_pathkeys) > root->num_groupby_pathkeys)
8099 : 15 : groupby_pathkeys = list_copy_head(root->group_pathkeys,
8100 : : root->num_groupby_pathkeys);
8101 : : else
8102 : 2574 : groupby_pathkeys = root->group_pathkeys;
8103 : :
8104 : : /* Try Gather for unordered paths and Gather Merge for ordered ones. */
2244 tomas.vondra@postgre 8105 : 2589 : generate_useful_gather_paths(root, rel, true);
8106 : :
2993 rhaas@postgresql.org 8107 : 2589 : cheapest_partial_path = linitial(rel->partial_pathlist);
8108 : :
8109 : : /* XXX Shouldn't this also consider the group-key-reordering? */
2244 tomas.vondra@postgre 8110 [ + - + + : 6150 : foreach(lc, rel->partial_pathlist)
+ + ]
8111 : : {
8112 : 3561 : Path *path = (Path *) lfirst(lc);
8113 : : bool is_sorted;
8114 : : int presorted_keys;
8115 : : double total_groups;
8116 : :
806 drowley@postgresql.o 8117 : 3561 : is_sorted = pathkeys_count_contained_in(groupby_pathkeys,
8118 : : path->pathkeys,
8119 : : &presorted_keys);
8120 : :
2244 tomas.vondra@postgre 8121 [ + + ]: 3561 : if (is_sorted)
8122 : 2328 : continue;
8123 : :
8124 : : /*
8125 : : * Try at least sorting the cheapest path and also try incrementally
8126 : : * sorting any path which is partially sorted already (no need to deal
8127 : : * with paths which have presorted keys when incremental sort is
8128 : : * disabled unless it's the cheapest input path).
8129 : : */
850 drowley@postgresql.o 8130 [ - + ]: 1233 : if (path != cheapest_partial_path &&
850 drowley@postgresql.o 8131 [ # # # # ]:UBC 0 : (presorted_keys == 0 || !enable_incremental_sort))
2244 tomas.vondra@postgre 8132 : 0 : continue;
8133 : :
8134 : : /*
8135 : : * We've no need to consider both a sort and incremental sort. We'll
8136 : : * just do a sort if there are no presorted keys and an incremental
8137 : : * sort when there are presorted keys.
8138 : : */
850 drowley@postgresql.o 8139 [ - + - - ]:CBC 1233 : if (presorted_keys == 0 || !enable_incremental_sort)
8140 : 1233 : path = (Path *) create_sort_path(root, rel, path,
8141 : : groupby_pathkeys,
8142 : : -1.0);
8143 : : else
850 drowley@postgresql.o 8144 :UBC 0 : path = (Path *) create_incremental_sort_path(root,
8145 : : rel,
8146 : : path,
8147 : : groupby_pathkeys,
8148 : : presorted_keys,
8149 : : -1.0);
676 rguo@postgresql.org 8150 :CBC 1233 : total_groups = compute_gather_rows(path);
8151 : : path = (Path *)
2244 tomas.vondra@postgre 8152 : 1233 : create_gather_merge_path(root,
8153 : : rel,
8154 : : path,
8155 : 1233 : rel->reltarget,
8156 : : groupby_pathkeys,
8157 : : NULL,
8158 : : &total_groups);
8159 : :
8160 : 1233 : add_path(rel, path);
8161 : : }
3357 rhaas@postgresql.org 8162 : 2589 : }
8163 : :
8164 : : /*
8165 : : * can_partial_agg
8166 : : *
8167 : : * Determines whether or not partial grouping and/or aggregation is possible.
8168 : : * Returns true when possible, false otherwise.
8169 : : */
8170 : : static bool
2013 heikki.linnakangas@i 8171 : 34212 : can_partial_agg(PlannerInfo *root)
8172 : : {
3046 rhaas@postgresql.org 8173 : 34212 : Query *parse = root->parse;
8174 : :
2993 8175 [ + + - + ]: 34212 : if (!parse->hasAggs && parse->groupClause == NIL)
8176 : : {
8177 : : /*
8178 : : * We don't know how to do parallel aggregation unless we have either
8179 : : * some aggregates or a grouping clause.
8180 : : */
3046 rhaas@postgresql.org 8181 :UBC 0 : return false;
8182 : : }
3046 rhaas@postgresql.org 8183 [ + + ]:CBC 34212 : else if (parse->groupingSets)
8184 : : {
8185 : : /* We don't know how to do grouping sets in parallel. */
8186 : 886 : return false;
8187 : : }
2013 heikki.linnakangas@i 8188 [ + + + + ]: 33326 : else if (root->hasNonPartialAggs || root->hasNonSerialAggs)
8189 : : {
8190 : : /* Insufficient support for partial mode. */
3046 rhaas@postgresql.org 8191 : 3243 : return false;
8192 : : }
8193 : :
8194 : : /* Everything looks good. */
8195 : 30083 : return true;
8196 : : }
8197 : :
8198 : : /*
8199 : : * apply_scanjoin_target_to_paths
8200 : : *
8201 : : * Adjust the final scan/join relation, and recursively all of its children,
8202 : : * to generate the final scan/join target. It would be more correct to model
8203 : : * this as a separate planning step with a new RelOptInfo at the toplevel and
8204 : : * for each child relation, but doing it this way is noticeably cheaper.
8205 : : * Maybe that problem can be solved at some point, but for now we do this.
8206 : : *
8207 : : * If tlist_same_exprs is true, then the scan/join target to be applied has
8208 : : * the same expressions as the existing reltarget, so we need only insert the
8209 : : * appropriate sortgroupref information. By avoiding the creation of
8210 : : * projection paths we save effort both immediately and at plan creation time.
8211 : : */
8212 : : static void
2991 8213 : 412061 : apply_scanjoin_target_to_paths(PlannerInfo *root,
8214 : : RelOptInfo *rel,
8215 : : List *scanjoin_targets,
8216 : : List *scanjoin_targets_contain_srfs,
8217 : : bool scanjoin_target_parallel_safe,
8218 : : bool tlist_same_exprs)
8219 : : {
2641 tgl@sss.pgh.pa.us 8220 [ + + + + : 412061 : bool rel_is_partitioned = IS_PARTITIONED_REL(rel);
+ + + - +
+ ]
8221 : : PathTarget *scanjoin_target;
8222 : : ListCell *lc;
8223 : :
8224 : : /* This recurses, so be paranoid. */
2984 rhaas@postgresql.org 8225 : 412061 : check_stack_depth();
8226 : :
8227 : : /*
8228 : : * If the rel only has Append and MergeAppend paths, we want to drop its
8229 : : * existing paths and generate new ones. This function would still be
8230 : : * correct if we kept the existing paths: we'd modify them to generate the
8231 : : * correct target above the partitioning Append, and then they'd compete
8232 : : * on cost with paths generating the target below the Append. However, in
8233 : : * our current cost model the latter way is always the same or cheaper
8234 : : * cost, so modifying the existing paths would just be useless work.
8235 : : * Moreover, when the cost is the same, varying roundoff errors might
8236 : : * sometimes allow an existing path to be picked, resulting in undesirable
8237 : : * cross-platform plan variations. So we drop old paths and thereby force
8238 : : * the work to be done below the Append.
8239 : : *
8240 : : * However, there are several cases when this optimization is not safe. If
8241 : : * the rel isn't partitioned, then none of the paths will be Append or
8242 : : * MergeAppend paths, so we should definitely not do this. If it is
8243 : : * partitioned but is a joinrel, it may have Append and MergeAppend paths,
8244 : : * but it can also have join paths that we can't afford to discard.
8245 : : *
8246 : : * Some care is needed, because we have to allow
8247 : : * generate_useful_gather_paths to see the old partial paths in the next
8248 : : * stanza. Hence, zap the main pathlist here, then allow
8249 : : * generate_useful_gather_paths to add path(s) to the main list, and
8250 : : * finally zap the partial pathlist.
8251 : : */
176 rhaas@postgresql.org 8252 [ + + + + :GNC 412061 : if (rel_is_partitioned && IS_SIMPLE_REL(rel))
+ + ]
2641 tgl@sss.pgh.pa.us 8253 :CBC 8712 : rel->pathlist = NIL;
8254 : :
8255 : : /*
8256 : : * If the scan/join target is not parallel-safe, partial paths cannot
8257 : : * generate it.
8258 : : */
2984 rhaas@postgresql.org 8259 [ + + ]: 412061 : if (!scanjoin_target_parallel_safe)
8260 : : {
8261 : : /*
8262 : : * Since we can't generate the final scan/join target in parallel
8263 : : * workers, this is our last opportunity to use any partial paths that
8264 : : * exist; so build Gather path(s) that use them and emit whatever the
8265 : : * current reltarget is. We don't do this in the case where the
8266 : : * target is parallel-safe, since we will be able to generate superior
8267 : : * paths by doing it after the final scan/join target has been
8268 : : * applied.
8269 : : */
2244 tomas.vondra@postgre 8270 : 53767 : generate_useful_gather_paths(root, rel, false);
8271 : :
8272 : : /* Can't use parallel query above this level. */
2984 rhaas@postgresql.org 8273 : 53767 : rel->partial_pathlist = NIL;
8274 : 53767 : rel->consider_parallel = false;
8275 : : }
8276 : :
8277 : : /* Finish dropping old paths for a partitioned rel, per comment above */
176 rhaas@postgresql.org 8278 [ + + + + :GNC 412061 : if (rel_is_partitioned && IS_SIMPLE_REL(rel))
+ + ]
2984 rhaas@postgresql.org 8279 :CBC 8712 : rel->partial_pathlist = NIL;
8280 : :
8281 : : /* Extract SRF-free scan/join target. */
8282 : 412061 : scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
8283 : :
8284 : : /*
8285 : : * Apply the SRF-free scan/join target to each existing path.
8286 : : *
8287 : : * If the tlist exprs are the same, we can just inject the sortgroupref
8288 : : * information into the existing pathtargets. Otherwise, replace each
8289 : : * path with a projection path that generates the SRF-free scan/join
8290 : : * target. This can't change the ordering of paths within rel->pathlist,
8291 : : * so we just modify the list in place.
8292 : : */
2991 8293 [ + + + + : 859544 : foreach(lc, rel->pathlist)
+ + ]
8294 : : {
8295 : 447483 : Path *subpath = (Path *) lfirst(lc);
8296 : :
8297 : : /* Shouldn't have any parameterized paths anymore */
8298 [ - + ]: 447483 : Assert(subpath->param_info == NULL);
8299 : :
2984 8300 [ + + ]: 447483 : if (tlist_same_exprs)
8301 : 164157 : subpath->pathtarget->sortgrouprefs =
8302 : 164157 : scanjoin_target->sortgrouprefs;
8303 : : else
8304 : : {
8305 : : Path *newpath;
8306 : :
2991 8307 : 283326 : newpath = (Path *) create_projection_path(root, rel, subpath,
8308 : : scanjoin_target);
8309 : 283326 : lfirst(lc) = newpath;
8310 : : }
8311 : : }
8312 : :
8313 : : /* Likewise adjust the targets for any partial paths. */
2984 8314 [ + + + + : 432310 : foreach(lc, rel->partial_pathlist)
+ + ]
8315 : : {
8316 : 20249 : Path *subpath = (Path *) lfirst(lc);
8317 : :
8318 : : /* Shouldn't have any parameterized paths anymore */
8319 [ - + ]: 20249 : Assert(subpath->param_info == NULL);
8320 : :
8321 [ + + ]: 20249 : if (tlist_same_exprs)
8322 : 16166 : subpath->pathtarget->sortgrouprefs =
8323 : 16166 : scanjoin_target->sortgrouprefs;
8324 : : else
8325 : : {
8326 : : Path *newpath;
8327 : :
2641 tgl@sss.pgh.pa.us 8328 : 4083 : newpath = (Path *) create_projection_path(root, rel, subpath,
8329 : : scanjoin_target);
2991 rhaas@postgresql.org 8330 : 4083 : lfirst(lc) = newpath;
8331 : : }
8332 : : }
8333 : :
8334 : : /*
8335 : : * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
8336 : : * atop each existing path. (Note that this function doesn't look at the
8337 : : * cheapest-path fields, which is a good thing because they're bogus right
8338 : : * now.)
8339 : : */
2984 8340 [ + + ]: 412061 : if (root->parse->hasTargetSRFs)
8341 : 10404 : adjust_paths_for_srfs(root, rel,
8342 : : scanjoin_targets,
8343 : : scanjoin_targets_contain_srfs);
8344 : :
8345 : : /*
8346 : : * Update the rel's target to be the final (with SRFs) scan/join target.
8347 : : * This now matches the actual output of all the paths, and we might get
8348 : : * confused in createplan.c if they don't agree. We must do this now so
8349 : : * that any append paths made in the next part will use the correct
8350 : : * pathtarget (cf. create_append_path).
8351 : : *
8352 : : * Note that this is also necessary if GetForeignUpperPaths() gets called
8353 : : * on the final scan/join relation or on any of its children, since the
8354 : : * FDW might look at the rel's target to create ForeignPaths.
8355 : : */
2641 tgl@sss.pgh.pa.us 8356 : 412061 : rel->reltarget = llast_node(PathTarget, scanjoin_targets);
8357 : :
8358 : : /*
8359 : : * If the relation is partitioned, recursively apply the scan/join target
8360 : : * to all partitions, and generate brand-new Append paths in which the
8361 : : * scan/join target is computed below the Append rather than above it.
8362 : : * Since Append is not projection-capable, that might save a separate
8363 : : * Result node, and it also is important for partitionwise aggregate.
8364 : : */
8365 [ + + ]: 412061 : if (rel_is_partitioned)
8366 : : {
2984 rhaas@postgresql.org 8367 : 10015 : List *live_children = NIL;
8368 : : int i;
8369 : :
8370 : : /* Adjust each partition. */
1761 drowley@postgresql.o 8371 : 10015 : i = -1;
8372 [ + + ]: 30081 : while ((i = bms_next_member(rel->live_parts, i)) >= 0)
8373 : : {
8374 : 20066 : RelOptInfo *child_rel = rel->part_rels[i];
8375 : : AppendRelInfo **appinfos;
8376 : : int nappinfos;
2984 rhaas@postgresql.org 8377 : 20066 : List *child_scanjoin_targets = NIL;
8378 : :
1761 drowley@postgresql.o 8379 [ - + ]: 20066 : Assert(child_rel != NULL);
8380 : :
8381 : : /* Dummy children can be ignored. */
8382 [ + + ]: 20066 : if (IS_DUMMY_REL(child_rel))
2618 tgl@sss.pgh.pa.us 8383 : 40 : continue;
8384 : :
8385 : : /* Translate scan/join targets for this child. */
2984 rhaas@postgresql.org 8386 : 20026 : appinfos = find_appinfos_by_relids(root, child_rel->relids,
8387 : : &nappinfos);
8388 [ + - + + : 40052 : foreach(lc, scanjoin_targets)
+ + ]
8389 : : {
8390 : 20026 : PathTarget *target = lfirst_node(PathTarget, lc);
8391 : :
8392 : 20026 : target = copy_pathtarget(target);
8393 : 20026 : target->exprs = (List *)
8394 : 20026 : adjust_appendrel_attrs(root,
8395 : 20026 : (Node *) target->exprs,
8396 : : nappinfos, appinfos);
8397 : 20026 : child_scanjoin_targets = lappend(child_scanjoin_targets,
8398 : : target);
8399 : : }
8400 : 20026 : pfree(appinfos);
8401 : :
8402 : : /* Recursion does the real work. */
8403 : 20026 : apply_scanjoin_target_to_paths(root, child_rel,
8404 : : child_scanjoin_targets,
8405 : : scanjoin_targets_contain_srfs,
8406 : : scanjoin_target_parallel_safe,
8407 : : tlist_same_exprs);
8408 : :
8409 : : /* Save non-dummy children for Append paths. */
8410 [ + - ]: 20026 : if (!IS_DUMMY_REL(child_rel))
8411 : 20026 : live_children = lappend(live_children, child_rel);
8412 : : }
8413 : :
8414 : : /* Build new paths for this relation by appending child paths. */
2641 tgl@sss.pgh.pa.us 8415 : 10015 : add_paths_to_append_rel(root, rel, live_children);
8416 : : }
8417 : :
8418 : : /*
8419 : : * Consider generating Gather or Gather Merge paths. We must only do this
8420 : : * if the relation is parallel safe, and we don't do it for child rels to
8421 : : * avoid creating multiple Gather nodes within the same plan. We must do
8422 : : * this after all paths have been generated and before set_cheapest, since
8423 : : * one of the generated paths may turn out to be the cheapest one.
8424 : : */
2984 rhaas@postgresql.org 8425 [ + + + + : 412061 : if (rel->consider_parallel && !IS_OTHER_REL(rel))
+ + + - ]
2244 tomas.vondra@postgre 8426 : 141418 : generate_useful_gather_paths(root, rel, false);
8427 : :
8428 : : /*
8429 : : * Reassess which paths are the cheapest, now that we've potentially added
8430 : : * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
8431 : : * this relation.
8432 : : */
2984 rhaas@postgresql.org 8433 : 412061 : set_cheapest(rel);
2991 8434 : 412061 : }
8435 : :
8436 : : /*
8437 : : * create_partitionwise_grouping_paths
8438 : : *
8439 : : * If the partition keys of input relation are part of the GROUP BY clause, all
8440 : : * the rows belonging to a given group come from a single partition. This
8441 : : * allows aggregation/grouping over a partitioned relation to be broken down
8442 : : * into aggregation/grouping on each partition. This should be no worse, and
8443 : : * often better, than the normal approach.
8444 : : *
8445 : : * However, if the GROUP BY clause does not contain all the partition keys,
8446 : : * rows from a given group may be spread across multiple partitions. In that
8447 : : * case, we perform partial aggregation for each group, append the results,
8448 : : * and then finalize aggregation. This is less certain to win than the
8449 : : * previous case. It may win if the PartialAggregate stage greatly reduces
8450 : : * the number of groups, because fewer rows will pass through the Append node.
8451 : : * It may lose if we have lots of small groups.
8452 : : */
8453 : : static void
8454 : 685 : create_partitionwise_grouping_paths(PlannerInfo *root,
8455 : : RelOptInfo *input_rel,
8456 : : RelOptInfo *grouped_rel,
8457 : : RelOptInfo *partially_grouped_rel,
8458 : : const AggClauseCosts *agg_costs,
8459 : : grouping_sets_data *gd,
8460 : : PartitionwiseAggregateType patype,
8461 : : GroupPathExtraData *extra)
8462 : : {
8463 : 685 : List *grouped_live_children = NIL;
8464 : 685 : List *partially_grouped_live_children = NIL;
2984 8465 : 685 : PathTarget *target = grouped_rel->reltarget;
2899 8466 : 685 : bool partial_grouping_valid = true;
8467 : : int i;
8468 : :
2991 8469 [ - + ]: 685 : Assert(patype != PARTITIONWISE_AGGREGATE_NONE);
8470 [ + + - + ]: 685 : Assert(patype != PARTITIONWISE_AGGREGATE_PARTIAL ||
8471 : : partially_grouped_rel != NULL);
8472 : :
8473 : : /* Add paths for partitionwise aggregation/grouping. */
1761 drowley@postgresql.o 8474 : 685 : i = -1;
8475 [ + + ]: 2480 : while ((i = bms_next_member(input_rel->live_parts, i)) >= 0)
8476 : : {
8477 : 1795 : RelOptInfo *child_input_rel = input_rel->part_rels[i];
8478 : : PathTarget *child_target;
8479 : : AppendRelInfo **appinfos;
8480 : : int nappinfos;
8481 : : GroupPathExtraData child_extra;
8482 : : RelOptInfo *child_grouped_rel;
8483 : : RelOptInfo *child_partially_grouped_rel;
8484 : :
8485 [ - + ]: 1795 : Assert(child_input_rel != NULL);
8486 : :
8487 : : /* Dummy children can be ignored. */
8488 [ - + ]: 1795 : if (IS_DUMMY_REL(child_input_rel))
2618 tgl@sss.pgh.pa.us 8489 :UBC 0 : continue;
8490 : :
1761 drowley@postgresql.o 8491 :CBC 1795 : child_target = copy_pathtarget(target);
8492 : :
8493 : : /*
8494 : : * Copy the given "extra" structure as is and then override the
8495 : : * members specific to this child.
8496 : : */
2991 rhaas@postgresql.org 8497 : 1795 : memcpy(&child_extra, extra, sizeof(child_extra));
8498 : :
8499 : 1795 : appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
8500 : : &nappinfos);
8501 : :
8502 : 1795 : child_target->exprs = (List *)
8503 : 1795 : adjust_appendrel_attrs(root,
8504 : 1795 : (Node *) target->exprs,
8505 : : nappinfos, appinfos);
8506 : :
8507 : : /* Translate havingQual and targetList. */
8508 : 1795 : child_extra.havingQual = (Node *)
8509 : : adjust_appendrel_attrs(root,
8510 : : extra->havingQual,
8511 : : nappinfos, appinfos);
8512 : 1795 : child_extra.targetList = (List *)
8513 : 1795 : adjust_appendrel_attrs(root,
8514 : 1795 : (Node *) extra->targetList,
8515 : : nappinfos, appinfos);
8516 : :
8517 : : /*
8518 : : * extra->patype was the value computed for our parent rel; patype is
8519 : : * the value for this relation. For the child, our value is its
8520 : : * parent rel's value.
8521 : : */
8522 : 1795 : child_extra.patype = patype;
8523 : :
8524 : : /*
8525 : : * Create grouping relation to hold fully aggregated grouping and/or
8526 : : * aggregation paths for the child.
8527 : : */
8528 : 1795 : child_grouped_rel = make_grouping_rel(root, child_input_rel,
8529 : : child_target,
8530 : 1795 : extra->target_parallel_safe,
8531 : : child_extra.havingQual);
8532 : :
8533 : : /* Create grouping paths for this child relation. */
8534 : 1795 : create_ordinary_grouping_paths(root, child_input_rel,
8535 : : child_grouped_rel,
8536 : : agg_costs, gd, &child_extra,
8537 : : &child_partially_grouped_rel);
8538 : :
8539 [ + + ]: 1795 : if (child_partially_grouped_rel)
8540 : : {
8541 : : partially_grouped_live_children =
8542 : 1283 : lappend(partially_grouped_live_children,
8543 : : child_partially_grouped_rel);
8544 : : }
8545 : : else
2899 8546 : 512 : partial_grouping_valid = false;
8547 : :
2991 8548 [ + + ]: 1795 : if (patype == PARTITIONWISE_AGGREGATE_FULL)
8549 : : {
8550 : 1082 : set_cheapest(child_grouped_rel);
8551 : 1082 : grouped_live_children = lappend(grouped_live_children,
8552 : : child_grouped_rel);
8553 : : }
8554 : :
8555 : 1795 : pfree(appinfos);
8556 : : }
8557 : :
8558 : : /*
8559 : : * Try to create append paths for partially grouped children. For full
8560 : : * partitionwise aggregation, we might have paths in the partial_pathlist
8561 : : * if parallel aggregation is possible. For partial partitionwise
8562 : : * aggregation, we may have paths in both pathlist and partial_pathlist.
8563 : : *
8564 : : * NB: We must have a partially grouped path for every child in order to
8565 : : * generate a partially grouped path for this relation.
8566 : : */
2899 8567 [ + + + + ]: 685 : if (partially_grouped_rel && partial_grouping_valid)
8568 : : {
8569 [ - + ]: 501 : Assert(partially_grouped_live_children != NIL);
8570 : :
2991 8571 : 501 : add_paths_to_append_rel(root, partially_grouped_rel,
8572 : : partially_grouped_live_children);
8573 : : }
8574 : :
8575 : : /* If possible, create append paths for fully grouped children. */
8576 [ + + ]: 685 : if (patype == PARTITIONWISE_AGGREGATE_FULL)
8577 : : {
2899 8578 [ - + ]: 404 : Assert(grouped_live_children != NIL);
8579 : :
2991 8580 : 404 : add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
8581 : : }
8582 : 685 : }
8583 : :
8584 : : /*
8585 : : * group_by_has_partkey
8586 : : *
8587 : : * Returns true if all the partition keys of the given relation are part of
8588 : : * the GROUP BY clauses, including having matching collation, false otherwise.
8589 : : */
8590 : : static bool
8591 : 640 : group_by_has_partkey(RelOptInfo *input_rel,
8592 : : List *targetList,
8593 : : List *groupClause)
8594 : : {
8595 : 640 : List *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
8596 : 640 : int cnt = 0;
8597 : : int partnatts;
8598 : :
8599 : : /* Input relation should be partitioned. */
8600 [ - + ]: 640 : Assert(input_rel->part_scheme);
8601 : :
8602 : : /* Rule out early, if there are no partition keys present. */
8603 [ - + ]: 640 : if (!input_rel->partexprs)
2991 rhaas@postgresql.org 8604 :UBC 0 : return false;
8605 : :
2991 rhaas@postgresql.org 8606 :CBC 640 : partnatts = input_rel->part_scheme->partnatts;
8607 : :
8608 [ + + ]: 1074 : for (cnt = 0; cnt < partnatts; cnt++)
8609 : : {
8610 : 670 : List *partexprs = input_rel->partexprs[cnt];
8611 : : ListCell *lc;
8612 : 670 : bool found = false;
8613 : :
8614 [ + + + + : 1001 : foreach(lc, partexprs)
+ + ]
8615 : : {
8616 : : ListCell *lg;
8617 : 775 : Expr *partexpr = lfirst(lc);
568 amitlan@postgresql.o 8618 : 775 : Oid partcoll = input_rel->part_scheme->partcollation[cnt];
8619 : :
8620 [ + - + + : 1206 : foreach(lg, groupexprs)
+ + ]
8621 : : {
8622 : 875 : Expr *groupexpr = lfirst(lg);
8623 : 875 : Oid groupcoll = exprCollation((Node *) groupexpr);
8624 : :
8625 : : /*
8626 : : * Note: we can assume there is at most one RelabelType node;
8627 : : * eval_const_expressions() will have simplified if more than
8628 : : * one.
8629 : : */
8630 [ + + ]: 875 : if (IsA(groupexpr, RelabelType))
8631 : 20 : groupexpr = ((RelabelType *) groupexpr)->arg;
8632 : :
8633 [ + + ]: 875 : if (equal(groupexpr, partexpr))
8634 : : {
8635 : : /*
8636 : : * Reject a match if the grouping collation does not match
8637 : : * the partitioning collation.
8638 : : */
8639 [ + + + - : 444 : if (OidIsValid(partcoll) && OidIsValid(groupcoll) &&
+ + ]
8640 : : partcoll != groupcoll)
8641 : 10 : return false;
8642 : :
8643 : 434 : found = true;
8644 : 434 : break;
8645 : : }
8646 : : }
8647 : :
8648 [ + + ]: 765 : if (found)
8649 : 434 : break;
8650 : : }
8651 : :
8652 : : /*
8653 : : * If none of the partition key expressions match with any of the
8654 : : * GROUP BY expression, return false.
8655 : : */
2991 rhaas@postgresql.org 8656 [ + + ]: 660 : if (!found)
8657 : 226 : return false;
8658 : : }
8659 : :
8660 : 404 : return true;
8661 : : }
8662 : :
8663 : : /*
8664 : : * generate_setop_child_grouplist
8665 : : * Build a SortGroupClause list defining the sort/grouping properties
8666 : : * of the child of a set operation.
8667 : : *
8668 : : * This is similar to generate_setop_grouplist() but differs as the setop
8669 : : * child query's targetlist entries may already have a tleSortGroupRef
8670 : : * assigned for other purposes, such as GROUP BYs. Here we keep the
8671 : : * SortGroupClause list in the same order as 'op' groupClauses and just adjust
8672 : : * the tleSortGroupRef to reference the TargetEntry's 'ressortgroupref'. If
8673 : : * any of the columns in the targetlist don't match to the setop's colTypes
8674 : : * then we return an empty list. This may leave some TLEs with unreferenced
8675 : : * ressortgroupref markings, but that's harmless.
8676 : : */
8677 : : static List *
739 8678 : 10473 : generate_setop_child_grouplist(SetOperationStmt *op, List *targetlist)
8679 : : {
8680 : 10473 : List *grouplist = copyObject(op->groupClauses);
8681 : : ListCell *lg;
8682 : : ListCell *lt;
8683 : : ListCell *ct;
8684 : :
8685 : 10473 : lg = list_head(grouplist);
505 drowley@postgresql.o 8686 : 10473 : ct = list_head(op->colTypes);
739 rhaas@postgresql.org 8687 [ + + + + : 40703 : foreach(lt, targetlist)
+ + ]
8688 : : {
8689 : 30467 : TargetEntry *tle = (TargetEntry *) lfirst(lt);
8690 : : SortGroupClause *sgc;
8691 : : Oid coltype;
8692 : :
8693 : : /* resjunk columns could have sortgrouprefs. Leave these alone */
8694 [ - + ]: 30467 : if (tle->resjunk)
739 rhaas@postgresql.org 8695 :UBC 0 : continue;
8696 : :
8697 : : /*
8698 : : * We expect every non-resjunk target to have a SortGroupClause and
8699 : : * colTypes.
8700 : : */
739 rhaas@postgresql.org 8701 [ - + ]:CBC 30467 : Assert(lg != NULL);
505 drowley@postgresql.o 8702 [ - + ]: 30467 : Assert(ct != NULL);
739 rhaas@postgresql.org 8703 : 30467 : sgc = (SortGroupClause *) lfirst(lg);
505 drowley@postgresql.o 8704 : 30467 : coltype = lfirst_oid(ct);
8705 : :
8706 : : /* reject if target type isn't the same as the setop target type */
8707 [ + + ]: 30467 : if (coltype != exprType((Node *) tle->expr))
8708 : 237 : return NIL;
8709 : :
739 rhaas@postgresql.org 8710 : 30230 : lg = lnext(grouplist, lg);
505 drowley@postgresql.o 8711 : 30230 : ct = lnext(op->colTypes, ct);
8712 : :
8713 : : /* assign a tleSortGroupRef, or reuse the existing one */
739 rhaas@postgresql.org 8714 : 30230 : sgc->tleSortGroupRef = assignSortGroupRef(tle, targetlist);
8715 : : }
8716 : :
8717 [ - + ]: 10236 : Assert(lg == NULL);
505 drowley@postgresql.o 8718 [ - + ]: 10236 : Assert(ct == NULL);
8719 : :
739 rhaas@postgresql.org 8720 : 10236 : return grouplist;
8721 : : }
8722 : :
8723 : : /*
8724 : : * create_unique_paths
8725 : : * Build a new RelOptInfo containing Paths that represent elimination of
8726 : : * distinct rows from the input data. Distinct-ness is defined according to
8727 : : * the needs of the semijoin represented by sjinfo. If it is not possible
8728 : : * to identify how to make the data unique, NULL is returned.
8729 : : *
8730 : : * If used at all, this is likely to be called repeatedly on the same rel,
8731 : : * so we cache the result.
8732 : : */
8733 : : RelOptInfo *
284 rguo@postgresql.org 8734 :GNC 6924 : create_unique_paths(PlannerInfo *root, RelOptInfo *rel, SpecialJoinInfo *sjinfo)
8735 : : {
8736 : : RelOptInfo *unique_rel;
8737 : 6924 : List *sortPathkeys = NIL;
8738 : 6924 : List *groupClause = NIL;
8739 : : MemoryContext oldcontext;
8740 : :
8741 : : /* Caller made a mistake if SpecialJoinInfo is the wrong one */
8742 [ - + ]: 6924 : Assert(sjinfo->jointype == JOIN_SEMI);
8743 [ - + ]: 6924 : Assert(bms_equal(rel->relids, sjinfo->syn_righthand));
8744 : :
8745 : : /* If result already cached, return it */
8746 [ + + ]: 6924 : if (rel->unique_rel)
8747 : 1196 : return rel->unique_rel;
8748 : :
8749 : : /* If it's not possible to unique-ify, return NULL */
8750 [ + + + - ]: 5728 : if (!(sjinfo->semi_can_btree || sjinfo->semi_can_hash))
8751 : 104 : return NULL;
8752 : :
8753 : : /*
8754 : : * Punt if this is a child relation and we failed to build a unique-ified
8755 : : * relation for its parent. This can happen if all the RHS columns were
8756 : : * found to be equated to constants when unique-ifying the parent table,
8757 : : * leaving no columns to unique-ify.
8758 : : */
274 8759 [ + + + + : 5624 : if (IS_OTHER_REL(rel) && rel->top_parent->unique_rel == NULL)
- + + + ]
8760 : 10 : return NULL;
8761 : :
8762 : : /*
8763 : : * When called during GEQO join planning, we are in a short-lived memory
8764 : : * context. We must make sure that the unique rel and any subsidiary data
8765 : : * structures created for a baserel survive the GEQO cycle, else the
8766 : : * baserel is trashed for future GEQO cycles. On the other hand, when we
8767 : : * are creating those for a joinrel during GEQO, we don't want them to
8768 : : * clutter the main planning context. Upshot is that the best solution is
8769 : : * to explicitly allocate memory in the same context the given RelOptInfo
8770 : : * is in.
8771 : : */
284 8772 : 5614 : oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
8773 : :
8774 : 5614 : unique_rel = makeNode(RelOptInfo);
8775 : 5614 : memcpy(unique_rel, rel, sizeof(RelOptInfo));
8776 : :
8777 : : /*
8778 : : * clear path info
8779 : : */
8780 : 5614 : unique_rel->pathlist = NIL;
8781 : 5614 : unique_rel->ppilist = NIL;
8782 : 5614 : unique_rel->partial_pathlist = NIL;
8783 : 5614 : unique_rel->cheapest_startup_path = NULL;
8784 : 5614 : unique_rel->cheapest_total_path = NULL;
8785 : 5614 : unique_rel->cheapest_parameterized_paths = NIL;
8786 : :
8787 : : /*
8788 : : * Build the target list for the unique rel. We also build the pathkeys
8789 : : * that represent the ordering requirements for the sort-based
8790 : : * implementation, and the list of SortGroupClause nodes that represent
8791 : : * the columns to be grouped on for the hash-based implementation.
8792 : : *
8793 : : * For a child rel, we can construct these fields from those of its
8794 : : * parent.
8795 : : */
8796 [ + + + + : 5614 : if (IS_OTHER_REL(rel))
- + ]
8797 : 360 : {
8798 : : PathTarget *child_unique_target;
8799 : : PathTarget *parent_unique_target;
8800 : :
8801 : 360 : parent_unique_target = rel->top_parent->unique_rel->reltarget;
8802 : :
8803 : 360 : child_unique_target = copy_pathtarget(parent_unique_target);
8804 : :
8805 : : /* Translate the target expressions */
8806 : 360 : child_unique_target->exprs = (List *)
8807 : 360 : adjust_appendrel_attrs_multilevel(root,
8808 : 360 : (Node *) parent_unique_target->exprs,
8809 : : rel,
8810 : 360 : rel->top_parent);
8811 : :
8812 : 360 : unique_rel->reltarget = child_unique_target;
8813 : :
8814 : 360 : sortPathkeys = rel->top_parent->unique_pathkeys;
8815 : 360 : groupClause = rel->top_parent->unique_groupclause;
8816 : : }
8817 : : else
8818 : : {
8819 : : List *newtlist;
8820 : : int nextresno;
8821 : 5254 : List *sortList = NIL;
8822 : : ListCell *lc1;
8823 : : ListCell *lc2;
8824 : :
8825 : : /*
8826 : : * The values we are supposed to unique-ify may be expressions in the
8827 : : * variables of the input rel's targetlist. We have to add any such
8828 : : * expressions to the unique rel's targetlist.
8829 : : *
8830 : : * To complicate matters, some of the values to be unique-ified may be
8831 : : * known redundant by the EquivalenceClass machinery (e.g., because
8832 : : * they have been equated to constants). There is no need to compare
8833 : : * such values during unique-ification, and indeed we had better not
8834 : : * try because the Vars involved may not have propagated as high as
8835 : : * the semijoin's level. We use make_pathkeys_for_sortclauses to
8836 : : * detect such cases, which is a tad inefficient but it doesn't seem
8837 : : * worth building specialized infrastructure for this.
8838 : : */
8839 : 5254 : newtlist = make_tlist_from_pathtarget(rel->reltarget);
8840 : 5254 : nextresno = list_length(newtlist) + 1;
8841 : :
8842 : 10709 : forboth(lc1, sjinfo->semi_rhs_exprs, lc2, sjinfo->semi_operators)
[ + - + +
+ - + + +
+ + - +
+ ]
8843 : : {
8844 : 5455 : Expr *uniqexpr = lfirst(lc1);
8845 : 5455 : Oid in_oper = lfirst_oid(lc2);
8846 : : Oid sortop;
8847 : : TargetEntry *tle;
275 tgl@sss.pgh.pa.us 8848 : 5455 : bool made_tle = false;
8849 : :
284 rguo@postgresql.org 8850 : 5455 : tle = tlist_member(uniqexpr, newtlist);
8851 [ + + ]: 5455 : if (!tle)
8852 : : {
179 peter@eisentraut.org 8853 : 2752 : tle = makeTargetEntry(uniqexpr,
8854 : : nextresno,
8855 : : NULL,
8856 : : false);
284 rguo@postgresql.org 8857 : 2752 : newtlist = lappend(newtlist, tle);
8858 : 2752 : nextresno++;
275 tgl@sss.pgh.pa.us 8859 : 2752 : made_tle = true;
8860 : : }
8861 : :
8862 : : /*
8863 : : * Try to build an ORDER BY list to sort the input compatibly. We
8864 : : * do this for each sortable clause even when the clauses are not
8865 : : * all sortable, so that we can detect clauses that are redundant
8866 : : * according to the pathkey machinery.
8867 : : */
8868 : 5455 : sortop = get_ordering_op_for_equality_op(in_oper, false);
8869 [ + - ]: 5455 : if (OidIsValid(sortop))
8870 : : {
8871 : : Oid eqop;
8872 : : SortGroupClause *sortcl;
8873 : :
8874 : : /*
8875 : : * The Unique node will need equality operators. Normally
8876 : : * these are the same as the IN clause operators, but if those
8877 : : * are cross-type operators then the equality operators are
8878 : : * the ones for the IN clause operators' RHS datatype.
8879 : : */
284 rguo@postgresql.org 8880 : 5455 : eqop = get_equality_op_for_ordering_op(sortop, NULL);
8881 [ - + ]: 5455 : if (!OidIsValid(eqop)) /* shouldn't happen */
284 rguo@postgresql.org 8882 [ # # ]:UNC 0 : elog(ERROR, "could not find equality operator for ordering operator %u",
8883 : : sortop);
8884 : :
284 rguo@postgresql.org 8885 :GNC 5455 : sortcl = makeNode(SortGroupClause);
8886 : 5455 : sortcl->tleSortGroupRef = assignSortGroupRef(tle, newtlist);
8887 : 5455 : sortcl->eqop = eqop;
8888 : 5455 : sortcl->sortop = sortop;
8889 : 5455 : sortcl->reverse_sort = false;
8890 : 5455 : sortcl->nulls_first = false;
8891 : 5455 : sortcl->hashable = false; /* no need to make this accurate */
8892 : 5455 : sortList = lappend(sortList, sortcl);
8893 : :
8894 : : /*
8895 : : * At each step, convert the SortGroupClause list to pathkey
8896 : : * form. If the just-added SortGroupClause is redundant, the
8897 : : * result will be shorter than the SortGroupClause list.
8898 : : */
275 tgl@sss.pgh.pa.us 8899 : 5455 : sortPathkeys = make_pathkeys_for_sortclauses(root, sortList,
8900 : : newtlist);
8901 [ + + ]: 5455 : if (list_length(sortPathkeys) != list_length(sortList))
8902 : : {
8903 : : /* Drop the redundant SortGroupClause */
8904 : 1710 : sortList = list_delete_last(sortList);
8905 [ - + ]: 1710 : Assert(list_length(sortPathkeys) == list_length(sortList));
8906 : : /* Undo tlist addition, if we made one */
8907 [ + + ]: 1710 : if (made_tle)
8908 : : {
8909 : 10 : newtlist = list_delete_last(newtlist);
8910 : 10 : nextresno--;
8911 : : }
8912 : : /* We need not consider this clause for hashing, either */
8913 : 1710 : continue;
8914 : : }
8915 : : }
275 tgl@sss.pgh.pa.us 8916 [ # # ]:UNC 0 : else if (sjinfo->semi_can_btree) /* shouldn't happen */
8917 [ # # ]: 0 : elog(ERROR, "could not find ordering operator for equality operator %u",
8918 : : in_oper);
8919 : :
284 rguo@postgresql.org 8920 [ + - ]:GNC 3745 : if (sjinfo->semi_can_hash)
8921 : : {
8922 : : /* Create a GROUP BY list for the Agg node to use */
8923 : : Oid eq_oper;
8924 : : SortGroupClause *groupcl;
8925 : :
8926 : : /*
8927 : : * Get the hashable equality operators for the Agg node to
8928 : : * use. Normally these are the same as the IN clause
8929 : : * operators, but if those are cross-type operators then the
8930 : : * equality operators are the ones for the IN clause
8931 : : * operators' RHS datatype.
8932 : : */
8933 [ - + ]: 3745 : if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
284 rguo@postgresql.org 8934 [ # # ]:UNC 0 : elog(ERROR, "could not find compatible hash operator for operator %u",
8935 : : in_oper);
8936 : :
284 rguo@postgresql.org 8937 :GNC 3745 : groupcl = makeNode(SortGroupClause);
8938 : 3745 : groupcl->tleSortGroupRef = assignSortGroupRef(tle, newtlist);
8939 : 3745 : groupcl->eqop = eq_oper;
8940 : 3745 : groupcl->sortop = sortop;
8941 : 3745 : groupcl->reverse_sort = false;
8942 : 3745 : groupcl->nulls_first = false;
8943 : 3745 : groupcl->hashable = true;
8944 : 3745 : groupClause = lappend(groupClause, groupcl);
8945 : : }
8946 : : }
8947 : :
8948 : : /*
8949 : : * Done building the sortPathkeys and groupClause. But the
8950 : : * sortPathkeys are bogus if not all the clauses were sortable.
8951 : : */
275 tgl@sss.pgh.pa.us 8952 [ - + ]: 5254 : if (!sjinfo->semi_can_btree)
275 tgl@sss.pgh.pa.us 8953 :UNC 0 : sortPathkeys = NIL;
8954 : :
8955 : : /*
8956 : : * It can happen that all the RHS columns are equated to constants.
8957 : : * We'd have to do something special to unique-ify in that case, and
8958 : : * it's such an unlikely-in-the-real-world case that it's not worth
8959 : : * the effort. So just punt if we found no columns to unique-ify.
8960 : : */
275 tgl@sss.pgh.pa.us 8961 [ + + + - ]:GNC 5254 : if (sortPathkeys == NIL && groupClause == NIL)
8962 : : {
8963 : 1625 : MemoryContextSwitchTo(oldcontext);
8964 : 1625 : return NULL;
8965 : : }
8966 : :
8967 : : /* Convert the required targetlist back to PathTarget form */
284 rguo@postgresql.org 8968 : 3629 : unique_rel->reltarget = create_pathtarget(root, newtlist);
8969 : : }
8970 : :
8971 : : /* build unique paths based on input rel's pathlist */
8972 : 3989 : create_final_unique_paths(root, rel, sortPathkeys, groupClause,
8973 : : sjinfo, unique_rel);
8974 : :
8975 : : /* build unique paths based on input rel's partial_pathlist */
8976 : 3989 : create_partial_unique_paths(root, rel, sortPathkeys, groupClause,
8977 : : sjinfo, unique_rel);
8978 : :
8979 : : /* Now choose the best path(s) */
8980 : 3989 : set_cheapest(unique_rel);
8981 : :
8982 : : /*
8983 : : * There shouldn't be any partial paths for the unique relation;
8984 : : * otherwise, we won't be able to properly guarantee uniqueness.
8985 : : */
8986 [ - + ]: 3989 : Assert(unique_rel->partial_pathlist == NIL);
8987 : :
8988 : : /* Cache the result */
8989 : 3989 : rel->unique_rel = unique_rel;
8990 : 3989 : rel->unique_pathkeys = sortPathkeys;
8991 : 3989 : rel->unique_groupclause = groupClause;
8992 : :
8993 : 3989 : MemoryContextSwitchTo(oldcontext);
8994 : :
8995 : 3989 : return unique_rel;
8996 : : }
8997 : :
8998 : : /*
8999 : : * create_final_unique_paths
9000 : : * Create unique paths in 'unique_rel' based on 'input_rel' pathlist
9001 : : */
9002 : : static void
9003 : 7121 : create_final_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
9004 : : List *sortPathkeys, List *groupClause,
9005 : : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
9006 : : {
9007 : 7121 : Path *cheapest_input_path = input_rel->cheapest_total_path;
9008 : :
9009 : : /* Estimate number of output rows */
9010 : 7121 : unique_rel->rows = estimate_num_groups(root,
9011 : : sjinfo->semi_rhs_exprs,
9012 : : cheapest_input_path->rows,
9013 : : NULL,
9014 : : NULL);
9015 : :
9016 : : /* Consider sort-based implementations, if possible. */
9017 [ + - ]: 7121 : if (sjinfo->semi_can_btree)
9018 : : {
9019 : : ListCell *lc;
9020 : :
9021 : : /*
9022 : : * Use any available suitably-sorted path as input, and also consider
9023 : : * sorting the cheapest-total path and incremental sort on any paths
9024 : : * with presorted keys.
9025 : : *
9026 : : * To save planning time, we ignore parameterized input paths unless
9027 : : * they are the cheapest-total path.
9028 : : */
9029 [ + - + + : 15520 : foreach(lc, input_rel->pathlist)
+ + ]
9030 : : {
9031 : 8399 : Path *input_path = (Path *) lfirst(lc);
9032 : : Path *path;
9033 : : bool is_sorted;
9034 : : int presorted_keys;
9035 : :
9036 : : /*
9037 : : * Ignore parameterized paths that are not the cheapest-total
9038 : : * path.
9039 : : */
9040 [ + + + + ]: 8399 : if (input_path->param_info &&
9041 : : input_path != cheapest_input_path)
9042 : 740 : continue;
9043 : :
9044 : 7695 : is_sorted = pathkeys_count_contained_in(sortPathkeys,
9045 : : input_path->pathkeys,
9046 : : &presorted_keys);
9047 : :
9048 : : /*
9049 : : * Ignore paths that are not suitably or partially sorted, unless
9050 : : * they are the cheapest total path (no need to deal with paths
9051 : : * which have presorted keys when incremental sort is disabled).
9052 : : */
9053 [ + + + + ]: 7695 : if (!is_sorted && input_path != cheapest_input_path &&
9054 [ + + - + ]: 76 : (presorted_keys == 0 || !enable_incremental_sort))
9055 : 36 : continue;
9056 : :
9057 : : /*
9058 : : * Make a separate ProjectionPath in case we need a Result node.
9059 : : */
9060 : 7659 : path = (Path *) create_projection_path(root,
9061 : : unique_rel,
9062 : : input_path,
9063 : 7659 : unique_rel->reltarget);
9064 : :
9065 [ + + ]: 7659 : if (!is_sorted)
9066 : : {
9067 : : /*
9068 : : * We've no need to consider both a sort and incremental sort.
9069 : : * We'll just do a sort if there are no presorted keys and an
9070 : : * incremental sort when there are presorted keys.
9071 : : */
9072 [ + + - + ]: 3972 : if (presorted_keys == 0 || !enable_incremental_sort)
9073 : 3932 : path = (Path *) create_sort_path(root,
9074 : : unique_rel,
9075 : : path,
9076 : : sortPathkeys,
9077 : : -1.0);
9078 : : else
9079 : 40 : path = (Path *) create_incremental_sort_path(root,
9080 : : unique_rel,
9081 : : path,
9082 : : sortPathkeys,
9083 : : presorted_keys,
9084 : : -1.0);
9085 : : }
9086 : :
9087 : 7659 : path = (Path *) create_unique_path(root, unique_rel, path,
9088 : : list_length(sortPathkeys),
9089 : : unique_rel->rows);
9090 : :
9091 : 7659 : add_path(unique_rel, path);
9092 : : }
9093 : : }
9094 : :
9095 : : /* Consider hash-based implementation, if possible. */
9096 [ + - ]: 7121 : if (sjinfo->semi_can_hash)
9097 : : {
9098 : : Path *path;
9099 : :
9100 : : /*
9101 : : * Make a separate ProjectionPath in case we need a Result node.
9102 : : */
9103 : 7121 : path = (Path *) create_projection_path(root,
9104 : : unique_rel,
9105 : : cheapest_input_path,
9106 : 7121 : unique_rel->reltarget);
9107 : :
9108 : 7121 : path = (Path *) create_agg_path(root,
9109 : : unique_rel,
9110 : : path,
9111 : : cheapest_input_path->pathtarget,
9112 : : AGG_HASHED,
9113 : : AGGSPLIT_SIMPLE,
9114 : : groupClause,
9115 : : NIL,
9116 : : NULL,
9117 : : unique_rel->rows);
9118 : :
9119 : 7121 : add_path(unique_rel, path);
9120 : : }
9121 : 7121 : }
9122 : :
9123 : : /*
9124 : : * create_partial_unique_paths
9125 : : * Create unique paths in 'unique_rel' based on 'input_rel' partial_pathlist
9126 : : */
9127 : : static void
9128 : 3989 : create_partial_unique_paths(PlannerInfo *root, RelOptInfo *input_rel,
9129 : : List *sortPathkeys, List *groupClause,
9130 : : SpecialJoinInfo *sjinfo, RelOptInfo *unique_rel)
9131 : : {
9132 : : RelOptInfo *partial_unique_rel;
9133 : : Path *cheapest_partial_path;
9134 : :
9135 : : /* nothing to do when there are no partial paths in the input rel */
9136 [ + + + + ]: 3989 : if (!input_rel->consider_parallel || input_rel->partial_pathlist == NIL)
9137 : 857 : return;
9138 : :
9139 : : /*
9140 : : * nothing to do if there's anything in the targetlist that's
9141 : : * parallel-restricted.
9142 : : */
9143 [ - + ]: 3132 : if (!is_parallel_safe(root, (Node *) unique_rel->reltarget->exprs))
284 rguo@postgresql.org 9144 :UNC 0 : return;
9145 : :
284 rguo@postgresql.org 9146 :GNC 3132 : cheapest_partial_path = linitial(input_rel->partial_pathlist);
9147 : :
9148 : 3132 : partial_unique_rel = makeNode(RelOptInfo);
9149 : 3132 : memcpy(partial_unique_rel, input_rel, sizeof(RelOptInfo));
9150 : :
9151 : : /*
9152 : : * clear path info
9153 : : */
9154 : 3132 : partial_unique_rel->pathlist = NIL;
9155 : 3132 : partial_unique_rel->ppilist = NIL;
9156 : 3132 : partial_unique_rel->partial_pathlist = NIL;
9157 : 3132 : partial_unique_rel->cheapest_startup_path = NULL;
9158 : 3132 : partial_unique_rel->cheapest_total_path = NULL;
9159 : 3132 : partial_unique_rel->cheapest_parameterized_paths = NIL;
9160 : :
9161 : : /* Estimate number of output rows */
9162 : 3132 : partial_unique_rel->rows = estimate_num_groups(root,
9163 : : sjinfo->semi_rhs_exprs,
9164 : : cheapest_partial_path->rows,
9165 : : NULL,
9166 : : NULL);
9167 : 3132 : partial_unique_rel->reltarget = unique_rel->reltarget;
9168 : :
9169 : : /* Consider sort-based implementations, if possible. */
9170 [ + - ]: 3132 : if (sjinfo->semi_can_btree)
9171 : : {
9172 : : ListCell *lc;
9173 : :
9174 : : /*
9175 : : * Use any available suitably-sorted path as input, and also consider
9176 : : * sorting the cheapest partial path and incremental sort on any paths
9177 : : * with presorted keys.
9178 : : */
9179 [ + - + + : 6518 : foreach(lc, input_rel->partial_pathlist)
+ + ]
9180 : : {
9181 : 3386 : Path *input_path = (Path *) lfirst(lc);
9182 : : Path *path;
9183 : : bool is_sorted;
9184 : : int presorted_keys;
9185 : :
9186 : 3386 : is_sorted = pathkeys_count_contained_in(sortPathkeys,
9187 : : input_path->pathkeys,
9188 : : &presorted_keys);
9189 : :
9190 : : /*
9191 : : * Ignore paths that are not suitably or partially sorted, unless
9192 : : * they are the cheapest partial path (no need to deal with paths
9193 : : * which have presorted keys when incremental sort is disabled).
9194 : : */
9195 [ + + - + ]: 3386 : if (!is_sorted && input_path != cheapest_partial_path &&
284 rguo@postgresql.org 9196 [ # # # # ]:UNC 0 : (presorted_keys == 0 || !enable_incremental_sort))
9197 : 0 : continue;
9198 : :
9199 : : /*
9200 : : * Make a separate ProjectionPath in case we need a Result node.
9201 : : */
284 rguo@postgresql.org 9202 :GNC 3386 : path = (Path *) create_projection_path(root,
9203 : : partial_unique_rel,
9204 : : input_path,
9205 : 3386 : partial_unique_rel->reltarget);
9206 : :
9207 [ + + ]: 3386 : if (!is_sorted)
9208 : : {
9209 : : /*
9210 : : * We've no need to consider both a sort and incremental sort.
9211 : : * We'll just do a sort if there are no presorted keys and an
9212 : : * incremental sort when there are presorted keys.
9213 : : */
9214 [ - + - - ]: 3092 : if (presorted_keys == 0 || !enable_incremental_sort)
9215 : 3092 : path = (Path *) create_sort_path(root,
9216 : : partial_unique_rel,
9217 : : path,
9218 : : sortPathkeys,
9219 : : -1.0);
9220 : : else
284 rguo@postgresql.org 9221 :UNC 0 : path = (Path *) create_incremental_sort_path(root,
9222 : : partial_unique_rel,
9223 : : path,
9224 : : sortPathkeys,
9225 : : presorted_keys,
9226 : : -1.0);
9227 : : }
9228 : :
284 rguo@postgresql.org 9229 :GNC 3386 : path = (Path *) create_unique_path(root, partial_unique_rel, path,
9230 : : list_length(sortPathkeys),
9231 : : partial_unique_rel->rows);
9232 : :
9233 : 3386 : add_partial_path(partial_unique_rel, path);
9234 : : }
9235 : : }
9236 : :
9237 : : /* Consider hash-based implementation, if possible. */
9238 [ + - ]: 3132 : if (sjinfo->semi_can_hash)
9239 : : {
9240 : : Path *path;
9241 : :
9242 : : /*
9243 : : * Make a separate ProjectionPath in case we need a Result node.
9244 : : */
9245 : 3132 : path = (Path *) create_projection_path(root,
9246 : : partial_unique_rel,
9247 : : cheapest_partial_path,
9248 : 3132 : partial_unique_rel->reltarget);
9249 : :
9250 : 3132 : path = (Path *) create_agg_path(root,
9251 : : partial_unique_rel,
9252 : : path,
9253 : : cheapest_partial_path->pathtarget,
9254 : : AGG_HASHED,
9255 : : AGGSPLIT_SIMPLE,
9256 : : groupClause,
9257 : : NIL,
9258 : : NULL,
9259 : : partial_unique_rel->rows);
9260 : :
9261 : 3132 : add_partial_path(partial_unique_rel, path);
9262 : : }
9263 : :
9264 [ + - ]: 3132 : if (partial_unique_rel->partial_pathlist != NIL)
9265 : : {
9266 : 3132 : generate_useful_gather_paths(root, partial_unique_rel, true);
9267 : 3132 : set_cheapest(partial_unique_rel);
9268 : :
9269 : : /*
9270 : : * Finally, create paths to unique-ify the final result. This step is
9271 : : * needed to remove any duplicates due to combining rows from parallel
9272 : : * workers.
9273 : : */
9274 : 3132 : create_final_unique_paths(root, partial_unique_rel,
9275 : : sortPathkeys, groupClause,
9276 : : sjinfo, unique_rel);
9277 : : }
9278 : : }
9279 : :
9280 : : /*
9281 : : * Choose a unique name for some subroot.
9282 : : *
9283 : : * Modifies glob->subplanNames to track names already used.
9284 : : */
9285 : : char *
235 rhaas@postgresql.org 9286 : 65679 : choose_plan_name(PlannerGlobal *glob, const char *name, bool always_number)
9287 : : {
9288 : : unsigned n;
9289 : :
9290 : : /*
9291 : : * If a numeric suffix is not required, then search the list of
9292 : : * previously-assigned names for a match. If none is found, then we can
9293 : : * use the provided name without modification.
9294 : : */
9295 [ + + ]: 65679 : if (!always_number)
9296 : : {
9297 : 19388 : bool found = false;
9298 : :
9299 [ + + + + : 46679 : foreach_ptr(char, subplan_name, glob->subplanNames)
+ + ]
9300 : : {
9301 [ + + ]: 12280 : if (strcmp(subplan_name, name) == 0)
9302 : : {
9303 : 4377 : found = true;
9304 : 4377 : break;
9305 : : }
9306 : : }
9307 : :
9308 [ + + ]: 19388 : if (!found)
9309 : : {
9310 : : /* pstrdup here is just to avoid cast-away-const */
9311 : 15011 : char *chosen_name = pstrdup(name);
9312 : :
9313 : 15011 : glob->subplanNames = lappend(glob->subplanNames, chosen_name);
9314 : 15011 : return chosen_name;
9315 : : }
9316 : : }
9317 : :
9318 : : /*
9319 : : * If a numeric suffix is required or if the un-suffixed name is already
9320 : : * in use, then loop until we find a positive integer that produces a
9321 : : * novel name.
9322 : : */
9323 : 50668 : for (n = 1; true; ++n)
9324 : 43502 : {
9325 : 94170 : char *proposed_name = psprintf("%s_%u", name, n);
9326 : 94170 : bool found = false;
9327 : :
9328 [ + + + + : 350916 : foreach_ptr(char, subplan_name, glob->subplanNames)
+ + ]
9329 : : {
9330 [ + + ]: 206078 : if (strcmp(subplan_name, proposed_name) == 0)
9331 : : {
9332 : 43502 : found = true;
9333 : 43502 : break;
9334 : : }
9335 : : }
9336 : :
9337 [ + + ]: 94170 : if (!found)
9338 : : {
9339 : 50668 : glob->subplanNames = lappend(glob->subplanNames, proposed_name);
9340 : 50668 : return proposed_name;
9341 : : }
9342 : :
9343 : 43502 : pfree(proposed_name);
9344 : : }
9345 : : }
|