Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * prepunion.c
4 : : * Routines to plan set-operation queries. The filename is a leftover
5 : : * from a time when only UNIONs were implemented.
6 : : *
7 : : * There are two code paths in the planner for set-operation queries.
8 : : * If a subquery consists entirely of simple UNION ALL operations, it
9 : : * is converted into an "append relation". Otherwise, it is handled
10 : : * by the general code in this module (plan_set_operations and its
11 : : * subroutines). There is some support code here for the append-relation
12 : : * case, but most of the heavy lifting for that is done elsewhere,
13 : : * notably in prepjointree.c and allpaths.c.
14 : : *
15 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
16 : : * Portions Copyright (c) 1994, Regents of the University of California
17 : : *
18 : : *
19 : : * IDENTIFICATION
20 : : * src/backend/optimizer/prep/prepunion.c
21 : : *
22 : : *-------------------------------------------------------------------------
23 : : */
24 : : #include "postgres.h"
25 : :
26 : : #include <math.h>
27 : :
28 : : #include "access/htup_details.h"
29 : : #include "catalog/pg_type.h"
30 : : #include "miscadmin.h"
31 : : #include "nodes/makefuncs.h"
32 : : #include "nodes/nodeFuncs.h"
33 : : #include "optimizer/cost.h"
34 : : #include "optimizer/pathnode.h"
35 : : #include "optimizer/paths.h"
36 : : #include "optimizer/planner.h"
37 : : #include "optimizer/prep.h"
38 : : #include "optimizer/tlist.h"
39 : : #include "parser/parse_coerce.h"
40 : : #include "port/pg_bitutils.h"
41 : : #include "utils/selfuncs.h"
42 : :
43 : :
44 : : static RelOptInfo *recurse_set_operations(Node *setOp, PlannerInfo *root,
45 : : SetOperationStmt *parentOp,
46 : : List *colTypes, List *colCollations,
47 : : List *refnames_tlist,
48 : : List **pTargetList,
49 : : bool *istrivial_tlist);
50 : : static RelOptInfo *generate_recursion_path(SetOperationStmt *setOp,
51 : : PlannerInfo *root,
52 : : List *refnames_tlist,
53 : : List **pTargetList);
54 : : static void build_setop_child_paths(PlannerInfo *root, RelOptInfo *rel,
55 : : bool trivial_tlist, List *child_tlist,
56 : : List *interesting_pathkeys,
57 : : double *pNumGroups);
58 : : static RelOptInfo *generate_union_paths(SetOperationStmt *op, PlannerInfo *root,
59 : : List *refnames_tlist,
60 : : List **pTargetList);
61 : : static RelOptInfo *generate_nonunion_paths(SetOperationStmt *op, PlannerInfo *root,
62 : : List *refnames_tlist,
63 : : List **pTargetList);
64 : : static List *plan_union_children(PlannerInfo *root,
65 : : SetOperationStmt *top_union,
66 : : List *refnames_tlist,
67 : : List **tlist_list,
68 : : List **istrivial_tlist);
69 : : static void postprocess_setop_rel(PlannerInfo *root, RelOptInfo *rel);
70 : : static List *generate_setop_tlist(List *colTypes, List *colCollations,
71 : : Index varno,
72 : : bool hack_constants,
73 : : List *input_tlist,
74 : : List *refnames_tlist,
75 : : bool *trivial_tlist);
76 : : static List *generate_append_tlist(List *colTypes, List *colCollations,
77 : : List *input_tlists,
78 : : List *refnames_tlist);
79 : : static List *generate_setop_grouplist(SetOperationStmt *op, List *targetlist);
80 : : static PathTarget *create_setop_pathtarget(PlannerInfo *root, List *tlist,
81 : : List *child_pathlist);
82 : :
83 : :
84 : : /*
85 : : * plan_set_operations
86 : : *
87 : : * Plans the queries for a tree of set operations (UNION/INTERSECT/EXCEPT)
88 : : *
89 : : * This routine only deals with the setOperations tree of the given query.
90 : : * Any top-level ORDER BY requested in root->parse->sortClause will be handled
91 : : * when we return to grouping_planner; likewise for LIMIT.
92 : : *
93 : : * What we return is an "upperrel" RelOptInfo containing at least one Path
94 : : * that implements the set-operation tree. In addition, root->processed_tlist
95 : : * receives a targetlist representing the output of the topmost setop node.
96 : : */
97 : : RelOptInfo *
98 : 5096 : plan_set_operations(PlannerInfo *root)
99 : : {
100 : 5096 : Query *parse = root->parse;
101 : 5096 : SetOperationStmt *topop = castNode(SetOperationStmt, parse->setOperations);
102 : : Node *node;
103 : : RangeTblEntry *leftmostRTE;
104 : : Query *leftmostQuery;
105 : : RelOptInfo *setop_rel;
106 : : List *top_tlist;
107 : :
108 : : Assert(topop);
109 : :
110 : : /* check for unsupported stuff */
111 : : Assert(parse->jointree->fromlist == NIL);
112 : : Assert(parse->jointree->quals == NULL);
113 : : Assert(parse->groupClause == NIL);
114 : : Assert(parse->havingQual == NULL);
115 : : Assert(parse->windowClause == NIL);
116 : : Assert(parse->distinctClause == NIL);
117 : :
118 : : /*
119 : : * In the outer query level, equivalence classes are limited to classes
120 : : * which define that the top-level target entry is equivalent to the
121 : : * corresponding child target entry. There won't be any equivalence class
122 : : * merging. Mark that merging is complete to allow us to make pathkeys.
123 : : */
124 : : Assert(root->eq_classes == NIL);
125 : 5096 : root->ec_merging_done = true;
126 : :
127 : : /*
128 : : * We'll need to build RelOptInfos for each of the leaf subqueries, which
129 : : * are RTE_SUBQUERY rangetable entries in this Query. Prepare the index
130 : : * arrays for those, and for AppendRelInfos in case they're needed.
131 : : */
132 : 5096 : setup_simple_rel_arrays(root);
133 : :
134 : : /*
135 : : * Find the leftmost component Query. We need to use its column names for
136 : : * all generated tlists (else SELECT INTO won't work right).
137 : : */
138 : 5096 : node = topop->larg;
139 [ + - + + ]: 8155 : while (node && IsA(node, SetOperationStmt))
140 : 3059 : node = ((SetOperationStmt *) node)->larg;
141 : : Assert(node && IsA(node, RangeTblRef));
142 : 5096 : leftmostRTE = root->simple_rte_array[((RangeTblRef *) node)->rtindex];
143 : 5096 : leftmostQuery = leftmostRTE->subquery;
144 : : Assert(leftmostQuery != NULL);
145 : :
146 : : /*
147 : : * If the topmost node is a recursive union, it needs special processing.
148 : : */
149 [ + + ]: 5096 : if (root->hasRecursion)
150 : : {
151 : 742 : setop_rel = generate_recursion_path(topop, root,
152 : : leftmostQuery->targetList,
153 : : &top_tlist);
154 : : }
155 : : else
156 : : {
157 : : bool trivial_tlist;
158 : :
159 : : /*
160 : : * Recurse on setOperations tree to generate paths for set ops. The
161 : : * final output paths should have just the column types shown as the
162 : : * output from the top-level node.
163 : : */
164 : 4354 : setop_rel = recurse_set_operations((Node *) topop, root,
165 : : NULL, /* no parent */
166 : : topop->colTypes, topop->colCollations,
167 : : leftmostQuery->targetList,
168 : : &top_tlist,
169 : : &trivial_tlist);
170 : : }
171 : :
172 : : /* Must return the built tlist into root->processed_tlist. */
173 : 5080 : root->processed_tlist = top_tlist;
174 : :
175 : 5080 : return setop_rel;
176 : : }
177 : :
178 : : /*
179 : : * recurse_set_operations
180 : : * Recursively handle one step in a tree of set operations
181 : : *
182 : : * setOp: current step (could be a SetOperationStmt or a leaf RangeTblRef)
183 : : * parentOp: parent step, or NULL if none (but see below)
184 : : * colTypes: OID list of set-op's result column datatypes
185 : : * colCollations: OID list of set-op's result column collations
186 : : * refnames_tlist: targetlist to take column names from
187 : : *
188 : : * parentOp should be passed as NULL unless that step is interested in
189 : : * getting sorted output from this step. ("Sorted" means "sorted according
190 : : * to the default btree opclasses of the result column datatypes".)
191 : : *
192 : : * Returns a RelOptInfo for the subtree, as well as these output parameters:
193 : : * *pTargetList: receives the fully-fledged tlist for the subtree's top plan
194 : : * *istrivial_tlist: true if, and only if, datatypes between parent and child
195 : : * match.
196 : : *
197 : : * If setOp is a leaf node, this function plans the sub-query but does
198 : : * not populate the pathlist of the returned RelOptInfo. The caller will
199 : : * generate SubqueryScan paths using useful path(s) of the subquery (see
200 : : * build_setop_child_paths). But this function does build the paths for
201 : : * set-operation nodes.
202 : : *
203 : : * The pTargetList output parameter is mostly redundant with the pathtarget
204 : : * of the returned RelOptInfo, but for the moment we need it because much of
205 : : * the logic in this file depends on flag columns being marked resjunk.
206 : : * XXX Now that there are no flag columns and hence no resjunk columns, we
207 : : * could probably refactor this file to deal only in pathtargets.
208 : : *
209 : : * We don't have to care about typmods here: the only allowed difference
210 : : * between set-op input and output typmods is input is a specific typmod
211 : : * and output is -1, and that does not require a coercion.
212 : : */
213 : : static RelOptInfo *
214 : 17835 : recurse_set_operations(Node *setOp, PlannerInfo *root,
215 : : SetOperationStmt *parentOp,
216 : : List *colTypes, List *colCollations,
217 : : List *refnames_tlist,
218 : : List **pTargetList,
219 : : bool *istrivial_tlist)
220 : : {
221 : : RelOptInfo *rel;
222 : :
223 : 17835 : *istrivial_tlist = true; /* for now */
224 : :
225 : : /* Guard against stack overflow due to overly complex setop nests */
226 : 17835 : check_stack_depth();
227 : :
228 [ + + ]: 17835 : if (IsA(setOp, RangeTblRef))
229 : : {
230 : 13311 : RangeTblRef *rtr = (RangeTblRef *) setOp;
231 : 13311 : RangeTblEntry *rte = root->simple_rte_array[rtr->rtindex];
232 : 13311 : Query *subquery = rte->subquery;
233 : : PlannerInfo *subroot;
234 : : List *tlist;
235 : : bool trivial_tlist;
236 : : char *plan_name;
237 : :
238 : : Assert(subquery != NULL);
239 : :
240 : : /* Build a RelOptInfo for this leaf subquery. */
241 : 13311 : rel = build_simple_rel(root, rtr->rtindex, NULL);
242 : :
243 : : /* plan_params should not be in use in current query level */
244 : : Assert(root->plan_params == NIL);
245 : :
246 : : /*
247 : : * Generate a subroot and Paths for the subquery. If we have a
248 : : * parentOp, pass that down to encourage subquery_planner to consider
249 : : * suitably-sorted Paths.
250 : : */
251 : 13311 : plan_name = choose_plan_name(root->glob, "setop", true);
252 : 13311 : subroot = rel->subroot = subquery_planner(root->glob, subquery,
253 : : plan_name, root, NULL,
254 : : false, root->tuple_fraction,
255 : : parentOp);
256 : :
257 : : /*
258 : : * It should not be possible for the primitive query to contain any
259 : : * cross-references to other primitive queries in the setop tree.
260 : : */
261 [ - + ]: 13311 : if (root->plan_params)
262 [ # # ]: 0 : elog(ERROR, "unexpected outer reference in set operation subquery");
263 : :
264 : : /* Figure out the appropriate target list for this subquery. */
265 : 13311 : tlist = generate_setop_tlist(colTypes, colCollations,
266 : 13311 : rtr->rtindex,
267 : : true,
268 : : subroot->processed_tlist,
269 : : refnames_tlist,
270 : : &trivial_tlist);
271 : 13311 : rel->reltarget = create_pathtarget(root, tlist);
272 : :
273 : : /* Return the fully-fledged tlist to caller, too */
274 : 13311 : *pTargetList = tlist;
275 : 13311 : *istrivial_tlist = trivial_tlist;
276 : : }
277 [ + - ]: 4524 : else if (IsA(setOp, SetOperationStmt))
278 : : {
279 : 4524 : SetOperationStmt *op = (SetOperationStmt *) setOp;
280 : :
281 : : /* UNIONs are much different from INTERSECT/EXCEPT */
282 [ + + ]: 4524 : if (op->op == SETOP_UNION)
283 : 3802 : rel = generate_union_paths(op, root,
284 : : refnames_tlist,
285 : : pTargetList);
286 : : else
287 : 722 : rel = generate_nonunion_paths(op, root,
288 : : refnames_tlist,
289 : : pTargetList);
290 : :
291 : : /*
292 : : * If necessary, add a Result node to project the caller-requested
293 : : * output columns.
294 : : *
295 : : * XXX you don't really want to know about this: setrefs.c will apply
296 : : * fix_upper_expr() to the Result node's tlist. This would fail if the
297 : : * Vars generated by generate_setop_tlist() were not exactly equal()
298 : : * to the corresponding tlist entries of the subplan. However, since
299 : : * the subplan was generated by generate_union_paths() or
300 : : * generate_nonunion_paths(), and hence its tlist was generated by
301 : : * generate_append_tlist() or generate_setop_tlist(), this will work.
302 : : * We just tell generate_setop_tlist() to use varno 0.
303 : : */
304 [ + + ]: 4512 : if (!tlist_same_datatypes(*pTargetList, colTypes, false) ||
305 [ - + ]: 4492 : !tlist_same_collations(*pTargetList, colCollations, false))
306 : : {
307 : : PathTarget *target;
308 : : bool trivial_tlist;
309 : : ListCell *lc;
310 : :
311 : 20 : *pTargetList = generate_setop_tlist(colTypes, colCollations,
312 : : 0,
313 : : false,
314 : : *pTargetList,
315 : : refnames_tlist,
316 : : &trivial_tlist);
317 : 20 : *istrivial_tlist = trivial_tlist;
318 : 20 : target = create_pathtarget(root, *pTargetList);
319 : :
320 : : /* Apply projection to each path */
321 [ + - + + : 40 : foreach(lc, rel->pathlist)
+ + ]
322 : : {
323 : 20 : Path *subpath = (Path *) lfirst(lc);
324 : : Path *path;
325 : :
326 : : Assert(subpath->param_info == NULL);
327 : 20 : path = apply_projection_to_path(root, subpath->parent,
328 : : subpath, target);
329 : : /* If we had to add a Result, path is different from subpath */
330 [ + + ]: 20 : if (path != subpath)
331 : 15 : lfirst(lc) = path;
332 : : }
333 : :
334 : : /* Apply projection to each partial path */
335 [ - + - - : 20 : foreach(lc, rel->partial_pathlist)
- + ]
336 : : {
337 : 0 : Path *subpath = (Path *) lfirst(lc);
338 : : Path *path;
339 : :
340 : : Assert(subpath->param_info == NULL);
341 : :
342 : : /* avoid apply_projection_to_path, in case of multiple refs */
343 : 0 : path = (Path *) create_projection_path(root, subpath->parent,
344 : : subpath, target);
345 : 0 : lfirst(lc) = path;
346 : : }
347 : : }
348 : 4512 : postprocess_setop_rel(root, rel);
349 : : }
350 : : else
351 : : {
352 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
353 : : (int) nodeTag(setOp));
354 : : *pTargetList = NIL;
355 : : rel = NULL; /* keep compiler quiet */
356 : : }
357 : :
358 : 17823 : return rel;
359 : : }
360 : :
361 : : /*
362 : : * Generate paths for a recursive UNION node
363 : : */
364 : : static RelOptInfo *
365 : 742 : generate_recursion_path(SetOperationStmt *setOp, PlannerInfo *root,
366 : : List *refnames_tlist,
367 : : List **pTargetList)
368 : : {
369 : : RelOptInfo *result_rel;
370 : : Path *path;
371 : : RelOptInfo *lrel,
372 : : *rrel;
373 : : Path *lpath;
374 : : Path *rpath;
375 : : List *lpath_tlist;
376 : : bool lpath_trivial_tlist;
377 : : List *rpath_tlist;
378 : : bool rpath_trivial_tlist;
379 : : List *tlist;
380 : : List *groupList;
381 : : double dNumGroups;
382 : :
383 : : /* Parser should have rejected other cases */
384 [ - + ]: 742 : if (setOp->op != SETOP_UNION)
385 [ # # ]: 0 : elog(ERROR, "only UNION queries can be recursive");
386 : : /* Worktable ID should be assigned */
387 : : Assert(root->wt_param_id >= 0);
388 : :
389 : : /*
390 : : * Unlike a regular UNION node, process the left and right inputs
391 : : * separately without any intention of combining them into one Append.
392 : : */
393 : 742 : lrel = recurse_set_operations(setOp->larg, root,
394 : : NULL, /* no value in sorted results */
395 : : setOp->colTypes, setOp->colCollations,
396 : : refnames_tlist,
397 : : &lpath_tlist,
398 : : &lpath_trivial_tlist);
399 [ + - ]: 742 : if (lrel->rtekind == RTE_SUBQUERY)
400 : 742 : build_setop_child_paths(root, lrel, lpath_trivial_tlist, lpath_tlist,
401 : : NIL, NULL);
402 : 742 : lpath = lrel->cheapest_total_path;
403 : : /* The right path will want to look at the left one ... */
404 : 742 : root->non_recursive_path = lpath;
405 : 742 : rrel = recurse_set_operations(setOp->rarg, root,
406 : : NULL, /* no value in sorted results */
407 : : setOp->colTypes, setOp->colCollations,
408 : : refnames_tlist,
409 : : &rpath_tlist,
410 : : &rpath_trivial_tlist);
411 [ + + ]: 742 : if (rrel->rtekind == RTE_SUBQUERY)
412 : 737 : build_setop_child_paths(root, rrel, rpath_trivial_tlist, rpath_tlist,
413 : : NIL, NULL);
414 : 742 : rpath = rrel->cheapest_total_path;
415 : 742 : root->non_recursive_path = NULL;
416 : :
417 : : /*
418 : : * Generate tlist for RecursiveUnion path node --- same as in Append cases
419 : : */
420 : 742 : tlist = generate_append_tlist(setOp->colTypes, setOp->colCollations,
421 : : list_make2(lpath_tlist, rpath_tlist),
422 : : refnames_tlist);
423 : :
424 : 742 : *pTargetList = tlist;
425 : :
426 : : /* Build result relation. */
427 : 742 : result_rel = fetch_upper_rel(root, UPPERREL_SETOP,
428 : 742 : bms_union(lrel->relids, rrel->relids));
429 : 742 : result_rel->reltarget = create_pathtarget(root, tlist);
430 : :
431 : : /*
432 : : * If UNION, identify the grouping operators
433 : : */
434 [ + + ]: 742 : if (setOp->all)
435 : : {
436 : 502 : groupList = NIL;
437 : 502 : dNumGroups = 0;
438 : : }
439 : : else
440 : : {
441 : : /* Identify the grouping semantics */
442 : 240 : groupList = generate_setop_grouplist(setOp, tlist);
443 : :
444 : : /* We only support hashing here */
445 [ + + ]: 240 : if (!grouping_is_hashable(groupList))
446 [ + - ]: 4 : ereport(ERROR,
447 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
448 : : errmsg("could not implement recursive UNION"),
449 : : errdetail("All column datatypes must be hashable.")));
450 : :
451 : : /*
452 : : * For the moment, take the number of distinct groups as equal to the
453 : : * total input size, ie, the worst case.
454 : : */
455 : 236 : dNumGroups = lpath->rows + rpath->rows * 10;
456 : : }
457 : :
458 : : /*
459 : : * And make the path node.
460 : : */
461 : 738 : path = (Path *) create_recursiveunion_path(root,
462 : : result_rel,
463 : : lpath,
464 : : rpath,
465 : 738 : result_rel->reltarget,
466 : : groupList,
467 : : root->wt_param_id,
468 : : dNumGroups);
469 : :
470 : 738 : add_path(result_rel, path);
471 : 738 : postprocess_setop_rel(root, result_rel);
472 : 738 : return result_rel;
473 : : }
474 : :
475 : : /*
476 : : * build_setop_child_paths
477 : : * Build paths for the set op child relation denoted by 'rel'.
478 : : *
479 : : * 'rel' is an RTE_SUBQUERY relation. We have already generated paths within
480 : : * the subquery's subroot; the task here is to create SubqueryScan paths for
481 : : * 'rel', representing scans of the useful subquery paths.
482 : : *
483 : : * interesting_pathkeys: if not NIL, also include paths that suit these
484 : : * pathkeys, sorting any unsorted paths as required.
485 : : * *pNumGroups: if not NULL, we estimate the number of distinct groups
486 : : * in the result, and store it there.
487 : : */
488 : : static void
489 : 13295 : build_setop_child_paths(PlannerInfo *root, RelOptInfo *rel,
490 : : bool trivial_tlist, List *child_tlist,
491 : : List *interesting_pathkeys, double *pNumGroups)
492 : : {
493 : : RelOptInfo *final_rel;
494 : 13295 : List *setop_pathkeys = rel->subroot->setop_pathkeys;
495 : : ListCell *lc;
496 : :
497 : : /* it can't be a set op child rel if it's not a subquery */
498 : : Assert(rel->rtekind == RTE_SUBQUERY);
499 : :
500 : : /* when sorting is needed, add child rel equivalences */
501 [ + + ]: 13295 : if (interesting_pathkeys != NIL)
502 : 10404 : add_setop_child_rel_equivalences(root,
503 : : rel,
504 : : child_tlist,
505 : : interesting_pathkeys);
506 : :
507 : : /*
508 : : * Mark rel with estimated output rows, width, etc. Note that we have to
509 : : * do this before generating outer-query paths, else cost_subqueryscan is
510 : : * not happy.
511 : : */
512 : 13295 : set_subquery_size_estimates(root, rel);
513 : :
514 : : /*
515 : : * Since we may want to add a partial path to this relation, we must set
516 : : * its consider_parallel flag correctly.
517 : : */
518 : 13295 : final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
519 : 13295 : rel->consider_parallel = final_rel->consider_parallel;
520 : :
521 : : /* Generate subquery scan paths for any interesting path in final_rel */
522 [ + - + + : 34540 : foreach(lc, final_rel->pathlist)
+ + ]
523 : : {
524 : 21245 : Path *subpath = (Path *) lfirst(lc);
525 : : List *pathkeys;
526 : 21245 : Path *cheapest_input_path = final_rel->cheapest_total_path;
527 : : bool is_sorted;
528 : : int presorted_keys;
529 : :
530 : : /* If the input rel is dummy, propagate that to this query level */
531 [ + + ]: 21245 : if (is_dummy_rel(final_rel))
532 : : {
533 : 92 : mark_dummy_rel(rel);
534 : 3016 : continue;
535 : : }
536 : :
537 : : /*
538 : : * Include the cheapest path as-is so that the set operation can be
539 : : * cheaply implemented using a method which does not require the input
540 : : * to be sorted.
541 : : */
542 [ + + ]: 21153 : if (subpath == cheapest_input_path)
543 : : {
544 : : /* Convert subpath's pathkeys to outer representation */
545 : 13203 : pathkeys = convert_subquery_pathkeys(root, rel, subpath->pathkeys,
546 : : make_tlist_from_pathtarget(subpath->pathtarget));
547 : :
548 : : /* Generate outer path using this subpath */
549 : 13203 : add_path(rel, (Path *) create_subqueryscan_path(root,
550 : : rel,
551 : : subpath,
552 : : trivial_tlist,
553 : : pathkeys,
554 : : NULL));
555 : : }
556 : :
557 : : /* skip dealing with sorted paths if the setop doesn't need them */
558 [ + + ]: 21153 : if (interesting_pathkeys == NIL)
559 : 2909 : continue;
560 : :
561 : : /*
562 : : * Create paths to suit final sort order required for setop_pathkeys.
563 : : * Here we'll sort the cheapest input path (if not sorted already) and
564 : : * incremental sort any paths which are partially sorted.
565 : : */
566 : 18244 : is_sorted = pathkeys_count_contained_in(setop_pathkeys,
567 : : subpath->pathkeys,
568 : : &presorted_keys);
569 : :
570 [ + + ]: 18244 : if (!is_sorted)
571 : : {
572 : 12147 : double limittuples = rel->subroot->limit_tuples;
573 : :
574 : : /*
575 : : * Try at least sorting the cheapest path and also try
576 : : * incrementally sorting any path which is partially sorted
577 : : * already (no need to deal with paths which have presorted keys
578 : : * when incremental sort is disabled unless it's the cheapest
579 : : * input path).
580 : : */
581 [ + + ]: 12147 : if (subpath != cheapest_input_path &&
582 [ + + - + ]: 2651 : (presorted_keys == 0 || !enable_incremental_sort))
583 : 15 : continue;
584 : :
585 : : /*
586 : : * We've no need to consider both a sort and incremental sort.
587 : : * We'll just do a sort if there are no presorted keys and an
588 : : * incremental sort when there are presorted keys.
589 : : */
590 [ + + + + ]: 12132 : if (presorted_keys == 0 || !enable_incremental_sort)
591 : 9496 : subpath = (Path *) create_sort_path(rel->subroot,
592 : : final_rel,
593 : : subpath,
594 : : setop_pathkeys,
595 : : limittuples);
596 : : else
597 : 2636 : subpath = (Path *) create_incremental_sort_path(rel->subroot,
598 : : final_rel,
599 : : subpath,
600 : : setop_pathkeys,
601 : : presorted_keys,
602 : : limittuples);
603 : : }
604 : :
605 : : /*
606 : : * subpath is now sorted, so add it to the pathlist. We already added
607 : : * the cheapest_input_path above, so don't add it again unless we just
608 : : * sorted it.
609 : : */
610 [ + + ]: 18229 : if (subpath != cheapest_input_path)
611 : : {
612 : : /* Convert subpath's pathkeys to outer representation */
613 : 17405 : pathkeys = convert_subquery_pathkeys(root, rel, subpath->pathkeys,
614 : : make_tlist_from_pathtarget(subpath->pathtarget));
615 : :
616 : : /* Generate outer path using this subpath */
617 : 17405 : add_path(rel, (Path *) create_subqueryscan_path(root,
618 : : rel,
619 : : subpath,
620 : : trivial_tlist,
621 : : pathkeys,
622 : : NULL));
623 : : }
624 : : }
625 : :
626 : : /* if consider_parallel is false, there should be no partial paths */
627 : : Assert(final_rel->consider_parallel ||
628 : : final_rel->partial_pathlist == NIL);
629 : :
630 : : /*
631 : : * If we have a partial path for the child relation, we can use that to
632 : : * build a partial path for this relation. But there's no point in
633 : : * considering any path but the cheapest.
634 : : */
635 [ + + + - ]: 13295 : if (rel->consider_parallel && bms_is_empty(rel->lateral_relids) &&
636 [ + + ]: 9181 : final_rel->partial_pathlist != NIL)
637 : : {
638 : : Path *partial_subpath;
639 : : Path *partial_path;
640 : :
641 : 15 : partial_subpath = linitial(final_rel->partial_pathlist);
642 : : partial_path = (Path *)
643 : 15 : create_subqueryscan_path(root, rel, partial_subpath,
644 : : trivial_tlist,
645 : : NIL, NULL);
646 : 15 : add_partial_path(rel, partial_path);
647 : : }
648 : :
649 : 13295 : postprocess_setop_rel(root, rel);
650 : :
651 : : /*
652 : : * Estimate number of groups if caller wants it. If the subquery used
653 : : * grouping or aggregation, its output is probably mostly unique anyway;
654 : : * otherwise do statistical estimation.
655 : : *
656 : : * XXX you don't really want to know about this: we do the estimation
657 : : * using the subroot->parse's original targetlist expressions, not the
658 : : * subroot->processed_tlist which might seem more appropriate. The reason
659 : : * is that if the subquery is itself a setop, it may return a
660 : : * processed_tlist containing "varno 0" Vars generated by
661 : : * generate_append_tlist, and those would confuse estimate_num_groups
662 : : * mightily. We ought to get rid of the "varno 0" hack, but that requires
663 : : * a redesign of the parsetree representation of setops, so that there can
664 : : * be an RTE corresponding to each setop's output. Note, we use this not
665 : : * subquery's targetlist but subroot->parse's targetlist, because it was
666 : : * revised by self-join removal. subquery's targetlist might contain the
667 : : * references to the removed relids.
668 : : */
669 [ + + ]: 13295 : if (pNumGroups)
670 : : {
671 : 10730 : PlannerInfo *subroot = rel->subroot;
672 : 10730 : Query *subquery = subroot->parse;
673 : :
674 [ + - + - ]: 10730 : if (subquery->groupClause || subquery->groupingSets ||
675 [ + + + - ]: 10730 : subquery->distinctClause || subroot->hasHavingQual ||
676 [ + + ]: 10720 : subquery->hasAggs)
677 : 12 : *pNumGroups = rel->cheapest_total_path->rows;
678 : : else
679 : 10718 : *pNumGroups = estimate_num_groups(subroot,
680 : 10718 : get_tlist_exprs(subroot->parse->targetList, false),
681 : 10718 : rel->cheapest_total_path->rows,
682 : : NULL,
683 : : NULL);
684 : : }
685 : 13295 : }
686 : :
687 : : /*
688 : : * Generate paths for a UNION or UNION ALL node
689 : : */
690 : : static RelOptInfo *
691 : 3802 : generate_union_paths(SetOperationStmt *op, PlannerInfo *root,
692 : : List *refnames_tlist,
693 : : List **pTargetList)
694 : : {
695 : 3802 : Relids relids = NULL;
696 : : RelOptInfo *result_rel;
697 : : ListCell *lc;
698 : : ListCell *lc2;
699 : : ListCell *lc3;
700 : 3802 : AppendPathInput cheapest = {0};
701 : 3802 : AppendPathInput ordered = {0};
702 : 3802 : AppendPathInput partial = {0};
703 : 3802 : bool partial_paths_valid = true;
704 : 3802 : bool consider_parallel = true;
705 : : List *rellist;
706 : : List *tlist_list;
707 : : List *trivial_tlist_list;
708 : : List *tlist;
709 : 3802 : List *groupList = NIL;
710 : : Path *apath;
711 : 3802 : Path *gpath = NULL;
712 : 3802 : bool try_sorted = false;
713 : 3802 : List *union_pathkeys = NIL;
714 : 3802 : double dNumChildGroups = 0;
715 : :
716 : : /*
717 : : * If any of my children are identical UNION nodes (same op, all-flag, and
718 : : * colTypes/colCollations) then they can be merged into this node so that
719 : : * we generate only one Append/MergeAppend and unique-ification for the
720 : : * lot. Recurse to find such nodes.
721 : : */
722 : 3802 : rellist = plan_union_children(root,
723 : : op,
724 : : refnames_tlist,
725 : : &tlist_list,
726 : : &trivial_tlist_list);
727 : :
728 : : /*
729 : : * Generate tlist for Append/MergeAppend plan node.
730 : : *
731 : : * The tlist for an Append plan isn't important as far as the Append is
732 : : * concerned, but we must make it look real anyway for the benefit of the
733 : : * next plan level up.
734 : : */
735 : 3802 : tlist = generate_append_tlist(op->colTypes, op->colCollations,
736 : : tlist_list, refnames_tlist);
737 : 3802 : *pTargetList = tlist;
738 : :
739 : : /* For UNIONs (not UNION ALL), try sorting, if sorting is possible */
740 [ + + ]: 3802 : if (!op->all)
741 : : {
742 : : /* Identify the grouping semantics */
743 : 3321 : groupList = generate_setop_grouplist(op, tlist);
744 : :
745 [ + + ]: 3321 : if (grouping_is_sortable(op->groupClauses))
746 : : {
747 : 3253 : try_sorted = true;
748 : : /* Determine the pathkeys for sorting by the whole target list */
749 : 3253 : union_pathkeys = make_pathkeys_for_sortclauses(root, groupList,
750 : : tlist);
751 : :
752 : 3253 : root->query_pathkeys = union_pathkeys;
753 : : }
754 : : }
755 : :
756 : : /*
757 : : * Now that we've got the append target list, we can build the union child
758 : : * paths.
759 : : */
760 [ + - + + : 14355 : forthree(lc, rellist, lc2, trivial_tlist_list, lc3, tlist_list)
+ - + + +
- + + + +
+ - + - +
+ ]
761 : : {
762 : 10553 : RelOptInfo *rel = lfirst(lc);
763 : 10553 : bool trivial_tlist = lfirst_int(lc2);
764 : 10553 : List *child_tlist = lfirst_node(List, lc3);
765 : 10553 : double childGroups = 0;
766 : :
767 : : /* only build paths for the union children */
768 [ + + ]: 10553 : if (rel->rtekind == RTE_SUBQUERY)
769 : 10423 : build_setop_child_paths(root, rel, trivial_tlist, child_tlist,
770 : : union_pathkeys,
771 [ + + ]: 10423 : op->all ? NULL : &childGroups);
772 : : else
773 : 130 : childGroups = rel->rows;
774 : :
775 : : /*
776 : : * For UNION (not UNION ALL), accumulate the per-child distinct-group
777 : : * estimates. This sum is the basis for the UNION's output estimate
778 : : * below: since distinct(A union B) <= distinct(A) + distinct(B), the
779 : : * union cannot have more distinct rows than its children do in total.
780 : : * Children that are known to be empty contribute nothing, so skip
781 : : * them.
782 : : */
783 [ + + + + ]: 10553 : if (!op->all && !is_dummy_rel(rel))
784 : 9313 : dNumChildGroups += childGroups;
785 : : }
786 : :
787 : : /* Build path lists and relid set. */
788 [ + - + + : 14355 : foreach(lc, rellist)
+ + ]
789 : : {
790 : 10553 : RelOptInfo *rel = lfirst(lc);
791 : : Path *ordered_path;
792 : :
793 : : /*
794 : : * Record the relids so that we can identify the correct
795 : : * UPPERREL_SETOP RelOptInfo below.
796 : : */
797 : 10553 : relids = bms_add_members(relids, rel->relids);
798 : :
799 : : /* Skip any UNION children that are proven not to yield any rows */
800 [ + + ]: 10553 : if (is_dummy_rel(rel))
801 : 52 : continue;
802 : :
803 : 21002 : cheapest.subpaths = lappend(cheapest.subpaths,
804 : 10501 : rel->cheapest_total_path);
805 : :
806 [ + + ]: 10501 : if (try_sorted)
807 : : {
808 : 3550 : ordered_path = get_cheapest_path_for_pathkeys(rel->pathlist,
809 : : union_pathkeys,
810 : : NULL,
811 : : TOTAL_COST,
812 : : false);
813 : :
814 [ + + ]: 3550 : if (ordered_path != NULL)
815 : 593 : ordered.subpaths = lappend(ordered.subpaths, ordered_path);
816 : : else
817 : : {
818 : : /*
819 : : * If we can't find a sorted path, just give up trying to
820 : : * generate a list of correctly sorted child paths. This can
821 : : * happen when type coercion was added to the targetlist due
822 : : * to mismatching types from the union children.
823 : : */
824 : 2957 : try_sorted = false;
825 : : }
826 : : }
827 : :
828 [ + + ]: 10501 : if (consider_parallel)
829 : : {
830 [ + + ]: 7554 : if (!rel->consider_parallel)
831 : : {
832 : 2839 : consider_parallel = false;
833 : 2839 : partial_paths_valid = false;
834 : : }
835 [ + + ]: 4715 : else if (rel->partial_pathlist == NIL)
836 : 4702 : partial_paths_valid = false;
837 : : else
838 : 13 : partial.partial_subpaths = lappend(partial.partial_subpaths,
839 : 13 : linitial(rel->partial_pathlist));
840 : : }
841 : : }
842 : :
843 : : /* Build result relation. */
844 : 3802 : result_rel = fetch_upper_rel(root, UPPERREL_SETOP, relids);
845 : 3802 : result_rel->reltarget = create_setop_pathtarget(root, tlist,
846 : : cheapest.subpaths);
847 : 3802 : result_rel->consider_parallel = consider_parallel;
848 : 3802 : result_rel->consider_startup = (root->tuple_fraction > 0);
849 : :
850 : : /* If all UNION children were dummy rels, make the resulting rel dummy */
851 [ + + ]: 3802 : if (cheapest.subpaths == NIL)
852 : : {
853 : 6 : mark_dummy_rel(result_rel);
854 : :
855 : 6 : return result_rel;
856 : : }
857 : :
858 : : /*
859 : : * Append the child results together using the cheapest paths from each
860 : : * union child.
861 : : */
862 : 3796 : apath = (Path *) create_append_path(root, result_rel, cheapest,
863 : : NIL, NULL, 0, false, -1);
864 : :
865 : : /*
866 : : * Although we told create_append_path to assign NIL pathkeys to the
867 : : * AppendPath, it may have overridden that (if there's just one surviving
868 : : * child path, it will use that path's pathkeys). However, createplan.c
869 : : * will fail because the append relation's tlist contains "varno 0" Vars
870 : : * (cf. generate_append_tlist), which won't match what is in the pathkeys.
871 : : * We need to fix that someday, but for now, just force the AppendPath's
872 : : * pathkeys back to NIL.
873 : : */
874 : 3796 : apath->pathkeys = NIL;
875 : :
876 : : /*
877 : : * Initialize the result row estimate to the total input size. This is
878 : : * correct for UNION ALL; for the UNION case it is overwritten below with
879 : : * the estimated number of distinct groups.
880 : : */
881 : 3796 : result_rel->rows = apath->rows;
882 : :
883 : : /*
884 : : * Now consider doing the same thing using the partial paths plus Append
885 : : * plus Gather.
886 : : */
887 [ + + ]: 3796 : if (partial_paths_valid)
888 : : {
889 : : Path *papath;
890 : 7 : int parallel_workers = 0;
891 : :
892 : : /* Find the highest number of workers requested for any subpath. */
893 [ + - + + : 20 : foreach(lc, partial.partial_subpaths)
+ + ]
894 : : {
895 : 13 : Path *subpath = lfirst(lc);
896 : :
897 : 13 : parallel_workers = Max(parallel_workers,
898 : : subpath->parallel_workers);
899 : : }
900 : : Assert(parallel_workers > 0);
901 : :
902 : : /*
903 : : * If the use of parallel append is permitted, always request at least
904 : : * log2(# of children) paths. We assume it can be useful to have
905 : : * extra workers in this case because they will be spread out across
906 : : * the children. The precise formula is just a guess; see
907 : : * add_paths_to_append_rel.
908 : : */
909 [ + - ]: 7 : if (enable_parallel_append)
910 : : {
911 [ + - ]: 7 : parallel_workers = Max(parallel_workers,
912 : : pg_leftmost_one_pos32(list_length(partial.partial_subpaths)) + 1);
913 : 7 : parallel_workers = Min(parallel_workers,
914 : : max_parallel_workers_per_gather);
915 : : }
916 : : Assert(parallel_workers > 0);
917 : :
918 : : papath = (Path *)
919 : 7 : create_append_path(root, result_rel, partial,
920 : : NIL, NULL, parallel_workers,
921 : : enable_parallel_append, -1);
922 : : /* See comment above about pathkeys vs. "varno 0" Vars */
923 : 7 : papath->pathkeys = NIL;
924 : :
925 : : gpath = (Path *)
926 : 7 : create_gather_path(root, result_rel, papath,
927 : 7 : result_rel->reltarget, NULL, NULL);
928 : : }
929 : :
930 [ + + ]: 3796 : if (!op->all)
931 : : {
932 : 3315 : bool can_sort = grouping_is_sortable(groupList);
933 : 3315 : bool can_hash = grouping_is_hashable(groupList);
934 : :
935 : : /*
936 : : * Check that the operators support sorting or hashing. The parser
937 : : * would have checked that individual grouping columns support at
938 : : * least one, but it doesn't verify that they all support the same
939 : : * method.
940 : : */
941 [ + + + + ]: 3315 : if (!can_sort && !can_hash)
942 [ + - ]: 4 : ereport(ERROR,
943 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
944 : : /* translator: %s is UNION */
945 : : errmsg("could not implement %s", "UNION"),
946 : : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
947 : :
948 : : /*
949 : : * result_rel->rows was initialized to the total input size above,
950 : : * which is the correct estimate for UNION ALL. A UNION removes
951 : : * duplicates, so override it with the estimated number of distinct
952 : : * groups.
953 : : */
954 : 3311 : result_rel->rows = dNumChildGroups;
955 : :
956 [ + + ]: 3311 : if (can_hash)
957 : : {
958 : : Path *path;
959 : :
960 : : /*
961 : : * Try a hash aggregate plan on 'apath'. This is the cheapest
962 : : * available path containing each append child.
963 : : */
964 : 3251 : path = (Path *) create_agg_path(root,
965 : : result_rel,
966 : : apath,
967 : 3251 : result_rel->reltarget,
968 : : AGG_HASHED,
969 : : AGGSPLIT_SIMPLE,
970 : : groupList,
971 : : NIL,
972 : : NULL,
973 : : dNumChildGroups);
974 : 3251 : add_path(result_rel, path);
975 : :
976 : : /* Try hash aggregate on the Gather path, if valid */
977 [ + + ]: 3251 : if (gpath != NULL)
978 : : {
979 : : /* Hashed aggregate plan --- no sort needed */
980 : 7 : path = (Path *) create_agg_path(root,
981 : : result_rel,
982 : : gpath,
983 : 7 : result_rel->reltarget,
984 : : AGG_HASHED,
985 : : AGGSPLIT_SIMPLE,
986 : : groupList,
987 : : NIL,
988 : : NULL,
989 : : dNumChildGroups);
990 : 7 : add_path(result_rel, path);
991 : : }
992 : : }
993 : :
994 [ + + ]: 3311 : if (can_sort)
995 : : {
996 : 3247 : Path *path = apath;
997 : :
998 : : /* Try Sort -> Unique on the Append path */
999 [ + + ]: 3247 : if (groupList != NIL)
1000 : 3212 : path = (Path *) create_sort_path(root, result_rel, path,
1001 : : make_pathkeys_for_sortclauses(root, groupList, tlist),
1002 : : -1.0);
1003 : :
1004 : 3247 : path = (Path *) create_unique_path(root,
1005 : : result_rel,
1006 : : path,
1007 : 3247 : list_length(path->pathkeys),
1008 : : dNumChildGroups);
1009 : :
1010 : 3247 : add_path(result_rel, path);
1011 : :
1012 : : /* Try Sort -> Unique on the Gather path, if set */
1013 [ + + ]: 3247 : if (gpath != NULL)
1014 : : {
1015 : 7 : path = gpath;
1016 : :
1017 : 7 : path = (Path *) create_sort_path(root, result_rel, path,
1018 : : make_pathkeys_for_sortclauses(root, groupList, tlist),
1019 : : -1.0);
1020 : :
1021 : 7 : path = (Path *) create_unique_path(root,
1022 : : result_rel,
1023 : : path,
1024 : 7 : list_length(path->pathkeys),
1025 : : dNumChildGroups);
1026 : 7 : add_path(result_rel, path);
1027 : : }
1028 : : }
1029 : :
1030 : : /*
1031 : : * Try making a MergeAppend path if we managed to find a path with the
1032 : : * correct pathkeys in each union child query.
1033 : : */
1034 [ + + + + ]: 3311 : if (try_sorted && groupList != NIL)
1035 : : {
1036 : : Path *path;
1037 : :
1038 : 255 : path = (Path *) create_merge_append_path(root,
1039 : : result_rel,
1040 : : ordered.subpaths,
1041 : : NIL,
1042 : : union_pathkeys,
1043 : : NULL);
1044 : :
1045 : : /* and make the MergeAppend unique */
1046 : 255 : path = (Path *) create_unique_path(root,
1047 : : result_rel,
1048 : : path,
1049 : : list_length(tlist),
1050 : : dNumChildGroups);
1051 : :
1052 : 255 : add_path(result_rel, path);
1053 : : }
1054 : : }
1055 : : else
1056 : : {
1057 : : /* UNION ALL */
1058 : 481 : add_path(result_rel, apath);
1059 : :
1060 [ - + ]: 481 : if (gpath != NULL)
1061 : 0 : add_path(result_rel, gpath);
1062 : : }
1063 : :
1064 : 3792 : return result_rel;
1065 : : }
1066 : :
1067 : : /*
1068 : : * Generate paths for an INTERSECT, INTERSECT ALL, EXCEPT, or EXCEPT ALL node
1069 : : */
1070 : : static RelOptInfo *
1071 : 722 : generate_nonunion_paths(SetOperationStmt *op, PlannerInfo *root,
1072 : : List *refnames_tlist,
1073 : : List **pTargetList)
1074 : : {
1075 : : RelOptInfo *result_rel;
1076 : : RelOptInfo *lrel,
1077 : : *rrel;
1078 : 722 : double save_fraction = root->tuple_fraction;
1079 : : Path *lpath,
1080 : : *rpath,
1081 : : *path;
1082 : : List *lpath_tlist,
1083 : : *rpath_tlist,
1084 : : *tlist,
1085 : : *groupList;
1086 : : bool lpath_trivial_tlist,
1087 : : rpath_trivial_tlist,
1088 : : result_trivial_tlist;
1089 : 722 : List *nonunion_pathkeys = NIL;
1090 : : double dLeftGroups,
1091 : : dRightGroups,
1092 : : dNumGroups,
1093 : : dNumOutputRows;
1094 : : bool can_sort;
1095 : : bool can_hash;
1096 : : SetOpCmd cmd;
1097 : :
1098 : : /*
1099 : : * Tell children to fetch all tuples.
1100 : : */
1101 : 722 : root->tuple_fraction = 0.0;
1102 : :
1103 : : /* Recurse on children */
1104 : 722 : lrel = recurse_set_operations(op->larg, root,
1105 : : op,
1106 : : op->colTypes, op->colCollations,
1107 : : refnames_tlist,
1108 : : &lpath_tlist,
1109 : : &lpath_trivial_tlist);
1110 : :
1111 : 722 : rrel = recurse_set_operations(op->rarg, root,
1112 : : op,
1113 : : op->colTypes, op->colCollations,
1114 : : refnames_tlist,
1115 : : &rpath_tlist,
1116 : : &rpath_trivial_tlist);
1117 : :
1118 : : /*
1119 : : * Generate tlist for SetOp plan node.
1120 : : *
1121 : : * The tlist for a SetOp plan isn't important so far as the SetOp is
1122 : : * concerned, but we must make it look real anyway for the benefit of the
1123 : : * next plan level up.
1124 : : */
1125 : 722 : tlist = generate_setop_tlist(op->colTypes, op->colCollations,
1126 : : 0, false, lpath_tlist, refnames_tlist,
1127 : : &result_trivial_tlist);
1128 : :
1129 : : /* We should not have needed any type coercions in the tlist */
1130 : : Assert(result_trivial_tlist);
1131 : :
1132 : 722 : *pTargetList = tlist;
1133 : :
1134 : : /* Identify the grouping semantics */
1135 : 722 : groupList = generate_setop_grouplist(op, tlist);
1136 : :
1137 : : /* Check whether the operators support sorting or hashing */
1138 : 722 : can_sort = grouping_is_sortable(groupList);
1139 : 722 : can_hash = grouping_is_hashable(groupList);
1140 [ + + + - ]: 722 : if (!can_sort && !can_hash)
1141 [ + - + + ]: 8 : ereport(ERROR,
1142 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1143 : : /* translator: %s is INTERSECT or EXCEPT */
1144 : : errmsg("could not implement %s",
1145 : : (op->op == SETOP_INTERSECT) ? "INTERSECT" : "EXCEPT"),
1146 : : errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
1147 : :
1148 [ + - ]: 714 : if (can_sort)
1149 : : {
1150 : : /* Determine the pathkeys for sorting by the whole target list */
1151 : 714 : nonunion_pathkeys = make_pathkeys_for_sortclauses(root, groupList,
1152 : : tlist);
1153 : :
1154 : 714 : root->query_pathkeys = nonunion_pathkeys;
1155 : : }
1156 : :
1157 : : /*
1158 : : * Now that we've got all that info, we can build the child paths.
1159 : : */
1160 [ + + ]: 714 : if (lrel->rtekind == RTE_SUBQUERY)
1161 : 689 : build_setop_child_paths(root, lrel, lpath_trivial_tlist, lpath_tlist,
1162 : : nonunion_pathkeys, &dLeftGroups);
1163 : : else
1164 : 25 : dLeftGroups = lrel->rows;
1165 [ + + ]: 714 : if (rrel->rtekind == RTE_SUBQUERY)
1166 : 704 : build_setop_child_paths(root, rrel, rpath_trivial_tlist, rpath_tlist,
1167 : : nonunion_pathkeys, &dRightGroups);
1168 : : else
1169 : 10 : dRightGroups = rrel->rows;
1170 : :
1171 : : /* Undo effects of forcing tuple_fraction to 0 */
1172 : 714 : root->tuple_fraction = save_fraction;
1173 : :
1174 : : /*
1175 : : * For EXCEPT, we must put the left input first. For INTERSECT, either
1176 : : * order should give the same results, and we prefer to put the smaller
1177 : : * input first in order to (a) minimize the size of the hash table in the
1178 : : * hashing case, and (b) improve our chances of exploiting the executor's
1179 : : * fast path for empty left-hand input. "Smaller" means the one with the
1180 : : * fewer groups.
1181 : : */
1182 [ + + + + ]: 714 : if (op->op != SETOP_EXCEPT && dLeftGroups > dRightGroups)
1183 : : {
1184 : : /* need to swap the two inputs */
1185 : : RelOptInfo *tmprel;
1186 : : List *tmplist;
1187 : : double tmpd;
1188 : :
1189 : 30 : tmprel = lrel;
1190 : 30 : lrel = rrel;
1191 : 30 : rrel = tmprel;
1192 : 30 : tmplist = lpath_tlist;
1193 : 30 : lpath_tlist = rpath_tlist;
1194 : 30 : rpath_tlist = tmplist;
1195 : 30 : tmpd = dLeftGroups;
1196 : 30 : dLeftGroups = dRightGroups;
1197 : 30 : dRightGroups = tmpd;
1198 : : }
1199 : :
1200 : 714 : lpath = lrel->cheapest_total_path;
1201 : 714 : rpath = rrel->cheapest_total_path;
1202 : :
1203 : : /* Build result relation. */
1204 : 714 : result_rel = fetch_upper_rel(root, UPPERREL_SETOP,
1205 : 714 : bms_union(lrel->relids, rrel->relids));
1206 : :
1207 : : /*
1208 : : * Create the PathTarget and set the width accordingly. For EXCEPT, since
1209 : : * the set op result won't contain rows from the rpath, we only account
1210 : : * for the width of the lpath. For INTERSECT, use both input paths.
1211 : : */
1212 [ + + ]: 714 : if (op->op == SETOP_EXCEPT)
1213 : 452 : result_rel->reltarget = create_setop_pathtarget(root, tlist,
1214 : : list_make1(lpath));
1215 : : else
1216 : 262 : result_rel->reltarget = create_setop_pathtarget(root, tlist,
1217 : : list_make2(lpath, rpath));
1218 : :
1219 : : /* Check for provably empty setop inputs and add short-circuit paths. */
1220 [ + + ]: 714 : if (op->op == SETOP_EXCEPT)
1221 : : {
1222 : : /*
1223 : : * For EXCEPTs, if the left side is dummy then there's no need to
1224 : : * inspect the right-hand side as scanning the right to find tuples to
1225 : : * remove won't make the left-hand input any more empty.
1226 : : */
1227 [ + + ]: 452 : if (is_dummy_rel(lrel))
1228 : : {
1229 : 10 : mark_dummy_rel(result_rel);
1230 : :
1231 : 10 : return result_rel;
1232 : : }
1233 : :
1234 : : /* Handle EXCEPTs with dummy right input */
1235 [ + + ]: 442 : if (is_dummy_rel(rrel))
1236 : : {
1237 [ + + ]: 15 : if (op->all)
1238 : : {
1239 : : Path *apath;
1240 : 10 : AppendPathInput append = {0};
1241 : :
1242 : 10 : append.subpaths = list_make1(lpath);
1243 : :
1244 : : /*
1245 : : * EXCEPT ALL: If the right-hand input is dummy then we can
1246 : : * simply scan the left-hand input. To keep createplan.c
1247 : : * happy, use a single child Append to handle the translation
1248 : : * between the set op targetlist and the targetlist of the
1249 : : * left input. The Append will be removed in setrefs.c.
1250 : : */
1251 : 10 : apath = (Path *) create_append_path(root, result_rel,
1252 : : append, NIL, NULL, 0,
1253 : : false, -1);
1254 : : /* See comment in generate_union_paths about "varno 0" Vars */
1255 : 10 : apath->pathkeys = NIL;
1256 : :
1257 : 10 : add_path(result_rel, apath);
1258 : :
1259 : 10 : return result_rel;
1260 : : }
1261 : : else
1262 : : {
1263 : : /*
1264 : : * To make EXCEPT with a dummy RHS work means having to
1265 : : * deduplicate the left input. That could be done with
1266 : : * AggPaths, but it doesn't seem worth the effort. Let the
1267 : : * normal path generation code below handle this one.
1268 : : */
1269 : : }
1270 : : }
1271 : : }
1272 : : else
1273 : : {
1274 : : /*
1275 : : * For INTERSECT, if either input is a dummy rel then we can mark the
1276 : : * result_rel as dummy since intersecting with an empty relation can
1277 : : * never yield any results. This is true regardless of INTERSECT or
1278 : : * INTERSECT ALL.
1279 : : */
1280 [ + + - + ]: 262 : if (is_dummy_rel(lrel) || is_dummy_rel(rrel))
1281 : : {
1282 : 15 : mark_dummy_rel(result_rel);
1283 : :
1284 : 15 : return result_rel;
1285 : : }
1286 : : }
1287 : :
1288 : : /*
1289 : : * Estimate number of distinct groups that we'll need hashtable entries
1290 : : * for; this is the size of the left-hand input for EXCEPT, or the smaller
1291 : : * input for INTERSECT. Also estimate the number of eventual output rows.
1292 : : * In non-ALL cases, we estimate each group produces one output row; in
1293 : : * ALL cases use the relevant relation size. These are worst-case
1294 : : * estimates, of course, but we need to be conservative.
1295 : : */
1296 [ + + ]: 679 : if (op->op == SETOP_EXCEPT)
1297 : : {
1298 : 432 : dNumGroups = dLeftGroups;
1299 [ + + ]: 432 : dNumOutputRows = op->all ? lpath->rows : dNumGroups;
1300 : : }
1301 : : else
1302 : : {
1303 : 247 : dNumGroups = dLeftGroups;
1304 [ + + + + ]: 247 : dNumOutputRows = op->all ? Min(lpath->rows, rpath->rows) : dNumGroups;
1305 : : }
1306 : 679 : result_rel->rows = dNumOutputRows;
1307 : :
1308 : : /* Select the SetOpCmd type */
1309 [ + + - ]: 679 : switch (op->op)
1310 : : {
1311 : 247 : case SETOP_INTERSECT:
1312 : 247 : cmd = op->all ? SETOPCMD_INTERSECT_ALL : SETOPCMD_INTERSECT;
1313 : 247 : break;
1314 : 432 : case SETOP_EXCEPT:
1315 [ + + ]: 432 : cmd = op->all ? SETOPCMD_EXCEPT_ALL : SETOPCMD_EXCEPT;
1316 : 432 : break;
1317 : 0 : default:
1318 [ # # ]: 0 : elog(ERROR, "unrecognized set op: %d", (int) op->op);
1319 : : cmd = SETOPCMD_INTERSECT; /* keep compiler quiet */
1320 : : break;
1321 : : }
1322 : :
1323 : : /*
1324 : : * If we can hash, that just requires a SetOp atop the cheapest inputs.
1325 : : */
1326 [ + + ]: 679 : if (can_hash)
1327 : : {
1328 : 629 : path = (Path *) create_setop_path(root,
1329 : : result_rel,
1330 : : lpath,
1331 : : rpath,
1332 : : cmd,
1333 : : SETOP_HASHED,
1334 : : groupList,
1335 : : dNumGroups,
1336 : : dNumOutputRows);
1337 : 629 : add_path(result_rel, path);
1338 : : }
1339 : :
1340 : : /*
1341 : : * If we can sort, generate the cheapest sorted input paths, and add a
1342 : : * SetOp atop those.
1343 : : */
1344 [ + - ]: 679 : if (can_sort)
1345 : : {
1346 : : List *pathkeys;
1347 : : Path *slpath,
1348 : : *srpath;
1349 : :
1350 : : /* First the left input ... */
1351 : 679 : pathkeys = make_pathkeys_for_sortclauses(root,
1352 : : groupList,
1353 : : lpath_tlist);
1354 [ + + ]: 679 : if (pathkeys_contained_in(pathkeys, lpath->pathkeys))
1355 : 80 : slpath = lpath; /* cheapest path is already sorted */
1356 : : else
1357 : : {
1358 : 599 : slpath = get_cheapest_path_for_pathkeys(lrel->pathlist,
1359 : : nonunion_pathkeys,
1360 : : NULL,
1361 : : TOTAL_COST,
1362 : : false);
1363 : : /* Subquery failed to produce any presorted paths? */
1364 [ + + ]: 599 : if (slpath == NULL)
1365 : 216 : slpath = (Path *) create_sort_path(root,
1366 : : lpath->parent,
1367 : : lpath,
1368 : : pathkeys,
1369 : : -1.0);
1370 : : }
1371 : :
1372 : : /* and now the same for the right. */
1373 : 679 : pathkeys = make_pathkeys_for_sortclauses(root,
1374 : : groupList,
1375 : : rpath_tlist);
1376 [ + + ]: 679 : if (pathkeys_contained_in(pathkeys, rpath->pathkeys))
1377 : 90 : srpath = rpath; /* cheapest path is already sorted */
1378 : : else
1379 : : {
1380 : 589 : srpath = get_cheapest_path_for_pathkeys(rrel->pathlist,
1381 : : nonunion_pathkeys,
1382 : : NULL,
1383 : : TOTAL_COST,
1384 : : false);
1385 : : /* Subquery failed to produce any presorted paths? */
1386 [ + + ]: 589 : if (srpath == NULL)
1387 : 226 : srpath = (Path *) create_sort_path(root,
1388 : : rpath->parent,
1389 : : rpath,
1390 : : pathkeys,
1391 : : -1.0);
1392 : : }
1393 : :
1394 : 679 : path = (Path *) create_setop_path(root,
1395 : : result_rel,
1396 : : slpath,
1397 : : srpath,
1398 : : cmd,
1399 : : SETOP_SORTED,
1400 : : groupList,
1401 : : dNumGroups,
1402 : : dNumOutputRows);
1403 : 679 : add_path(result_rel, path);
1404 : : }
1405 : :
1406 : 679 : return result_rel;
1407 : : }
1408 : :
1409 : : /*
1410 : : * Pull up children of a UNION node that are identically-propertied UNIONs,
1411 : : * and perform planning of the queries underneath the N-way UNION.
1412 : : *
1413 : : * The result is a list of RelOptInfos containing Paths for sub-nodes, with
1414 : : * one entry for each descendant that is a leaf query or non-identical setop.
1415 : : * We also return parallel lists of the childrens' targetlists and
1416 : : * is-trivial-tlist flags.
1417 : : *
1418 : : * NOTE: we can also pull a UNION ALL up into a UNION, since the distinct
1419 : : * output rows will be lost anyway.
1420 : : */
1421 : : static List *
1422 : 3802 : plan_union_children(PlannerInfo *root,
1423 : : SetOperationStmt *top_union,
1424 : : List *refnames_tlist,
1425 : : List **tlist_list,
1426 : : List **istrivial_tlist)
1427 : : {
1428 : 3802 : List *pending_rels = list_make1(top_union);
1429 : 3802 : List *result = NIL;
1430 : : List *child_tlist;
1431 : : bool trivial_tlist;
1432 : :
1433 : 3802 : *tlist_list = NIL;
1434 : 3802 : *istrivial_tlist = NIL;
1435 : :
1436 [ + + ]: 21106 : while (pending_rels != NIL)
1437 : : {
1438 : 17304 : Node *setOp = linitial(pending_rels);
1439 : :
1440 : 17304 : pending_rels = list_delete_first(pending_rels);
1441 : :
1442 [ + + ]: 17304 : if (IsA(setOp, SetOperationStmt))
1443 : : {
1444 : 6881 : SetOperationStmt *op = (SetOperationStmt *) setOp;
1445 : :
1446 [ + + ]: 6881 : if (op->op == top_union->op &&
1447 [ + + + + : 13557 : (op->all == top_union->all || op->all) &&
+ + ]
1448 [ + - ]: 13517 : equal(op->colTypes, top_union->colTypes) &&
1449 : 6751 : equal(op->colCollations, top_union->colCollations))
1450 : : {
1451 : : /* Same UNION, so fold children into parent */
1452 : 6751 : pending_rels = lcons(op->rarg, pending_rels);
1453 : 6751 : pending_rels = lcons(op->larg, pending_rels);
1454 : 6751 : continue;
1455 : : }
1456 : : }
1457 : :
1458 : : /*
1459 : : * Not same, so plan this child separately.
1460 : : *
1461 : : * If top_union isn't a UNION ALL, then we are interested in sorted
1462 : : * output from the child, so pass top_union as parentOp. Note that
1463 : : * this isn't necessarily the child node's immediate SetOperationStmt
1464 : : * parent, but that's fine: it's the effective parent.
1465 : : */
1466 : 10553 : result = lappend(result, recurse_set_operations(setOp, root,
1467 [ + + ]: 10553 : top_union->all ? NULL : top_union,
1468 : : top_union->colTypes,
1469 : : top_union->colCollations,
1470 : : refnames_tlist,
1471 : : &child_tlist,
1472 : : &trivial_tlist));
1473 : 10553 : *tlist_list = lappend(*tlist_list, child_tlist);
1474 : 10553 : *istrivial_tlist = lappend_int(*istrivial_tlist, trivial_tlist);
1475 : : }
1476 : :
1477 : 3802 : return result;
1478 : : }
1479 : :
1480 : : /*
1481 : : * postprocess_setop_rel - perform steps required after adding paths
1482 : : */
1483 : : static void
1484 : 18545 : postprocess_setop_rel(PlannerInfo *root, RelOptInfo *rel)
1485 : : {
1486 : : /*
1487 : : * We don't currently worry about allowing FDWs to contribute paths to
1488 : : * this relation, but give extensions a chance.
1489 : : */
1490 [ - + ]: 18545 : if (create_upper_paths_hook)
1491 : 0 : (*create_upper_paths_hook) (root, UPPERREL_SETOP,
1492 : : NULL, rel, NULL);
1493 : :
1494 : : /* Select cheapest path */
1495 : 18545 : set_cheapest(rel);
1496 : 18545 : }
1497 : :
1498 : : /*
1499 : : * Generate targetlist for a set-operation plan node
1500 : : *
1501 : : * colTypes: OID list of set-op's result column datatypes
1502 : : * colCollations: OID list of set-op's result column collations
1503 : : * varno: varno to use in generated Vars
1504 : : * hack_constants: true to copy up constants (see comments in code)
1505 : : * input_tlist: targetlist of this node's input node
1506 : : * refnames_tlist: targetlist to take column names from
1507 : : * trivial_tlist: output parameter, set to true if targetlist is trivial
1508 : : */
1509 : : static List *
1510 : 14053 : generate_setop_tlist(List *colTypes, List *colCollations,
1511 : : Index varno,
1512 : : bool hack_constants,
1513 : : List *input_tlist,
1514 : : List *refnames_tlist,
1515 : : bool *trivial_tlist)
1516 : : {
1517 : 14053 : List *tlist = NIL;
1518 : 14053 : int resno = 1;
1519 : : ListCell *ctlc,
1520 : : *cclc,
1521 : : *itlc,
1522 : : *rtlc;
1523 : : TargetEntry *tle;
1524 : : Node *expr;
1525 : :
1526 : 14053 : *trivial_tlist = true; /* until proven differently */
1527 : :
1528 [ + + + + : 56478 : forfour(ctlc, colTypes, cclc, colCollations,
+ + + + +
+ + + + +
+ + + + +
- + - + -
+ + ]
1529 : : itlc, input_tlist, rtlc, refnames_tlist)
1530 : : {
1531 : 42425 : Oid colType = lfirst_oid(ctlc);
1532 : 42425 : Oid colColl = lfirst_oid(cclc);
1533 : 42425 : TargetEntry *inputtle = (TargetEntry *) lfirst(itlc);
1534 : 42425 : TargetEntry *reftle = (TargetEntry *) lfirst(rtlc);
1535 : :
1536 : : Assert(inputtle->resno == resno);
1537 : : Assert(reftle->resno == resno);
1538 : : Assert(!inputtle->resjunk);
1539 : : Assert(!reftle->resjunk);
1540 : :
1541 : : /*
1542 : : * Generate columns referencing input columns and having appropriate
1543 : : * data types and column names. Insert datatype coercions where
1544 : : * necessary.
1545 : : *
1546 : : * HACK: constants in the input's targetlist are copied up as-is
1547 : : * rather than being referenced as subquery outputs. This is mainly
1548 : : * to ensure that when we try to coerce them to the output column's
1549 : : * datatype, the right things happen for UNKNOWN constants. But do
1550 : : * this only at the first level of subquery-scan plans; we don't want
1551 : : * phony constants appearing in the output tlists of upper-level
1552 : : * nodes!
1553 : : *
1554 : : * Note that copying a constant doesn't in itself require us to mark
1555 : : * the tlist nontrivial; see trivial_subqueryscan() in setrefs.c.
1556 : : */
1557 [ + + + - : 42425 : if (hack_constants && inputtle->expr && IsA(inputtle->expr, Const))
+ + ]
1558 : 12832 : expr = (Node *) inputtle->expr;
1559 : : else
1560 : 118372 : expr = (Node *) makeVar(varno,
1561 : 29593 : inputtle->resno,
1562 : 29593 : exprType((Node *) inputtle->expr),
1563 : 29593 : exprTypmod((Node *) inputtle->expr),
1564 : 29593 : exprCollation((Node *) inputtle->expr),
1565 : : 0);
1566 : :
1567 [ + + ]: 42425 : if (exprType(expr) != colType)
1568 : : {
1569 : : /*
1570 : : * Note: it's not really cool to be applying coerce_to_common_type
1571 : : * here; one notable point is that assign_expr_collations never
1572 : : * gets run on any generated nodes. For the moment that's not a
1573 : : * problem because we force the correct exposed collation below.
1574 : : * It would likely be best to make the parser generate the correct
1575 : : * output tlist for every set-op to begin with, though.
1576 : : */
1577 : 995 : expr = coerce_to_common_type(NULL, /* no UNKNOWNs here */
1578 : : expr,
1579 : : colType,
1580 : : "UNION/INTERSECT/EXCEPT");
1581 : 995 : *trivial_tlist = false; /* the coercion makes it not trivial */
1582 : : }
1583 : :
1584 : : /*
1585 : : * Ensure the tlist entry's exposed collation matches the set-op. This
1586 : : * is necessary because plan_set_operations() reports the result
1587 : : * ordering as a list of SortGroupClauses, which don't carry collation
1588 : : * themselves but just refer to tlist entries. If we don't show the
1589 : : * right collation then planner.c might do the wrong thing in
1590 : : * higher-level queries.
1591 : : *
1592 : : * Note we use RelabelType, not CollateExpr, since this expression
1593 : : * will reach the executor without any further processing.
1594 : : */
1595 [ + + ]: 42425 : if (exprCollation(expr) != colColl)
1596 : : {
1597 : 10805 : expr = applyRelabelType(expr,
1598 : : exprType(expr), exprTypmod(expr), colColl,
1599 : : COERCE_IMPLICIT_CAST, -1, false);
1600 : 10805 : *trivial_tlist = false; /* the relabel makes it not trivial */
1601 : : }
1602 : :
1603 : 84850 : tle = makeTargetEntry((Expr *) expr,
1604 : 42425 : (AttrNumber) resno++,
1605 : 42425 : pstrdup(reftle->resname),
1606 : : false);
1607 : :
1608 : : /*
1609 : : * By convention, all output columns in a setop tree have
1610 : : * ressortgroupref equal to their resno. In some cases the ref isn't
1611 : : * needed, but this is a cleaner way than modifying the tlist later.
1612 : : */
1613 : 42425 : tle->ressortgroupref = tle->resno;
1614 : :
1615 : 42425 : tlist = lappend(tlist, tle);
1616 : : }
1617 : :
1618 : 14053 : return tlist;
1619 : : }
1620 : :
1621 : : /*
1622 : : * Generate targetlist for a set-operation Append node
1623 : : *
1624 : : * colTypes: OID list of set-op's result column datatypes
1625 : : * colCollations: OID list of set-op's result column collations
1626 : : * input_tlists: list of tlists for sub-plans of the Append
1627 : : * refnames_tlist: targetlist to take column names from
1628 : : *
1629 : : * The entries in the Append's targetlist should always be simple Vars;
1630 : : * we just have to make sure they have the right datatypes/typmods/collations.
1631 : : * The Vars are always generated with varno 0.
1632 : : *
1633 : : * XXX a problem with the varno-zero approach is that set_pathtarget_cost_width
1634 : : * cannot figure out a realistic width for the tlist we make here. But we
1635 : : * ought to refactor this code to produce a PathTarget directly, anyway.
1636 : : */
1637 : : static List *
1638 : 4544 : generate_append_tlist(List *colTypes, List *colCollations,
1639 : : List *input_tlists,
1640 : : List *refnames_tlist)
1641 : : {
1642 : 4544 : List *tlist = NIL;
1643 : 4544 : int resno = 1;
1644 : : ListCell *curColType;
1645 : : ListCell *curColCollation;
1646 : : ListCell *ref_tl_item;
1647 : : int colindex;
1648 : : TargetEntry *tle;
1649 : : Node *expr;
1650 : : ListCell *tlistl;
1651 : : int32 *colTypmods;
1652 : :
1653 : : /*
1654 : : * First extract typmods to use.
1655 : : *
1656 : : * If the inputs all agree on type and typmod of a particular column, use
1657 : : * that typmod; else use -1.
1658 : : */
1659 : 4544 : colTypmods = palloc_array(int32, list_length(colTypes));
1660 : :
1661 [ + - + + : 16581 : foreach(tlistl, input_tlists)
+ + ]
1662 : : {
1663 : 12037 : List *subtlist = (List *) lfirst(tlistl);
1664 : : ListCell *subtlistl;
1665 : :
1666 : 12037 : curColType = list_head(colTypes);
1667 : 12037 : colindex = 0;
1668 [ + + + + : 45886 : foreach(subtlistl, subtlist)
+ + ]
1669 : : {
1670 : 33849 : TargetEntry *subtle = (TargetEntry *) lfirst(subtlistl);
1671 : :
1672 : : Assert(!subtle->resjunk);
1673 : : Assert(curColType != NULL);
1674 [ + - ]: 33849 : if (exprType((Node *) subtle->expr) == lfirst_oid(curColType))
1675 : : {
1676 : : /* If first subplan, copy the typmod; else compare */
1677 : 33849 : int32 subtypmod = exprTypmod((Node *) subtle->expr);
1678 : :
1679 [ + + ]: 33849 : if (tlistl == list_head(input_tlists))
1680 : 12078 : colTypmods[colindex] = subtypmod;
1681 [ + + ]: 21771 : else if (subtypmod != colTypmods[colindex])
1682 : 10 : colTypmods[colindex] = -1;
1683 : : }
1684 : : else
1685 : : {
1686 : : /* types disagree, so force typmod to -1 */
1687 : 0 : colTypmods[colindex] = -1;
1688 : : }
1689 : 33849 : curColType = lnext(colTypes, curColType);
1690 : 33849 : colindex++;
1691 : : }
1692 : : Assert(curColType == NULL);
1693 : : }
1694 : :
1695 : : /*
1696 : : * Now we can build the tlist for the Append.
1697 : : */
1698 : 4544 : colindex = 0;
1699 [ + + + + : 16622 : forthree(curColType, colTypes, curColCollation, colCollations,
+ + + + +
+ + + + +
+ - + - +
+ ]
1700 : : ref_tl_item, refnames_tlist)
1701 : : {
1702 : 12078 : Oid colType = lfirst_oid(curColType);
1703 : 12078 : int32 colTypmod = colTypmods[colindex++];
1704 : 12078 : Oid colColl = lfirst_oid(curColCollation);
1705 : 12078 : TargetEntry *reftle = (TargetEntry *) lfirst(ref_tl_item);
1706 : :
1707 : : Assert(reftle->resno == resno);
1708 : : Assert(!reftle->resjunk);
1709 : 12078 : expr = (Node *) makeVar(0,
1710 : : resno,
1711 : : colType,
1712 : : colTypmod,
1713 : : colColl,
1714 : : 0);
1715 : 24156 : tle = makeTargetEntry((Expr *) expr,
1716 : 12078 : (AttrNumber) resno++,
1717 : 12078 : pstrdup(reftle->resname),
1718 : : false);
1719 : :
1720 : : /*
1721 : : * By convention, all output columns in a setop tree have
1722 : : * ressortgroupref equal to their resno. In some cases the ref isn't
1723 : : * needed, but this is a cleaner way than modifying the tlist later.
1724 : : */
1725 : 12078 : tle->ressortgroupref = tle->resno;
1726 : :
1727 : 12078 : tlist = lappend(tlist, tle);
1728 : : }
1729 : :
1730 : 4544 : pfree(colTypmods);
1731 : :
1732 : 4544 : return tlist;
1733 : : }
1734 : :
1735 : : /*
1736 : : * generate_setop_grouplist
1737 : : * Build a SortGroupClause list defining the sort/grouping properties
1738 : : * of the setop's output columns.
1739 : : *
1740 : : * Parse analysis already determined the properties and built a suitable
1741 : : * list, except that the entries do not have sortgrouprefs set because
1742 : : * the parser output representation doesn't include a tlist for each
1743 : : * setop. So what we need to do here is copy that list and install
1744 : : * proper sortgrouprefs into it (copying those from the targetlist).
1745 : : */
1746 : : static List *
1747 : 4283 : generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
1748 : : {
1749 : 4283 : List *grouplist = copyObject(op->groupClauses);
1750 : : ListCell *lg;
1751 : : ListCell *lt;
1752 : :
1753 : 4283 : lg = list_head(grouplist);
1754 [ + + + + : 16733 : foreach(lt, targetlist)
+ + ]
1755 : : {
1756 : 12450 : TargetEntry *tle = (TargetEntry *) lfirst(lt);
1757 : : SortGroupClause *sgc;
1758 : :
1759 : : Assert(!tle->resjunk);
1760 : :
1761 : : /* non-resjunk columns should have sortgroupref = resno */
1762 : : Assert(tle->ressortgroupref == tle->resno);
1763 : :
1764 : : /* non-resjunk columns should have grouping clauses */
1765 : : Assert(lg != NULL);
1766 : 12450 : sgc = (SortGroupClause *) lfirst(lg);
1767 : 12450 : lg = lnext(grouplist, lg);
1768 : : Assert(sgc->tleSortGroupRef == 0);
1769 : :
1770 : 12450 : sgc->tleSortGroupRef = tle->ressortgroupref;
1771 : : }
1772 : : Assert(lg == NULL);
1773 : 4283 : return grouplist;
1774 : : }
1775 : :
1776 : : /*
1777 : : * create_setop_pathtarget
1778 : : * Do the normal create_pathtarget() work, plus set the resulting
1779 : : * PathTarget's width to the average width of the Paths in child_pathlist
1780 : : * weighted using the estimated row count of each path.
1781 : : *
1782 : : * Note: This is required because set op target lists use varno==0, which
1783 : : * results in a type default width estimate rather than one that's based on
1784 : : * statistics of the columns from the set op children.
1785 : : */
1786 : : static PathTarget *
1787 : 4516 : create_setop_pathtarget(PlannerInfo *root, List *tlist, List *child_pathlist)
1788 : : {
1789 : : PathTarget *reltarget;
1790 : : ListCell *lc;
1791 : 4516 : double parent_rows = 0;
1792 : 4516 : double parent_size = 0;
1793 : :
1794 : 4516 : reltarget = create_pathtarget(root, tlist);
1795 : :
1796 : : /* Calculate the total rows and total size. */
1797 [ + + + + : 15993 : foreach(lc, child_pathlist)
+ + ]
1798 : : {
1799 : 11477 : Path *path = (Path *) lfirst(lc);
1800 : :
1801 : 11477 : parent_rows += path->rows;
1802 : 11477 : parent_size += path->parent->reltarget->width * path->rows;
1803 : : }
1804 : :
1805 [ + + ]: 4516 : if (parent_rows > 0)
1806 : 4495 : reltarget->width = rint(parent_size / parent_rows);
1807 : :
1808 : 4516 : return reltarget;
1809 : : }
|