PostgreSQL Source Code git master
Loading...
Searching...
No Matches
allpaths.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * allpaths.c
4 * Routines to find possible search paths for processing a query
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/path/allpaths.c
12 *
13 *-------------------------------------------------------------------------
14 */
15
16#include "postgres.h"
17
18#include <limits.h>
19#include <math.h>
20
21#include "access/sysattr.h"
22#include "access/tsmapi.h"
23#include "catalog/pg_class.h"
24#include "catalog/pg_operator.h"
25#include "catalog/pg_proc.h"
26#include "foreign/fdwapi.h"
27#include "miscadmin.h"
28#include "nodes/makefuncs.h"
29#include "nodes/nodeFuncs.h"
30#include "nodes/supportnodes.h"
31#ifdef OPTIMIZER_DEBUG
32#include "nodes/print.h"
33#endif
35#include "optimizer/clauses.h"
36#include "optimizer/cost.h"
37#include "optimizer/geqo.h"
38#include "optimizer/optimizer.h"
39#include "optimizer/pathnode.h"
40#include "optimizer/paths.h"
41#include "optimizer/plancat.h"
42#include "optimizer/planner.h"
43#include "optimizer/prep.h"
44#include "optimizer/tlist.h"
45#include "parser/parse_clause.h"
46#include "parser/parsetree.h"
48#include "port/pg_bitutils.h"
50#include "utils/lsyscache.h"
51#include "utils/selfuncs.h"
52
53
54/* Bitmask flags for pushdown_safety_info.unsafeFlags */
55#define UNSAFE_HAS_VOLATILE_FUNC (1 << 0)
56#define UNSAFE_HAS_SET_FUNC (1 << 1)
57#define UNSAFE_NOTIN_DISTINCTON_CLAUSE (1 << 2)
58#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE (1 << 3)
59#define UNSAFE_TYPE_MISMATCH (1 << 4)
60
61/* results of subquery_is_pushdown_safe */
63{
64 unsigned char *unsafeFlags; /* bitmask of reasons why this target list
65 * column is unsafe for qual pushdown, or 0 if
66 * no reason. */
67 bool unsafeVolatile; /* don't push down volatile quals */
68 bool unsafeLeaky; /* don't push down leaky quals */
70
71/* Return type for qual_is_pushdown_safe */
73{
74 PUSHDOWN_UNSAFE, /* unsafe to push qual into subquery */
75 PUSHDOWN_SAFE, /* safe to push qual into subquery */
76 PUSHDOWN_WINDOWCLAUSE_RUNCOND, /* unsafe, but may work as WindowClause
77 * run condition */
79
80/* These parameters are set by GUC */
81bool enable_geqo = false; /* just in case GUC doesn't set it */
87
88/* Hook for plugins to get control in set_rel_pathlist() */
90
91/* Hook for plugins to replace standard_join_search() */
93
94
99static void set_rel_size(PlannerInfo *root, RelOptInfo *rel,
100 Index rti, RangeTblEntry *rte);
102 Index rti, RangeTblEntry *rte);
119 Index rti, RangeTblEntry *rte);
121 Index rti, RangeTblEntry *rte);
127 RelOptInfo *rel,
129static void accumulate_append_subpath(Path *path,
130 List **subpaths,
132 List **child_append_relid_sets);
134 List **child_append_relid_sets);
135static void set_dummy_rel_pathlist(RelOptInfo *rel);
137 Index rti, RangeTblEntry *rte);
153static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery,
157static void check_output_expressions(Query *subquery,
159static void compare_tlist_datatypes(List *tlist, List *colTypes,
163 RestrictInfo *rinfo,
165static Oid pushdown_var_grouping_eqop(Var *var, void *context);
166static Oid subquery_column_grouping_eqop(Query *subquery, AttrNumber attno);
167static Oid setop_column_grouping_eqop(Node *setop, AttrNumber attno);
168static bool setop_has_grouping(Node *setop);
169static void subquery_push_qual(Query *subquery,
170 RangeTblEntry *rte, Index rti, Node *qual);
172 RangeTblEntry *rte, Index rti, Node *qual);
173static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel,
175
176
177/*
178 * make_one_rel
179 * Finds all possible access paths for executing a query, returning a
180 * single rel that represents the join of all base rels in the query.
181 */
184{
185 RelOptInfo *rel;
186 Index rti;
187 double total_pages;
188
189 /* Mark base rels as to whether we care about fast-start plans */
191
192 /*
193 * Compute size estimates and consider_parallel flags for each base rel.
194 */
196
197 /*
198 * Build grouped relations for simple rels (i.e., base or "other" member
199 * relations) where possible.
200 */
202
203 /*
204 * We should now have size estimates for every actual table involved in
205 * the query, and we also know which if any have been deleted from the
206 * query by join removal, pruned by partition pruning, or eliminated by
207 * constraint exclusion. So we can now compute total_table_pages.
208 *
209 * Note that appendrels are not double-counted here, even though we don't
210 * bother to distinguish RelOptInfos for appendrel parents, because the
211 * parents will have pages = 0.
212 *
213 * XXX if a table is self-joined, we will count it once per appearance,
214 * which perhaps is the wrong thing ... but that's not completely clear,
215 * and detecting self-joins here is difficult, so ignore it for now.
216 */
217 total_pages = 0;
218 for (rti = 1; rti < root->simple_rel_array_size; rti++)
219 {
220 RelOptInfo *brel = root->simple_rel_array[rti];
221
222 /* there may be empty slots corresponding to non-baserel RTEs */
223 if (brel == NULL)
224 continue;
225
226 Assert(brel->relid == rti); /* sanity check on array */
227
228 if (IS_DUMMY_REL(brel))
229 continue;
230
231 if (IS_SIMPLE_REL(brel))
232 total_pages += (double) brel->pages;
233 }
234 root->total_table_pages = total_pages;
235
236 /*
237 * Generate access paths for each base rel.
238 */
240
241 /*
242 * Generate access paths for the entire join tree.
243 */
245
246 /*
247 * The result should join all and only the query's base + outer-join rels.
248 */
249 Assert(bms_equal(rel->relids, root->all_query_rels));
250
251 return rel;
252}
253
254/*
255 * set_base_rel_consider_startup
256 * Set the consider_[param_]startup flags for each base-relation entry.
257 *
258 * For the moment, we only deal with consider_param_startup here; because the
259 * logic for consider_startup is pretty trivial and is the same for every base
260 * relation, we just let build_simple_rel() initialize that flag correctly to
261 * start with. If that logic ever gets more complicated it would probably
262 * be better to move it here.
263 */
264static void
266{
267 /*
268 * Since parameterized paths can only be used on the inside of a nestloop
269 * join plan, there is usually little value in considering fast-start
270 * plans for them. However, for relations that are on the RHS of a SEMI
271 * or ANTI join, a fast-start plan can be useful because we're only going
272 * to care about fetching one tuple anyway.
273 *
274 * To minimize growth of planning time, we currently restrict this to
275 * cases where the RHS is a single base relation, not a join; there is no
276 * provision for consider_param_startup to get set at all on joinrels.
277 * Also we don't worry about appendrels. costsize.c's costing rules for
278 * nestloop semi/antijoins don't consider such cases either.
279 */
280 ListCell *lc;
281
282 foreach(lc, root->join_info_list)
283 {
285 int varno;
286
287 if ((sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) &&
289 {
290 RelOptInfo *rel = find_base_rel(root, varno);
291
292 rel->consider_param_startup = true;
293 }
294 }
295}
296
297/*
298 * set_base_rel_sizes
299 * Set the size estimates (rows and widths) for each base-relation entry.
300 * Also determine whether to consider parallel paths for base relations.
301 *
302 * We do this in a separate pass over the base rels so that rowcount
303 * estimates are available for parameterized path generation, and also so
304 * that each rel's consider_parallel flag is set correctly before we begin to
305 * generate paths.
306 */
307static void
309{
310 Index rti;
311
312 for (rti = 1; rti < root->simple_rel_array_size; rti++)
313 {
314 RelOptInfo *rel = root->simple_rel_array[rti];
316
317 /* there may be empty slots corresponding to non-baserel RTEs */
318 if (rel == NULL)
319 continue;
320
321 Assert(rel->relid == rti); /* sanity check on array */
322
323 /* ignore RTEs that are "other rels" */
324 if (rel->reloptkind != RELOPT_BASEREL)
325 continue;
326
327 rte = root->simple_rte_array[rti];
328
329 /*
330 * If parallelism is allowable for this query in general, see whether
331 * it's allowable for this rel in particular. We have to do this
332 * before set_rel_size(), because (a) if this rel is an inheritance
333 * parent, set_append_rel_size() will use and perhaps change the rel's
334 * consider_parallel flag, and (b) for some RTE types, set_rel_size()
335 * goes ahead and makes paths immediately.
336 */
337 if (root->glob->parallelModeOK)
339
340 set_rel_size(root, rel, rti, rte);
341 }
342}
343
344/*
345 * setup_simple_grouped_rels
346 * For each simple relation, build a grouped simple relation if eager
347 * aggregation is possible and if this relation can produce grouped paths.
348 */
349static void
351{
352 Index rti;
353
354 /*
355 * If there are no aggregate expressions or grouping expressions, eager
356 * aggregation is not possible.
357 */
358 if (root->agg_clause_list == NIL ||
359 root->group_expr_list == NIL)
360 return;
361
362 for (rti = 1; rti < root->simple_rel_array_size; rti++)
363 {
364 RelOptInfo *rel = root->simple_rel_array[rti];
365
366 /* there may be empty slots corresponding to non-baserel RTEs */
367 if (rel == NULL)
368 continue;
369
370 Assert(rel->relid == rti); /* sanity check on array */
371 Assert(IS_SIMPLE_REL(rel)); /* sanity check on rel */
372
374 }
375}
376
377/*
378 * set_base_rel_pathlists
379 * Finds all paths available for scanning each base-relation entry.
380 * Sequential scan and any available indices are considered.
381 * Each useful path is attached to its relation's 'pathlist' field.
382 */
383static void
385{
386 Index rti;
387
388 for (rti = 1; rti < root->simple_rel_array_size; rti++)
389 {
390 RelOptInfo *rel = root->simple_rel_array[rti];
391
392 /* there may be empty slots corresponding to non-baserel RTEs */
393 if (rel == NULL)
394 continue;
395
396 Assert(rel->relid == rti); /* sanity check on array */
397
398 /* ignore RTEs that are "other rels" */
399 if (rel->reloptkind != RELOPT_BASEREL)
400 continue;
401
402 set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
403 }
404}
405
406/*
407 * set_rel_size
408 * Set size estimates for a base relation
409 */
410static void
412 Index rti, RangeTblEntry *rte)
413{
414 if (rel->reloptkind == RELOPT_BASEREL &&
416 {
417 /*
418 * We proved we don't need to scan the rel via constraint exclusion,
419 * so set up a single dummy path for it. Here we only check this for
420 * regular baserels; if it's an otherrel, CE was already checked in
421 * set_append_rel_size().
422 *
423 * In this case, we go ahead and set up the relation's path right away
424 * instead of leaving it for set_rel_pathlist to do. This is because
425 * we don't have a convention for marking a rel as dummy except by
426 * assigning a dummy path to it.
427 */
429 }
430 else if (rte->inh)
431 {
432 /* It's an "append relation", process accordingly */
433 set_append_rel_size(root, rel, rti, rte);
434 }
435 else
436 {
437 switch (rel->rtekind)
438 {
439 case RTE_RELATION:
440 if (rte->relkind == RELKIND_FOREIGN_TABLE)
441 {
442 /* Foreign table */
444 }
445 else if (rte->relkind == RELKIND_PARTITIONED_TABLE)
446 {
447 /*
448 * We could get here if asked to scan a partitioned table
449 * with ONLY. In that case we shouldn't scan any of the
450 * partitions, so mark it as a dummy rel.
451 */
453 }
454 else if (rte->tablesample != NULL)
455 {
456 /* Sampled relation */
458 }
459 else
460 {
461 /* Plain relation */
463 }
464 break;
465 case RTE_SUBQUERY:
466
467 /*
468 * Subqueries don't support making a choice between
469 * parameterized and unparameterized paths, so just go ahead
470 * and build their paths immediately.
471 */
472 set_subquery_pathlist(root, rel, rti, rte);
473 break;
474 case RTE_FUNCTION:
476 break;
477 case RTE_TABLEFUNC:
479 break;
480 case RTE_VALUES:
482 break;
483 case RTE_CTE:
484
485 /*
486 * CTEs don't support making a choice between parameterized
487 * and unparameterized paths, so just go ahead and build their
488 * paths immediately.
489 */
490 if (rte->self_reference)
492 else
494 break;
496 /* Might as well just build the path immediately */
498 break;
499 case RTE_RESULT:
500 /* Might as well just build the path immediately */
502 break;
503 default:
504 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
505 break;
506 }
507 }
508
509 /*
510 * We insist that all non-dummy rels have a nonzero rowcount estimate.
511 */
512 Assert(rel->rows > 0 || IS_DUMMY_REL(rel));
513}
514
515/*
516 * set_rel_pathlist
517 * Build access paths for a base relation
518 */
519static void
521 Index rti, RangeTblEntry *rte)
522{
523 if (IS_DUMMY_REL(rel))
524 {
525 /* We already proved the relation empty, so nothing more to do */
526 }
527 else if (rte->inh)
528 {
529 /* It's an "append relation", process accordingly */
530 set_append_rel_pathlist(root, rel, rti, rte);
531 }
532 else
533 {
534 switch (rel->rtekind)
535 {
536 case RTE_RELATION:
537 if (rte->relkind == RELKIND_FOREIGN_TABLE)
538 {
539 /* Foreign table */
541 }
542 else if (rte->tablesample != NULL)
543 {
544 /* Sampled relation */
546 }
547 else
548 {
549 /* Plain relation */
551 }
552 break;
553 case RTE_SUBQUERY:
554 /* Subquery --- fully handled during set_rel_size */
555 break;
556 case RTE_FUNCTION:
557 /* RangeFunction */
559 break;
560 case RTE_TABLEFUNC:
561 /* Table Function */
563 break;
564 case RTE_VALUES:
565 /* Values list */
567 break;
568 case RTE_CTE:
569 /* CTE reference --- fully handled during set_rel_size */
570 break;
572 /* tuplestore reference --- fully handled during set_rel_size */
573 break;
574 case RTE_RESULT:
575 /* simple Result --- fully handled during set_rel_size */
576 break;
577 default:
578 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
579 break;
580 }
581 }
582
583 /*
584 * Allow a plugin to editorialize on the set of Paths for this base
585 * relation. It could add new paths (such as CustomPaths) by calling
586 * add_path(), or add_partial_path() if parallel aware. It could also
587 * delete or modify paths added by the core code.
588 */
590 (*set_rel_pathlist_hook) (root, rel, rti, rte);
591
592 /*
593 * If this is a baserel, we should normally consider gathering any partial
594 * paths we may have created for it. We have to do this after calling the
595 * set_rel_pathlist_hook, else it cannot add partial paths to be included
596 * here.
597 *
598 * However, if this is an inheritance child, skip it. Otherwise, we could
599 * end up with a very large number of gather nodes, each trying to grab
600 * its own pool of workers. Instead, we'll consider gathering partial
601 * paths for the parent appendrel.
602 *
603 * Also, if this is the topmost scan/join rel, we postpone gathering until
604 * the final scan/join targetlist is available (see grouping_planner).
605 */
606 if (rel->reloptkind == RELOPT_BASEREL &&
607 !bms_equal(rel->relids, root->all_query_rels))
609
610 /* Now find the cheapest of the paths for this rel */
611 set_cheapest(rel);
612
613 /*
614 * If a grouped relation for this rel exists, build partial aggregation
615 * paths for it.
616 *
617 * Note that this can only happen after we've called set_cheapest() for
618 * this base rel, because we need its cheapest paths.
619 */
621
622#ifdef OPTIMIZER_DEBUG
623 pprint(rel);
624#endif
625}
626
627/*
628 * set_plain_rel_size
629 * Set size estimates for a plain relation (no subquery, no inheritance)
630 */
631static void
633{
634 /*
635 * Test any partial indexes of rel for applicability. We must do this
636 * first since partial unique indexes can affect size estimates.
637 */
639
640 /* Mark rel with estimated output rows, width, etc */
642}
643
644/*
645 * If this relation could possibly be scanned from within a worker, then set
646 * its consider_parallel flag.
647 */
648static void
651{
652 /*
653 * The flag has previously been initialized to false, so we can just
654 * return if it becomes clear that we can't safely set it.
655 */
657
658 /* Don't call this if parallelism is disallowed for the entire query. */
659 Assert(root->glob->parallelModeOK);
660
661 /* This should only be called for baserels and appendrel children. */
662 Assert(IS_SIMPLE_REL(rel));
663
664 /* Assorted checks based on rtekind. */
665 switch (rte->rtekind)
666 {
667 case RTE_RELATION:
668
669 /*
670 * Currently, parallel workers can't access the leader's temporary
671 * tables. We could possibly relax this if we wrote all of its
672 * local buffers at the start of the query and made no changes
673 * thereafter (maybe we could allow hint bit changes), and if we
674 * taught the workers to read them. Writing a large number of
675 * temporary buffers could be expensive, though, and we don't have
676 * the rest of the necessary infrastructure right now anyway. So
677 * for now, bail out if we see a temporary table.
678 */
680 return;
681
682 /*
683 * Table sampling can be pushed down to workers if the sample
684 * function and its arguments are safe.
685 */
686 if (rte->tablesample != NULL)
687 {
688 char proparallel = func_parallel(rte->tablesample->tsmhandler);
689
691 return;
692 if (!is_parallel_safe(root, (Node *) rte->tablesample->args))
693 return;
694 }
695
696 /*
697 * Ask FDWs whether they can support performing a ForeignScan
698 * within a worker. Most often, the answer will be no. For
699 * example, if the nature of the FDW is such that it opens a TCP
700 * connection with a remote server, each parallel worker would end
701 * up with a separate connection, and these connections might not
702 * be appropriately coordinated between workers and the leader.
703 */
704 if (rte->relkind == RELKIND_FOREIGN_TABLE)
705 {
706 Assert(rel->fdwroutine);
707 if (!rel->fdwroutine->IsForeignScanParallelSafe)
708 return;
709 if (!rel->fdwroutine->IsForeignScanParallelSafe(root, rel, rte))
710 return;
711 }
712
713 /*
714 * There are additional considerations for appendrels, which we'll
715 * deal with in set_append_rel_size and set_append_rel_pathlist.
716 * For now, just set consider_parallel based on the rel's own
717 * quals and targetlist.
718 */
719 break;
720
721 case RTE_SUBQUERY:
722
723 /*
724 * There's no intrinsic problem with scanning a subquery-in-FROM
725 * (as distinct from a SubPlan or InitPlan) in a parallel worker.
726 * If the subquery doesn't happen to have any parallel-safe paths,
727 * then flagging it as consider_parallel won't change anything,
728 * but that's true for plain tables, too. We must set
729 * consider_parallel based on the rel's own quals and targetlist,
730 * so that if a subquery path is parallel-safe but the quals and
731 * projection we're sticking onto it are not, we correctly mark
732 * the SubqueryScanPath as not parallel-safe. (Note that
733 * set_subquery_pathlist() might push some of these quals down
734 * into the subquery itself, but that doesn't change anything.)
735 *
736 * We can't push sub-select containing LIMIT/OFFSET to workers as
737 * there is no guarantee that the row order will be fully
738 * deterministic, and applying LIMIT/OFFSET will lead to
739 * inconsistent results at the top-level. (In some cases, where
740 * the result is ordered, we could relax this restriction. But it
741 * doesn't currently seem worth expending extra effort to do so.)
742 */
743 {
744 Query *subquery = castNode(Query, rte->subquery);
745
746 if (limit_needed(subquery))
747 return;
748 }
749 break;
750
751 case RTE_JOIN:
752 /* Shouldn't happen; we're only considering baserels here. */
753 Assert(false);
754 return;
755
756 case RTE_FUNCTION:
757 /* Check for parallel-restricted functions. */
758 if (!is_parallel_safe(root, (Node *) rte->functions))
759 return;
760 break;
761
762 case RTE_TABLEFUNC:
763 /* not parallel safe */
764 return;
765
766 case RTE_VALUES:
767 /* Check for parallel-restricted functions. */
768 if (!is_parallel_safe(root, (Node *) rte->values_lists))
769 return;
770 break;
771
772 case RTE_CTE:
773
774 /*
775 * CTE tuplestores aren't shared among parallel workers, so we
776 * force all CTE scans to happen in the leader. Also, populating
777 * the CTE would require executing a subplan that's not available
778 * in the worker, might be parallel-restricted, and must get
779 * executed only once.
780 */
781 return;
782
784
785 /*
786 * tuplestore cannot be shared, at least without more
787 * infrastructure to support that.
788 */
789 return;
790
791 case RTE_RESULT:
792 /* RESULT RTEs, in themselves, are no problem. */
793 break;
794
795 case RTE_GRAPH_TABLE:
796
797 /*
798 * Shouldn't happen since these are replaced by subquery RTEs when
799 * rewriting queries.
800 */
801 Assert(false);
802 return;
803
804 case RTE_GROUP:
805 /* Shouldn't happen; we're only considering baserels here. */
806 Assert(false);
807 return;
808 }
809
810 /*
811 * If there's anything in baserestrictinfo that's parallel-restricted, we
812 * give up on parallelizing access to this relation. We could consider
813 * instead postponing application of the restricted quals until we're
814 * above all the parallelism in the plan tree, but it's not clear that
815 * that would be a win in very many cases, and it might be tricky to make
816 * outer join clauses work correctly. It would likely break equivalence
817 * classes, too.
818 */
820 return;
821
822 /*
823 * Likewise, if the relation's outputs are not parallel-safe, give up.
824 * (Usually, they're just Vars, but sometimes they're not.)
825 */
826 if (!is_parallel_safe(root, (Node *) rel->reltarget->exprs))
827 return;
828
829 /* We have a winner. */
830 rel->consider_parallel = true;
831}
832
833/*
834 * set_plain_rel_pathlist
835 * Build access paths for a plain relation (no subquery, no inheritance)
836 */
837static void
839{
841
842 /*
843 * We don't support pushing join clauses into the quals of a seqscan, but
844 * it could still have required parameterization due to LATERAL refs in
845 * its tlist.
846 */
848
849 /*
850 * Consider TID scans.
851 *
852 * If create_tidscan_paths returns true, then a TID scan path is forced.
853 * This happens when rel->baserestrictinfo contains CurrentOfExpr, because
854 * the executor can't handle any other type of path for such queries.
855 * Hence, we return without adding any other paths.
856 */
857 if (create_tidscan_paths(root, rel))
858 return;
859
860 /* Consider sequential scan */
862
863 /* If appropriate, consider parallel sequential scan */
866
867 /* Consider index scans */
869}
870
871/*
872 * create_plain_partial_paths
873 * Build partial access paths for parallel scan of a plain relation
874 */
875static void
877{
878 int parallel_workers;
879
880 parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
882
883 /* If any limit was set to zero, the user doesn't want a parallel scan. */
884 if (parallel_workers <= 0)
885 return;
886
887 /* Add an unordered partial path based on a parallel sequential scan. */
888 add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
889}
890
891/*
892 * set_tablesample_rel_size
893 * Set size estimates for a sampled relation
894 */
895static void
897{
898 TableSampleClause *tsc = rte->tablesample;
900 BlockNumber pages;
901 double tuples;
902
903 /*
904 * Test any partial indexes of rel for applicability. We must do this
905 * first since partial unique indexes can affect size estimates.
906 */
908
909 /*
910 * Call the sampling method's estimation function to estimate the number
911 * of pages it will read and the number of tuples it will return. (Note:
912 * we assume the function returns sane values.)
913 */
914 tsm = GetTsmRoutine(tsc->tsmhandler);
915 tsm->SampleScanGetSampleSize(root, rel, tsc->args,
916 &pages, &tuples);
917
918 /*
919 * For the moment, because we will only consider a SampleScan path for the
920 * rel, it's okay to just overwrite the pages and tuples estimates for the
921 * whole relation. If we ever consider multiple path types for sampled
922 * rels, we'll need more complication.
923 */
924 rel->pages = pages;
925 rel->tuples = tuples;
926
927 /* Mark rel with estimated output rows, width, etc */
929}
930
931/*
932 * set_tablesample_rel_pathlist
933 * Build access paths for a sampled relation
934 */
935static void
937{
939 Path *path;
940
941 /*
942 * We don't support pushing join clauses into the quals of a samplescan,
943 * but it could still have required parameterization due to LATERAL refs
944 * in its tlist or TABLESAMPLE arguments.
945 */
947
948 /* Consider sampled scan */
950
951 /*
952 * If the sampling method does not support repeatable scans, we must avoid
953 * plans that would scan the rel multiple times. Ideally, we'd simply
954 * avoid putting the rel on the inside of a nestloop join; but adding such
955 * a consideration to the planner seems like a great deal of complication
956 * to support an uncommon usage of second-rate sampling methods. Instead,
957 * if there is a risk that the query might perform an unsafe join, just
958 * wrap the SampleScan in a Materialize node. We can check for joins by
959 * counting the membership of all_query_rels (note that this correctly
960 * counts inheritance trees as single rels). If we're inside a subquery,
961 * we can't easily check whether a join might occur in the outer query, so
962 * just assume one is possible.
963 *
964 * GetTsmRoutine is relatively expensive compared to the other tests here,
965 * so check repeatable_across_scans last, even though that's a bit odd.
966 */
967 if ((root->query_level > 1 ||
968 bms_membership(root->all_query_rels) != BMS_SINGLETON) &&
969 !(GetTsmRoutine(rte->tablesample->tsmhandler)->repeatable_across_scans))
970 {
971 path = (Path *) create_material_path(rel, path, true);
972 }
973
974 add_path(rel, path);
975
976 /* For the moment, at least, there are no other paths to consider */
977}
978
979/*
980 * set_foreign_size
981 * Set size estimates for a foreign table RTE
982 */
983static void
985{
986 /* Mark rel with estimated output rows, width, etc */
988
989 /* Let FDW adjust the size estimates, if it can */
990 rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
991
992 /* ... but do not let it set the rows estimate to zero */
993 rel->rows = clamp_row_est(rel->rows);
994
995 /*
996 * Also, make sure rel->tuples is not insane relative to rel->rows.
997 * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
998 * FDW doesn't do anything to replace that.
999 */
1000 rel->tuples = Max(rel->tuples, rel->rows);
1001}
1002
1003/*
1004 * set_foreign_pathlist
1005 * Build access paths for a foreign table RTE
1006 */
1007static void
1009{
1010 /* Call the FDW's GetForeignPaths function to generate path(s) */
1011 rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
1012}
1013
1014/*
1015 * set_append_rel_size
1016 * Set size estimates for a simple "append relation"
1017 *
1018 * The passed-in rel and RTE represent the entire append relation. The
1019 * relation's contents are computed by appending together the output of the
1020 * individual member relations. Note that in the non-partitioned inheritance
1021 * case, the first member relation is actually the same table as is mentioned
1022 * in the parent RTE ... but it has a different RTE and RelOptInfo. This is
1023 * a good thing because their outputs are not the same size.
1024 */
1025static void
1027 Index rti, RangeTblEntry *rte)
1028{
1029 int parentRTindex = rti;
1030 bool has_live_children;
1031 double parent_tuples;
1032 double parent_rows;
1033 double parent_size;
1034 double *parent_attrsizes;
1035 int nattrs;
1036 ListCell *l;
1037
1038 /* Guard against stack overflow due to overly deep inheritance tree. */
1040
1041 Assert(IS_SIMPLE_REL(rel));
1042
1043 /*
1044 * If this is a partitioned baserel, set the consider_partitionwise_join
1045 * flag; currently, we only consider partitionwise joins with the baserel
1046 * if its targetlist doesn't contain a whole-row Var.
1047 */
1049 rel->reloptkind == RELOPT_BASEREL &&
1050 rte->relkind == RELKIND_PARTITIONED_TABLE &&
1051 bms_is_empty(rel->attr_needed[InvalidAttrNumber - rel->min_attr]))
1052 rel->consider_partitionwise_join = true;
1053
1054 /*
1055 * Initialize to compute size estimates for whole append relation.
1056 *
1057 * We handle tuples estimates by setting "tuples" to the total number of
1058 * tuples accumulated from each live child, rather than using "rows".
1059 * Although an appendrel itself doesn't directly enforce any quals, its
1060 * child relations may. Therefore, setting "tuples" equal to "rows" for
1061 * an appendrel isn't always appropriate, and can lead to inaccurate cost
1062 * estimates. For example, when estimating the number of distinct values
1063 * from an appendrel, we would be unable to adjust the estimate based on
1064 * the restriction selectivity (see estimate_num_groups).
1065 *
1066 * We handle width estimates by weighting the widths of different child
1067 * rels proportionally to their number of rows. This is sensible because
1068 * the use of width estimates is mainly to compute the total relation
1069 * "footprint" if we have to sort or hash it. To do this, we sum the
1070 * total equivalent size (in "double" arithmetic) and then divide by the
1071 * total rowcount estimate. This is done separately for the total rel
1072 * width and each attribute.
1073 *
1074 * Note: if you consider changing this logic, beware that child rels could
1075 * have zero rows and/or width, if they were excluded by constraints.
1076 */
1077 has_live_children = false;
1078 parent_tuples = 0;
1079 parent_rows = 0;
1080 parent_size = 0;
1081 nattrs = rel->max_attr - rel->min_attr + 1;
1082 parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
1083
1084 foreach(l, root->append_rel_list)
1085 {
1087 int childRTindex;
1093 ListCell *lc;
1094
1095 /* append_rel_list contains all append rels; ignore others */
1096 if (appinfo->parent_relid != parentRTindex)
1097 continue;
1098
1099 childRTindex = appinfo->child_relid;
1100 childRTE = root->simple_rte_array[childRTindex];
1101
1102 /*
1103 * The child rel's RelOptInfo was already created during
1104 * add_other_rels_to_query.
1105 */
1107 Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1108
1109 /* We may have already proven the child to be dummy. */
1111 continue;
1112
1113 /*
1114 * We have to copy the parent's targetlist and quals to the child,
1115 * with appropriate substitution of variables. However, the
1116 * baserestrictinfo quals were already copied/substituted when the
1117 * child RelOptInfo was built. So we don't need any additional setup
1118 * before applying constraint exclusion.
1119 */
1121 {
1122 /*
1123 * This child need not be scanned, so we can omit it from the
1124 * appendrel.
1125 */
1127 continue;
1128 }
1129
1130 /*
1131 * Constraint exclusion failed, so copy the parent's join quals and
1132 * targetlist to the child, with appropriate variable substitutions.
1133 *
1134 * We skip join quals that came from above outer joins that can null
1135 * this rel, since they would be of no value while generating paths
1136 * for the child. This saves some effort while processing the child
1137 * rel, and it also avoids an implementation restriction in
1138 * adjust_appendrel_attrs (it can't apply nullingrels to a non-Var).
1139 */
1140 childrinfos = NIL;
1141 foreach(lc, rel->joininfo)
1142 {
1143 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1144
1145 if (!bms_overlap(rinfo->clause_relids, rel->nulling_relids))
1148 (Node *) rinfo,
1149 1, &appinfo));
1150 }
1151 childrel->joininfo = childrinfos;
1152
1153 /*
1154 * Now for the child's targetlist.
1155 *
1156 * NB: the resulting childrel->reltarget->exprs may contain arbitrary
1157 * expressions, which otherwise would not occur in a rel's targetlist.
1158 * Code that might be looking at an appendrel child must cope with
1159 * such. (Normally, a rel's targetlist would only include Vars and
1160 * PlaceHolderVars.) XXX we do not bother to update the cost or width
1161 * fields of childrel->reltarget; not clear if that would be useful.
1162 */
1163 childrel->reltarget->exprs = (List *)
1165 (Node *) rel->reltarget->exprs,
1166 1, &appinfo);
1167
1168 /*
1169 * We have to make child entries in the EquivalenceClass data
1170 * structures as well. This is needed either if the parent
1171 * participates in some eclass joins (because we will want to consider
1172 * inner-indexscan joins on the individual children) or if the parent
1173 * has useful pathkeys (because we should try to build MergeAppend
1174 * paths that produce those sort orderings).
1175 */
1176 if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
1178 childrel->has_eclass_joins = rel->has_eclass_joins;
1179
1180 /*
1181 * Note: we could compute appropriate attr_needed data for the child's
1182 * variables, by transforming the parent's attr_needed through the
1183 * translated_vars mapping. However, currently there's no need
1184 * because attr_needed is only examined for base relations not
1185 * otherrels. So we just leave the child's attr_needed empty.
1186 */
1187
1188 /*
1189 * If we consider partitionwise joins with the parent rel, do the same
1190 * for partitioned child rels.
1191 *
1192 * Note: here we abuse the consider_partitionwise_join flag by setting
1193 * it for child rels that are not themselves partitioned. We do so to
1194 * tell try_partitionwise_join() that the child rel is sufficiently
1195 * valid to be used as a per-partition input, even if it later gets
1196 * proven to be dummy. (It's not usable until we've set up the
1197 * reltarget and EC entries, which we just did.)
1198 */
1200 childrel->consider_partitionwise_join = true;
1201
1202 /*
1203 * If parallelism is allowable for this query in general, see whether
1204 * it's allowable for this childrel in particular. But if we've
1205 * already decided the appendrel is not parallel-safe as a whole,
1206 * there's no point in considering parallelism for this child. For
1207 * consistency, do this before calling set_rel_size() for the child.
1208 */
1209 if (root->glob->parallelModeOK && rel->consider_parallel)
1211
1212 /*
1213 * Compute the child's size.
1214 */
1216
1217 /*
1218 * It is possible that constraint exclusion detected a contradiction
1219 * within a child subquery, even though we didn't prove one above. If
1220 * so, we can skip this child.
1221 */
1223 continue;
1224
1225 /* We have at least one live child. */
1226 has_live_children = true;
1227
1228 /*
1229 * If any live child is not parallel-safe, treat the whole appendrel
1230 * as not parallel-safe. In future we might be able to generate plans
1231 * in which some children are farmed out to workers while others are
1232 * not; but we don't have that today, so it's a waste to consider
1233 * partial paths anywhere in the appendrel unless it's all safe.
1234 * (Child rels visited before this one will be unmarked in
1235 * set_append_rel_pathlist().)
1236 */
1237 if (!childrel->consider_parallel)
1238 rel->consider_parallel = false;
1239
1240 /*
1241 * Accumulate size information from each live child.
1242 */
1243 Assert(childrel->rows > 0);
1244
1245 parent_tuples += childrel->tuples;
1246 parent_rows += childrel->rows;
1247 parent_size += childrel->reltarget->width * childrel->rows;
1248
1249 /*
1250 * Accumulate per-column estimates too. We need not do anything for
1251 * PlaceHolderVars in the parent list. If child expression isn't a
1252 * Var, or we didn't record a width estimate for it, we have to fall
1253 * back on a datatype-based estimate.
1254 *
1255 * By construction, child's targetlist is 1-to-1 with parent's.
1256 */
1258 childvars, childrel->reltarget->exprs)
1259 {
1262
1263 if (IsA(parentvar, Var) && parentvar->varno == parentRTindex)
1264 {
1265 int pndx = parentvar->varattno - rel->min_attr;
1266 int32 child_width = 0;
1267
1268 if (IsA(childvar, Var) &&
1269 ((Var *) childvar)->varno == childrel->relid)
1270 {
1271 int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
1272
1273 child_width = childrel->attr_widths[cndx];
1274 }
1275 if (child_width <= 0)
1278 Assert(child_width > 0);
1280 }
1281 }
1282 }
1283
1285 {
1286 /*
1287 * Save the finished size estimates.
1288 */
1289 int i;
1290
1291 Assert(parent_rows > 0);
1292 rel->tuples = parent_tuples;
1293 rel->rows = parent_rows;
1295 for (i = 0; i < nattrs; i++)
1296 rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
1297
1298 /*
1299 * Note that we leave rel->pages as zero; this is important to avoid
1300 * double-counting the appendrel tree in total_table_pages.
1301 */
1302 }
1303 else
1304 {
1305 /*
1306 * All children were excluded by constraints, so mark the whole
1307 * appendrel dummy. We must do this in this phase so that the rel's
1308 * dummy-ness is visible when we generate paths for other rels.
1309 */
1311 }
1312
1314}
1315
1316/*
1317 * set_append_rel_pathlist
1318 * Build access paths for an "append relation"
1319 */
1320static void
1322 Index rti, RangeTblEntry *rte)
1323{
1324 int parentRTindex = rti;
1326 ListCell *l;
1327
1328 /*
1329 * Generate access paths for each member relation, and remember the
1330 * non-dummy children.
1331 */
1332 foreach(l, root->append_rel_list)
1333 {
1335 int childRTindex;
1338
1339 /* append_rel_list contains all append rels; ignore others */
1340 if (appinfo->parent_relid != parentRTindex)
1341 continue;
1342
1343 /* Re-locate the child RTE and RelOptInfo */
1344 childRTindex = appinfo->child_relid;
1345 childRTE = root->simple_rte_array[childRTindex];
1346 childrel = root->simple_rel_array[childRTindex];
1347
1348 /*
1349 * If set_append_rel_size() decided the parent appendrel was
1350 * parallel-unsafe at some point after visiting this child rel, we
1351 * need to propagate the unsafety marking down to the child, so that
1352 * we don't generate useless partial paths for it.
1353 */
1354 if (!rel->consider_parallel)
1355 childrel->consider_parallel = false;
1356
1357 /*
1358 * Compute the child's access paths.
1359 */
1361
1362 /*
1363 * If child is dummy, ignore it.
1364 */
1366 continue;
1367
1368 /*
1369 * Child is live, so add it to the live_childrels list for use below.
1370 */
1372 }
1373
1374 /* Add paths to the append relation. */
1376}
1377
1378/*
1379 * set_grouped_rel_pathlist
1380 * If a grouped relation for the given 'rel' exists, build partial
1381 * aggregation paths for it.
1382 */
1383static void
1385{
1386 RelOptInfo *grouped_rel;
1387
1388 /*
1389 * If there are no aggregate expressions or grouping expressions, eager
1390 * aggregation is not possible.
1391 */
1392 if (root->agg_clause_list == NIL ||
1393 root->group_expr_list == NIL)
1394 return;
1395
1396 /* Add paths to the grouped base relation if one exists. */
1397 grouped_rel = rel->grouped_rel;
1398 if (grouped_rel)
1399 {
1400 Assert(IS_GROUPED_REL(grouped_rel));
1401
1402 generate_grouped_paths(root, grouped_rel, rel);
1403 set_cheapest(grouped_rel);
1404 }
1405}
1406
1407
1408/*
1409 * add_paths_to_append_rel
1410 * Generate paths for the given append relation given the set of non-dummy
1411 * child rels.
1412 *
1413 * The function collects all parameterizations and orderings supported by the
1414 * non-dummy children. For every such parameterization or ordering, it creates
1415 * an append path collecting one path from each non-dummy child with given
1416 * parameterization or ordering. Similarly it collects partial paths from
1417 * non-dummy children to create partial append paths.
1418 */
1419void
1422{
1424 AppendPathInput startup = {0};
1427 bool unparameterized_valid = true;
1428 bool startup_valid = true;
1429 bool partial_only_valid = true;
1430 bool parallel_append_valid = true;
1433 ListCell *l;
1434 double partial_rows = -1;
1435
1436 /* If appropriate, consider parallel append */
1438
1439 /*
1440 * For every non-dummy child, remember the cheapest path. Also, identify
1441 * all pathkeys (orderings) and parameterizations (required_outer sets)
1442 * available for the non-dummy member relations.
1443 */
1444 foreach(l, live_childrels)
1445 {
1447 ListCell *lcp;
1449
1450 /*
1451 * If child has an unparameterized cheapest-total path, add that to
1452 * the unparameterized Append path we are constructing for the parent.
1453 * If not, there's no workable unparameterized path.
1454 *
1455 * With partitionwise aggregates, the child rel's pathlist may be
1456 * empty, so don't assume that a path exists here.
1457 */
1458 if (childrel->pathlist != NIL &&
1459 childrel->cheapest_total_path->param_info == NULL)
1460 accumulate_append_subpath(childrel->cheapest_total_path,
1461 &unparameterized.subpaths, NULL, &unparameterized.child_append_relid_sets);
1462 else
1463 unparameterized_valid = false;
1464
1465 /*
1466 * When the planner is considering cheap startup plans, we'll also
1467 * collect all the cheapest_startup_paths (if set) and build an
1468 * AppendPath containing those as subpaths.
1469 */
1470 if (rel->consider_startup && childrel->cheapest_startup_path != NULL)
1471 {
1473
1474 /*
1475 * With an indication of how many tuples the query should provide,
1476 * the optimizer tries to choose the path optimal for that
1477 * specific number of tuples.
1478 */
1479 if (root->tuple_fraction > 0.0)
1482 root->tuple_fraction);
1483 else
1484 cheapest_path = childrel->cheapest_startup_path;
1485
1486 /* cheapest_startup_path must not be a parameterized path. */
1487 Assert(cheapest_path->param_info == NULL);
1489 &startup.subpaths,
1490 NULL,
1491 &startup.child_append_relid_sets);
1492 }
1493 else
1494 startup_valid = false;
1495
1496
1497 /* Same idea, but for a partial plan. */
1498 if (childrel->partial_pathlist != NIL)
1499 {
1500 cheapest_partial_path = linitial(childrel->partial_pathlist);
1502 &partial_only.partial_subpaths, NULL,
1503 &partial_only.child_append_relid_sets);
1504 }
1505 else
1506 partial_only_valid = false;
1507
1508 /*
1509 * Same idea, but for a parallel append mixing partial and non-partial
1510 * paths.
1511 */
1513 {
1514 Path *nppath = NULL;
1515
1516 nppath =
1518
1520 {
1521 /* Neither a partial nor a parallel-safe path? Forget it. */
1522 parallel_append_valid = false;
1523 }
1524 else if (nppath == NULL ||
1526 cheapest_partial_path->total_cost < nppath->total_cost))
1527 {
1528 /* Partial path is cheaper or the only option. */
1531 &parallel_append.partial_subpaths,
1532 &parallel_append.subpaths,
1533 &parallel_append.child_append_relid_sets);
1534 }
1535 else
1536 {
1537 /*
1538 * Either we've got only a non-partial path, or we think that
1539 * a single backend can execute the best non-partial path
1540 * faster than all the parallel backends working together can
1541 * execute the best partial path.
1542 *
1543 * It might make sense to be more aggressive here. Even if
1544 * the best non-partial path is more expensive than the best
1545 * partial path, it could still be better to choose the
1546 * non-partial path if there are several such paths that can
1547 * be given to different workers. For now, we don't try to
1548 * figure that out.
1549 */
1551 &parallel_append.subpaths,
1552 NULL,
1553 &parallel_append.child_append_relid_sets);
1554 }
1555 }
1556
1557 /*
1558 * Collect lists of all the available path orderings and
1559 * parameterizations for all the children. We use these as a
1560 * heuristic to indicate which sort orderings and parameterizations we
1561 * should build Append and MergeAppend paths for.
1562 */
1563 foreach(lcp, childrel->pathlist)
1564 {
1565 Path *childpath = (Path *) lfirst(lcp);
1566 List *childkeys = childpath->pathkeys;
1568
1569 /* Unsorted paths don't contribute to pathkey list */
1570 if (childkeys != NIL)
1571 {
1572 ListCell *lpk;
1573 bool found = false;
1574
1575 /* Have we already seen this ordering? */
1576 foreach(lpk, all_child_pathkeys)
1577 {
1579
1582 {
1583 found = true;
1584 break;
1585 }
1586 }
1587 if (!found)
1588 {
1589 /* No, so add it to all_child_pathkeys */
1591 childkeys);
1592 }
1593 }
1594
1595 /* Unparameterized paths don't contribute to param-set list */
1596 if (childouter)
1597 {
1598 ListCell *lco;
1599 bool found = false;
1600
1601 /* Have we already seen this param set? */
1602 foreach(lco, all_child_outers)
1603 {
1605
1607 {
1608 found = true;
1609 break;
1610 }
1611 }
1612 if (!found)
1613 {
1614 /* No, so add it to all_child_outers */
1616 childouter);
1617 }
1618 }
1619 }
1620 }
1621
1622 /*
1623 * If we found unparameterized paths for all children, build an unordered,
1624 * unparameterized Append path for the rel. (Note: this is correct even
1625 * if we have zero or one live subpath due to constraint exclusion.)
1626 */
1629 NIL, NULL, 0, false,
1630 -1));
1631
1632 /* build an AppendPath for the cheap startup paths, if valid */
1633 if (startup_valid)
1634 add_path(rel, (Path *) create_append_path(root, rel, startup,
1635 NIL, NULL, 0, false, -1));
1636
1637 /*
1638 * Consider an append of unordered, unparameterized partial paths. Make
1639 * it parallel-aware if possible.
1640 */
1641 if (partial_only_valid && partial_only.partial_subpaths != NIL)
1642 {
1644 ListCell *lc;
1645 int parallel_workers = 0;
1646
1647 /* Find the highest number of workers requested for any subpath. */
1648 foreach(lc, partial_only.partial_subpaths)
1649 {
1650 Path *path = lfirst(lc);
1651
1652 parallel_workers = Max(parallel_workers, path->parallel_workers);
1653 }
1654 Assert(parallel_workers > 0);
1655
1656 /*
1657 * If the use of parallel append is permitted, always request at least
1658 * log2(# of children) workers. We assume it can be useful to have
1659 * extra workers in this case because they will be spread out across
1660 * the children. The precise formula is just a guess, but we don't
1661 * want to end up with a radically different answer for a table with N
1662 * partitions vs. an unpartitioned table with the same data, so the
1663 * use of some kind of log-scaling here seems to make some sense.
1664 */
1666 {
1667 parallel_workers = Max(parallel_workers,
1669 parallel_workers = Min(parallel_workers,
1671 }
1672 Assert(parallel_workers > 0);
1673
1674 /* Generate a partial append path. */
1676 NIL, NULL, parallel_workers,
1678 -1);
1679
1680 /*
1681 * Make sure any subsequent partial paths use the same row count
1682 * estimate.
1683 */
1684 partial_rows = appendpath->path.rows;
1685
1686 /* Add the path. */
1688 }
1689
1690 /*
1691 * Consider a parallel-aware append using a mix of partial and non-partial
1692 * paths. (This only makes sense if there's at least one child which has
1693 * a non-partial path that is substantially cheaper than any partial path;
1694 * otherwise, we should use the append path added in the previous step.)
1695 */
1696 if (parallel_append_valid && parallel_append.subpaths != NIL)
1697 {
1699 ListCell *lc;
1700 int parallel_workers = 0;
1701
1702 /*
1703 * Find the highest number of workers requested for any partial
1704 * subpath.
1705 */
1706 foreach(lc, parallel_append.partial_subpaths)
1707 {
1708 Path *path = lfirst(lc);
1709
1710 parallel_workers = Max(parallel_workers, path->parallel_workers);
1711 }
1712
1713 /*
1714 * Same formula here as above. It's even more important in this
1715 * instance because the non-partial paths won't contribute anything to
1716 * the planned number of parallel workers.
1717 */
1718 parallel_workers = Max(parallel_workers,
1720 parallel_workers = Min(parallel_workers,
1722 Assert(parallel_workers > 0);
1723
1725 NIL, NULL, parallel_workers, true,
1726 partial_rows);
1728 }
1729
1730 /*
1731 * Also build unparameterized ordered append paths based on the collected
1732 * list of child pathkeys.
1733 */
1737
1738 /*
1739 * Build Append paths for each parameterization seen among the child rels.
1740 * (This may look pretty expensive, but in most cases of practical
1741 * interest, the child rels will expose mostly the same parameterizations,
1742 * so that not that many cases actually get considered here.)
1743 *
1744 * The Append node itself cannot enforce quals, so all qual checking must
1745 * be done in the child paths. This means that to have a parameterized
1746 * Append path, we must have the exact same parameterization for each
1747 * child path; otherwise some children might be failing to check the
1748 * moved-down quals. To make them match up, we can try to increase the
1749 * parameterization of lesser-parameterized paths.
1750 */
1751 foreach(l, all_child_outers)
1752 {
1754 ListCell *lcr;
1756 bool parameterized_valid = true;
1757
1758 /* Select the child paths for an Append with this parameterization */
1759 foreach(lcr, live_childrels)
1760 {
1762 Path *subpath;
1763
1764 if (childrel->pathlist == NIL)
1765 {
1766 /* failed to make a suitable path for this child */
1767 parameterized_valid = false;
1768 break;
1769 }
1770
1772 childrel,
1774 if (subpath == NULL)
1775 {
1776 /* failed to make a suitable path for this child */
1777 parameterized_valid = false;
1778 break;
1779 }
1781 &parameterized.child_append_relid_sets);
1782 }
1783
1785 add_path(rel, (Path *)
1787 NIL, required_outer, 0, false,
1788 -1));
1789 }
1790
1791 /*
1792 * When there is only a single child relation, the Append path can inherit
1793 * any ordering available for the child rel's path, so that it's useful to
1794 * consider ordered partial paths. Above we only considered the cheapest
1795 * partial path for each child, but let's also make paths using any
1796 * partial paths that have pathkeys.
1797 */
1798 if (list_length(live_childrels) == 1)
1799 {
1801
1802 /* skip the cheapest partial path, since we already used that above */
1803 for_each_from(l, childrel->partial_pathlist, 1)
1804 {
1805 Path *path = (Path *) lfirst(l);
1807 AppendPathInput append = {0};
1808
1809 /* skip paths with no pathkeys. */
1810 if (path->pathkeys == NIL)
1811 continue;
1812
1815 path->parallel_workers, true,
1816 partial_rows);
1818 }
1819 }
1820}
1821
1822/*
1823 * generate_orderedappend_paths
1824 * Generate ordered append paths for an append relation
1825 *
1826 * Usually we generate MergeAppend paths here, but there are some special
1827 * cases where we can generate simple Append paths, because the subpaths
1828 * can provide tuples in the required order already.
1829 *
1830 * We generate a path for each ordering (pathkey list) appearing in
1831 * all_child_pathkeys.
1832 *
1833 * We consider the cheapest-startup and cheapest-total cases, and also the
1834 * cheapest-fractional case when not all tuples need to be retrieved. For each
1835 * interesting ordering, we collect all the cheapest startup subpaths, all the
1836 * cheapest total paths, and, if applicable, all the cheapest fractional paths,
1837 * and build a suitable path for each case.
1838 *
1839 * We don't currently generate any parameterized ordered paths here. While
1840 * it would not take much more code here to do so, it's very unclear that it
1841 * is worth the planning cycles to investigate such paths: there's little
1842 * use for an ordered path on the inside of a nestloop. In fact, it's likely
1843 * that the current coding of add_path would reject such paths out of hand,
1844 * because add_path gives no credit for sort ordering of parameterized paths,
1845 * and a parameterized MergeAppend is going to be more expensive than the
1846 * corresponding parameterized Append path. If we ever try harder to support
1847 * parameterized mergejoin plans, it might be worth adding support for
1848 * parameterized paths here to feed such joins. (See notes in
1849 * optimizer/README for why that might not ever happen, though.)
1850 */
1851static void
1855{
1856 ListCell *lcp;
1859 bool partition_pathkeys_partial = true;
1861
1862 /*
1863 * Some partitioned table setups may allow us to use an Append node
1864 * instead of a MergeAppend. This is possible in cases such as RANGE
1865 * partitioned tables where it's guaranteed that an earlier partition must
1866 * contain rows which come earlier in the sort order. To detect whether
1867 * this is relevant, build pathkey descriptions of the partition ordering,
1868 * for both forward and reverse scans.
1869 */
1870 if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1871 partitions_are_ordered(rel->boundinfo, rel->live_parts))
1872 {
1876
1880
1881 /*
1882 * You might think we should truncate_useless_pathkeys here, but
1883 * allowing partition keys which are a subset of the query's pathkeys
1884 * can often be useful. For example, consider a table partitioned by
1885 * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1886 * paths that can produce the a, b, c ordering (perhaps via indexes on
1887 * (a, b, c)) then it works to consider the appendrel output as
1888 * ordered by a, b, c.
1889 */
1890 }
1891
1892 /* Now consider each interesting sort ordering */
1893 foreach(lcp, all_child_pathkeys)
1894 {
1895 List *pathkeys = (List *) lfirst(lcp);
1896 AppendPathInput startup = {0};
1897 AppendPathInput total = {0};
1899 bool startup_neq_total = false;
1900 bool fraction_neq_total = false;
1903 int end_index;
1904 int first_index;
1905 int direction;
1906
1907 /*
1908 * Determine if this sort ordering matches any partition pathkeys we
1909 * have, for both ascending and descending partition order. If the
1910 * partition pathkeys happen to be contained in pathkeys then it still
1911 * works, as described above, providing that the partition pathkeys
1912 * are complete and not just a prefix of the partition keys. (In such
1913 * cases we'll be relying on the child paths to have sorted the
1914 * lower-order columns of the required pathkeys.)
1915 */
1920
1925
1926 /*
1927 * When the required pathkeys match the reverse of the partition
1928 * order, we must build the list of paths in reverse starting with the
1929 * last matching partition first. We can get away without making any
1930 * special cases for this in the loop below by just looping backward
1931 * over the child relations in this case.
1932 */
1934 {
1935 /* loop backward */
1937 end_index = -1;
1938 direction = -1;
1939
1940 /*
1941 * Set this to true to save us having to check for
1942 * match_partition_order_desc in the loop below.
1943 */
1944 match_partition_order = true;
1945 }
1946 else
1947 {
1948 /* for all other case, loop forward */
1949 first_index = 0;
1951 direction = 1;
1952 }
1953
1954 /* Select the child paths for this ordering... */
1955 for (int i = first_index; i != end_index; i += direction)
1956 {
1961
1962 /* Locate the right paths, if they are available. */
1965 pathkeys,
1966 NULL,
1968 false);
1971 pathkeys,
1972 NULL,
1973 TOTAL_COST,
1974 false);
1975
1976 /*
1977 * If we can't find any paths with the right order just use the
1978 * cheapest-total path; we'll have to sort it later.
1979 */
1981 {
1983 childrel->cheapest_total_path;
1984 /* Assert we do have an unparameterized path for this child */
1985 Assert(cheapest_total->param_info == NULL);
1986 }
1987
1988 /*
1989 * When building a fractional path, determine a cheapest
1990 * fractional path for each child relation too. Looking at startup
1991 * and total costs is not enough, because the cheapest fractional
1992 * path may be dominated by two separate paths (one for startup,
1993 * one for total).
1994 *
1995 * When needed (building fractional path), determine the cheapest
1996 * fractional path too.
1997 */
1998 if (root->tuple_fraction > 0)
1999 {
2000 double path_fraction = root->tuple_fraction;
2001
2002 /*
2003 * We should not have a dummy child relation here. However,
2004 * we cannot use childrel->rows to compute the tuple fraction,
2005 * as childrel can be an upper relation with an unset row
2006 * estimate. Instead, we use the row estimate from the
2007 * cheapest_total path, which should already have been forced
2008 * to a sane value.
2009 */
2010 Assert(cheapest_total->rows > 0);
2011
2012 /* Convert absolute limit to a path fraction */
2013 if (path_fraction >= 1.0)
2015
2018 pathkeys,
2019 NULL,
2021
2022 /*
2023 * If we found no path with matching pathkeys, use the
2024 * cheapest total path instead.
2025 *
2026 * XXX We might consider partially sorted paths too (with an
2027 * incremental sort on top). But we'd have to build all the
2028 * incremental paths, do the costing etc.
2029 *
2030 * Also, notice whether we actually have different paths for
2031 * the "fractional" and "total" cases. This helps avoid
2032 * generating two identical ordered append paths.
2033 */
2037 fraction_neq_total = true;
2038 }
2039
2040 /*
2041 * Notice whether we actually have different paths for the
2042 * "cheapest" and "total" cases. This helps avoid generating two
2043 * identical ordered append paths.
2044 */
2046 startup_neq_total = true;
2047
2048 /*
2049 * Collect the appropriate child paths. The required logic varies
2050 * for the Append and MergeAppend cases.
2051 */
2053 {
2054 /*
2055 * We're going to make a plain Append path. We don't need
2056 * most of what accumulate_append_subpath would do, but we do
2057 * want to cut out child Appends or MergeAppends if they have
2058 * just a single subpath (and hence aren't doing anything
2059 * useful).
2060 */
2063 &startup.child_append_relid_sets);
2067
2068 startup.subpaths = lappend(startup.subpaths, cheapest_startup);
2069 total.subpaths = lappend(total.subpaths, cheapest_total);
2070
2072 {
2075 &fractional.child_append_relid_sets);
2076 fractional.subpaths =
2078 }
2079 }
2080 else
2081 {
2082 /*
2083 * Otherwise, rely on accumulate_append_subpath to collect the
2084 * child paths for the MergeAppend.
2085 */
2087 &startup.subpaths, NULL,
2088 &startup.child_append_relid_sets);
2090 &total.subpaths, NULL,
2092
2095 &fractional.subpaths, NULL,
2096 &fractional.child_append_relid_sets);
2097 }
2098 }
2099
2100 /* ... and build the Append or MergeAppend paths */
2102 {
2103 /* We only need Append */
2105 rel,
2106 startup,
2107 pathkeys,
2108 NULL,
2109 0,
2110 false,
2111 -1));
2114 rel,
2115 total,
2116 pathkeys,
2117 NULL,
2118 0,
2119 false,
2120 -1));
2121
2122 if (fractional.subpaths && fraction_neq_total)
2124 rel,
2125 fractional,
2126 pathkeys,
2127 NULL,
2128 0,
2129 false,
2130 -1));
2131 }
2132 else
2133 {
2134 /* We need MergeAppend */
2136 rel,
2137 startup.subpaths,
2139 pathkeys,
2140 NULL));
2143 rel,
2144 total.subpaths,
2146 pathkeys,
2147 NULL));
2148
2149 if (fractional.subpaths && fraction_neq_total)
2151 rel,
2152 fractional.subpaths,
2153 fractional.child_append_relid_sets,
2154 pathkeys,
2155 NULL));
2156 }
2157 }
2158}
2159
2160/*
2161 * get_cheapest_parameterized_child_path
2162 * Get cheapest path for this relation that has exactly the requested
2163 * parameterization.
2164 *
2165 * Returns NULL if unable to create such a path.
2166 */
2167static Path *
2170{
2171 Path *cheapest;
2172 ListCell *lc;
2173
2174 /*
2175 * Look up the cheapest existing path with no more than the needed
2176 * parameterization. If it has exactly the needed parameterization, we're
2177 * done.
2178 */
2180 NIL,
2182 TOTAL_COST,
2183 false);
2184 Assert(cheapest != NULL);
2186 return cheapest;
2187
2188 /*
2189 * Otherwise, we can "reparameterize" an existing path to match the given
2190 * parameterization, which effectively means pushing down additional
2191 * joinquals to be checked within the path's scan. However, some existing
2192 * paths might check the available joinquals already while others don't;
2193 * therefore, it's not clear which existing path will be cheapest after
2194 * reparameterization. We have to go through them all and find out.
2195 */
2196 cheapest = NULL;
2197 foreach(lc, rel->pathlist)
2198 {
2199 Path *path = (Path *) lfirst(lc);
2200
2201 /* Can't use it if it needs more than requested parameterization */
2203 continue;
2204
2205 /*
2206 * Reparameterization can only increase the path's cost, so if it's
2207 * already more expensive than the current cheapest, forget it.
2208 */
2209 if (cheapest != NULL &&
2211 continue;
2212
2213 /* Reparameterize if needed, then recheck cost */
2215 {
2216 path = reparameterize_path(root, path, required_outer, 1.0);
2217 if (path == NULL)
2218 continue; /* failed to reparameterize this one */
2220
2221 if (cheapest != NULL &&
2223 continue;
2224 }
2225
2226 /* We have a new best path */
2227 cheapest = path;
2228 }
2229
2230 /* Return the best path, or NULL if we found no suitable candidate */
2231 return cheapest;
2232}
2233
2234/*
2235 * accumulate_append_subpath
2236 * Add a subpath to the list being built for an Append or MergeAppend.
2237 *
2238 * It's possible that the child is itself an Append or MergeAppend path, in
2239 * which case we can "cut out the middleman" and just add its child paths to
2240 * our own list. (We don't try to do this earlier because we need to apply
2241 * both levels of transformation to the quals.)
2242 *
2243 * Note that if we omit a child MergeAppend in this way, we are effectively
2244 * omitting a sort step, which seems fine: if the parent is to be an Append,
2245 * its result would be unsorted anyway, while if the parent is to be a
2246 * MergeAppend, there's no point in a separate sort on a child.
2247 *
2248 * Normally, either path is a partial path and subpaths is a list of partial
2249 * paths, or else path is a non-partial plan and subpaths is a list of those.
2250 * However, if path is a parallel-aware Append, then we add its partial path
2251 * children to subpaths and the rest to special_subpaths. If the latter is
2252 * NULL, we don't flatten the path at all (unless it contains only partial
2253 * paths).
2254 */
2255static void
2257 List **child_append_relid_sets)
2258{
2259 if (IsA(path, AppendPath))
2260 {
2261 AppendPath *apath = (AppendPath *) path;
2262
2263 if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2264 {
2265 *subpaths = list_concat(*subpaths, apath->subpaths);
2266 *child_append_relid_sets =
2267 lappend(*child_append_relid_sets, path->parent->relids);
2268 *child_append_relid_sets =
2269 list_concat(*child_append_relid_sets,
2270 apath->child_append_relid_sets);
2271 return;
2272 }
2273 else if (special_subpaths != NULL)
2274 {
2276
2277 /* Split Parallel Append into partial and non-partial subpaths */
2278 *subpaths = list_concat(*subpaths,
2279 list_copy_tail(apath->subpaths,
2280 apath->first_partial_path));
2282 apath->first_partial_path);
2285 *child_append_relid_sets =
2286 lappend(*child_append_relid_sets, path->parent->relids);
2287 *child_append_relid_sets =
2288 list_concat(*child_append_relid_sets,
2289 apath->child_append_relid_sets);
2290 return;
2291 }
2292 }
2293 else if (IsA(path, MergeAppendPath))
2294 {
2296
2297 *subpaths = list_concat(*subpaths, mpath->subpaths);
2298 *child_append_relid_sets =
2299 lappend(*child_append_relid_sets, path->parent->relids);
2300 *child_append_relid_sets =
2301 list_concat(*child_append_relid_sets,
2302 mpath->child_append_relid_sets);
2303 return;
2304 }
2305
2306 *subpaths = lappend(*subpaths, path);
2307}
2308
2309/*
2310 * get_singleton_append_subpath
2311 * Returns the single subpath of an Append/MergeAppend, or just
2312 * return 'path' if it's not a single sub-path Append/MergeAppend.
2313 *
2314 * As a side effect, whenever we return a single subpath rather than the
2315 * original path, add the relid sets for the original path to
2316 * child_append_relid_sets, so that those relids don't entirely disappear
2317 * from the final plan.
2318 *
2319 * Note: 'path' must not be a parallel-aware path.
2320 */
2321static Path *
2322get_singleton_append_subpath(Path *path, List **child_append_relid_sets)
2323{
2324 Assert(!path->parallel_aware);
2325
2326 if (IsA(path, AppendPath))
2327 {
2328 AppendPath *apath = (AppendPath *) path;
2329
2330 if (list_length(apath->subpaths) == 1)
2331 {
2332 *child_append_relid_sets =
2333 lappend(*child_append_relid_sets, path->parent->relids);
2334 *child_append_relid_sets =
2335 list_concat(*child_append_relid_sets,
2336 apath->child_append_relid_sets);
2337 return (Path *) linitial(apath->subpaths);
2338 }
2339 }
2340 else if (IsA(path, MergeAppendPath))
2341 {
2343
2344 if (list_length(mpath->subpaths) == 1)
2345 {
2346 *child_append_relid_sets =
2347 lappend(*child_append_relid_sets, path->parent->relids);
2348 *child_append_relid_sets =
2349 list_concat(*child_append_relid_sets,
2350 mpath->child_append_relid_sets);
2351 return (Path *) linitial(mpath->subpaths);
2352 }
2353 }
2354
2355 return path;
2356}
2357
2358/*
2359 * set_dummy_rel_pathlist
2360 * Build a dummy path for a relation that's been excluded by constraints
2361 *
2362 * Rather than inventing a special "dummy" path type, we represent this as an
2363 * AppendPath with no members (see also IS_DUMMY_APPEND/IS_DUMMY_REL macros).
2364 *
2365 * (See also mark_dummy_rel, which does basically the same thing, but is
2366 * typically used to change a rel into dummy state after we already made
2367 * paths for it.)
2368 */
2369static void
2371{
2372 AppendPathInput in = {0};
2373
2374 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2375 rel->rows = 0;
2376 rel->reltarget->width = 0;
2377
2378 /* Discard any pre-existing paths; no further need for them */
2379 rel->pathlist = NIL;
2380 rel->partial_pathlist = NIL;
2381
2382 /* Set up the dummy path */
2383 add_path(rel, (Path *) create_append_path(NULL, rel, in,
2384 NIL, rel->lateral_relids,
2385 0, false, -1));
2386
2387 /*
2388 * We set the cheapest-path fields immediately, just in case they were
2389 * pointing at some discarded path. This is redundant in current usage
2390 * because set_rel_pathlist will do it later, but it's cheap so we keep it
2391 * for safety and consistency with mark_dummy_rel.
2392 */
2393 set_cheapest(rel);
2394}
2395
2396/*
2397 * find_window_run_conditions
2398 * Determine if 'wfunc' is really a WindowFunc and call its prosupport
2399 * function to determine the function's monotonic properties. We then
2400 * see if 'opexpr' can be used to short-circuit execution.
2401 *
2402 * For example row_number() over (order by ...) always produces a value one
2403 * higher than the previous. If someone has a window function in a subquery
2404 * and has a WHERE clause in the outer query to filter rows <= 10, then we may
2405 * as well stop processing the windowagg once the row number reaches 11. Here
2406 * we check if 'opexpr' might help us to stop doing needless extra processing
2407 * in WindowAgg nodes.
2408 *
2409 * '*keep_original' is set to true if the caller should also use 'opexpr' for
2410 * its original purpose. This is set to false if the caller can assume that
2411 * the run condition will handle all of the required filtering.
2412 *
2413 * Returns true if 'opexpr' was found to be useful and was added to the
2414 * WindowFunc's runCondition. We also set *keep_original accordingly and add
2415 * 'attno' to *run_cond_attrs offset by FirstLowInvalidHeapAttributeNumber.
2416 * If the 'opexpr' cannot be used then we set *keep_original to true and
2417 * return false.
2418 */
2419static bool
2421 WindowFunc *wfunc, OpExpr *opexpr, bool wfunc_left,
2423{
2425 Expr *otherexpr;
2429 List *opinfos;
2432 ListCell *lc;
2433
2434 *keep_original = true;
2435
2436 while (IsA(wfunc, RelabelType))
2437 wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2438
2439 /* we can only work with window functions */
2440 if (!IsA(wfunc, WindowFunc))
2441 return false;
2442
2443 /* can't use it if there are subplans in the WindowFunc */
2444 if (contain_subplans((Node *) wfunc))
2445 return false;
2446
2448
2449 /* Check if there's a support function for 'wfunc' */
2450 if (!OidIsValid(prosupport))
2451 return false;
2452
2453 /* get the Expr from the other side of the OpExpr */
2454 if (wfunc_left)
2455 otherexpr = lsecond(opexpr->args);
2456 else
2457 otherexpr = linitial(opexpr->args);
2458
2459 /*
2460 * The value being compared must not change during the evaluation of the
2461 * window partition.
2462 */
2464 return false;
2465
2466 /* find the window clause belonging to the window function */
2467 wclause = (WindowClause *) list_nth(subquery->windowClause,
2468 wfunc->winref - 1);
2469
2471 req.window_func = wfunc;
2472 req.window_clause = wclause;
2473
2474 /* call the support function */
2477 PointerGetDatum(&req)));
2478
2479 /*
2480 * Nothing to do if the function is neither monotonically increasing nor
2481 * monotonically decreasing.
2482 */
2483 if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2484 return false;
2485
2486 runopexpr = NULL;
2489
2490 foreach(lc, opinfos)
2491 {
2493 CompareType cmptype = opinfo->cmptype;
2494
2495 /* handle < / <= */
2496 if (cmptype == COMPARE_LT || cmptype == COMPARE_LE)
2497 {
2498 /*
2499 * < / <= is supported for monotonically increasing functions in
2500 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2501 * for monotonically decreasing functions.
2502 */
2503 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2504 (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2505 {
2506 *keep_original = false;
2507 runopexpr = opexpr;
2508 runoperator = opexpr->opno;
2509 }
2510 break;
2511 }
2512 /* handle > / >= */
2513 else if (cmptype == COMPARE_GT || cmptype == COMPARE_GE)
2514 {
2515 /*
2516 * > / >= is supported for monotonically decreasing functions in
2517 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2518 * for monotonically increasing functions.
2519 */
2520 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2521 (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2522 {
2523 *keep_original = false;
2524 runopexpr = opexpr;
2525 runoperator = opexpr->opno;
2526 }
2527 break;
2528 }
2529 /* handle = */
2530 else if (cmptype == COMPARE_EQ)
2531 {
2533
2534 /*
2535 * When both monotonically increasing and decreasing then the
2536 * return value of the window function will be the same each time.
2537 * We can simply use 'opexpr' as the run condition without
2538 * modifying it.
2539 */
2541 {
2542 *keep_original = false;
2543 runopexpr = opexpr;
2544 runoperator = opexpr->opno;
2545 break;
2546 }
2547
2548 /*
2549 * When monotonically increasing we make a qual with <wfunc> <=
2550 * <value> or <value> >= <wfunc> in order to filter out values
2551 * which are above the value in the equality condition. For
2552 * monotonically decreasing functions we want to filter values
2553 * below the value in the equality condition.
2554 */
2556 newcmptype = wfunc_left ? COMPARE_LE : COMPARE_GE;
2557 else
2558 newcmptype = wfunc_left ? COMPARE_GE : COMPARE_LE;
2559
2560 /* We must keep the original equality qual */
2561 *keep_original = true;
2562 runopexpr = opexpr;
2563
2564 /* determine the operator to use for the WindowFuncRunCondition */
2566 opinfo->oplefttype,
2567 opinfo->oprighttype,
2568 newcmptype);
2569 break;
2570 }
2571 }
2572
2573 if (runopexpr != NULL)
2574 {
2576
2578 wfuncrc->opno = runoperator;
2579 wfuncrc->inputcollid = runopexpr->inputcollid;
2580 wfuncrc->wfunc_left = wfunc_left;
2582
2583 wfunc->runCondition = lappend(wfunc->runCondition, wfuncrc);
2584
2585 /* record that this attno was used in a run condition */
2588 return true;
2589 }
2590
2591 /* unsupported OpExpr */
2592 return false;
2593}
2594
2595/*
2596 * check_and_push_window_quals
2597 * Check if 'clause' is a qual that can be pushed into a WindowFunc
2598 * as a 'runCondition' qual. These, when present, allow some unnecessary
2599 * work to be skipped during execution.
2600 *
2601 * 'run_cond_attrs' will be populated with all targetlist resnos of subquery
2602 * targets (offset by FirstLowInvalidHeapAttributeNumber) that we pushed
2603 * window quals for.
2604 *
2605 * Returns true if the caller still must keep the original qual or false if
2606 * the caller can safely ignore the original qual because the WindowAgg node
2607 * will use the runCondition to stop returning tuples.
2608 */
2609static bool
2612{
2613 OpExpr *opexpr = (OpExpr *) clause;
2614 bool keep_original = true;
2615 Var *var1;
2616 Var *var2;
2617
2618 /* We're only able to use OpExprs with 2 operands */
2619 if (!IsA(opexpr, OpExpr))
2620 return true;
2621
2622 if (list_length(opexpr->args) != 2)
2623 return true;
2624
2625 /*
2626 * Currently, we restrict this optimization to strict OpExprs. The reason
2627 * for this is that during execution, once the runcondition becomes false,
2628 * we stop evaluating WindowFuncs. To avoid leaving around stale window
2629 * function result values, we set them to NULL. Having only strict
2630 * OpExprs here ensures that we properly filter out the tuples with NULLs
2631 * in the top-level WindowAgg.
2632 */
2633 set_opfuncid(opexpr);
2634 if (!func_strict(opexpr->opfuncid))
2635 return true;
2636
2637 /*
2638 * Check for plain Vars that reference window functions in the subquery.
2639 * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2640 * be used as part of the run condition.
2641 */
2642
2643 /* Check the left side of the OpExpr */
2644 var1 = linitial(opexpr->args);
2645 if (IsA(var1, Var) && var1->varattno > 0)
2646 {
2647 TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2648 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2649
2650 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2652 return keep_original;
2653 }
2654
2655 /* and check the right side */
2656 var2 = lsecond(opexpr->args);
2657 if (IsA(var2, Var) && var2->varattno > 0)
2658 {
2659 TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2660 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2661
2662 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2663 false, &keep_original, run_cond_attrs))
2664 return keep_original;
2665 }
2666
2667 return true;
2668}
2669
2670/*
2671 * set_subquery_pathlist
2672 * Generate SubqueryScan access paths for a subquery RTE
2673 *
2674 * We don't currently support generating parameterized paths for subqueries
2675 * by pushing join clauses down into them; it seems too expensive to re-plan
2676 * the subquery multiple times to consider different alternatives.
2677 * (XXX that could stand to be reconsidered, now that we use Paths.)
2678 * So the paths made here will be parameterized if the subquery contains
2679 * LATERAL references, otherwise not. As long as that's true, there's no need
2680 * for a separate set_subquery_size phase: just make the paths right away.
2681 */
2682static void
2684 Index rti, RangeTblEntry *rte)
2685{
2686 Query *parse = root->parse;
2687 Query *subquery = rte->subquery;
2688 bool trivial_pathtarget;
2691 double tuple_fraction;
2694 ListCell *lc;
2695 char *plan_name;
2696
2697 /*
2698 * Must copy the Query so that planning doesn't mess up the RTE contents
2699 * (really really need to fix the planner to not scribble on its input,
2700 * someday ... but see remove_unused_subquery_outputs to start with).
2701 */
2702 subquery = copyObject(subquery);
2703
2704 /*
2705 * If it's a LATERAL subquery, it might contain some Vars of the current
2706 * query level, requiring it to be treated as parameterized, even though
2707 * we don't support pushing down join quals into subqueries.
2708 */
2710
2711 /*
2712 * Zero out result area for subquery_is_pushdown_safe, so that it can set
2713 * flags as needed while recursing. In particular, we need a workspace
2714 * for keeping track of the reasons why columns are unsafe to reference.
2715 * These reasons are stored in the bits inside unsafeFlags[i] when we
2716 * discover reasons that column i of the subquery is unsafe to be used in
2717 * a pushed-down qual.
2718 */
2719 memset(&safetyInfo, 0, sizeof(safetyInfo));
2720 safetyInfo.unsafeFlags = (unsigned char *)
2721 palloc0((list_length(subquery->targetList) + 1) * sizeof(unsigned char));
2722
2723 /*
2724 * If the subquery has the "security_barrier" flag, it means the subquery
2725 * originated from a view that must enforce row-level security. Then we
2726 * must not push down quals that contain leaky functions. (Ideally this
2727 * would be checked inside subquery_is_pushdown_safe, but since we don't
2728 * currently pass the RTE to that function, we must do it here.)
2729 */
2730 safetyInfo.unsafeLeaky = rte->security_barrier;
2731
2732 /*
2733 * If there are any restriction clauses that have been attached to the
2734 * subquery relation, consider pushing them down to become WHERE or HAVING
2735 * quals of the subquery itself. This transformation is useful because it
2736 * may allow us to generate a better plan for the subquery than evaluating
2737 * all the subquery output rows and then filtering them.
2738 *
2739 * There are several cases where we cannot push down clauses. Restrictions
2740 * involving the subquery are checked by subquery_is_pushdown_safe().
2741 * Restrictions on individual clauses are checked by
2742 * qual_is_pushdown_safe(). Also, we don't want to push down
2743 * pseudoconstant clauses; better to have the gating node above the
2744 * subquery.
2745 *
2746 * Non-pushed-down clauses will get evaluated as qpquals of the
2747 * SubqueryScan node.
2748 *
2749 * XXX Are there any cases where we want to make a policy decision not to
2750 * push down a pushable qual, because it'd result in a worse plan?
2751 */
2752 if (rel->baserestrictinfo != NIL &&
2753 subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2754 {
2755 /* OK to consider pushing down individual quals */
2757 ListCell *l;
2758
2759 foreach(l, rel->baserestrictinfo)
2760 {
2761 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2762 Node *clause = (Node *) rinfo->clause;
2763
2764 if (rinfo->pseudoconstant)
2765 {
2767 continue;
2768 }
2769
2770 switch (qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2771 {
2772 case PUSHDOWN_SAFE:
2773 /* Push it down */
2774 subquery_push_qual(subquery, rte, rti, clause);
2775 break;
2776
2778
2779 /*
2780 * Since we can't push the qual down into the subquery,
2781 * check if it happens to reference a window function. If
2782 * so then it might be useful to use for the WindowAgg's
2783 * runCondition.
2784 */
2785 if (!subquery->hasWindowFuncs ||
2786 check_and_push_window_quals(subquery, clause,
2788 {
2789 /*
2790 * subquery has no window funcs or the clause is not a
2791 * suitable window run condition qual or it is, but
2792 * the original must also be kept in the upper query.
2793 */
2795 }
2796 break;
2797
2798 case PUSHDOWN_UNSAFE:
2800 break;
2801 }
2802 }
2804 /* We don't bother recomputing baserestrict_min_security */
2805 }
2806
2807 pfree(safetyInfo.unsafeFlags);
2808
2809 /*
2810 * The upper query might not use all the subquery's output columns; if
2811 * not, we can simplify. Pass the attributes that were pushed down into
2812 * WindowAgg run conditions to ensure we don't accidentally think those
2813 * are unused.
2814 */
2816
2817 /*
2818 * We can safely pass the outer tuple_fraction down to the subquery if the
2819 * outer level has no joining, aggregation, or sorting to do. Otherwise
2820 * we'd better tell the subquery to plan for full retrieval. (XXX This
2821 * could probably be made more intelligent ...)
2822 */
2823 if (parse->hasAggs ||
2824 parse->groupClause ||
2825 parse->groupingSets ||
2826 root->hasHavingQual ||
2827 parse->distinctClause ||
2828 parse->sortClause ||
2829 bms_membership(root->all_baserels) == BMS_MULTIPLE)
2830 tuple_fraction = 0.0; /* default case */
2831 else
2832 tuple_fraction = root->tuple_fraction;
2833
2834 /* plan_params should not be in use in current query level */
2835 Assert(root->plan_params == NIL);
2836
2837 /* Generate a subroot and Paths for the subquery */
2838 plan_name = choose_plan_name(root->glob, rte->eref->aliasname, false);
2839 rel->subroot = subquery_planner(root->glob, subquery, plan_name,
2840 root, NULL, false, tuple_fraction, NULL);
2841
2842 /* Isolate the params needed by this specific subplan */
2843 rel->subplan_params = root->plan_params;
2844 root->plan_params = NIL;
2845
2846 /*
2847 * It's possible that constraint exclusion proved the subquery empty. If
2848 * so, it's desirable to produce an unadorned dummy path so that we will
2849 * recognize appropriate optimizations at this query level.
2850 */
2852
2854 {
2856 return;
2857 }
2858
2859 /*
2860 * Mark rel with estimated output rows, width, etc. Note that we have to
2861 * do this before generating outer-query paths, else cost_subqueryscan is
2862 * not happy.
2863 */
2865
2866 /*
2867 * Also detect whether the reltarget is trivial, so that we can pass that
2868 * info to cost_subqueryscan (rather than re-deriving it multiple times).
2869 * It's trivial if it fetches all the subplan output columns in order.
2870 */
2871 if (list_length(rel->reltarget->exprs) != list_length(subquery->targetList))
2872 trivial_pathtarget = false;
2873 else
2874 {
2875 trivial_pathtarget = true;
2876 foreach(lc, rel->reltarget->exprs)
2877 {
2878 Node *node = (Node *) lfirst(lc);
2879 Var *var;
2880
2881 if (!IsA(node, Var))
2882 {
2883 trivial_pathtarget = false;
2884 break;
2885 }
2886 var = (Var *) node;
2887 if (var->varno != rti ||
2888 var->varattno != foreach_current_index(lc) + 1)
2889 {
2890 trivial_pathtarget = false;
2891 break;
2892 }
2893 }
2894 }
2895
2896 /*
2897 * For each Path that subquery_planner produced, make a SubqueryScanPath
2898 * in the outer query.
2899 */
2900 foreach(lc, sub_final_rel->pathlist)
2901 {
2902 Path *subpath = (Path *) lfirst(lc);
2903 List *pathkeys;
2904
2905 /* Convert subpath's pathkeys to outer representation */
2907 rel,
2908 subpath->pathkeys,
2909 make_tlist_from_pathtarget(subpath->pathtarget));
2910
2911 /* Generate outer path using this subpath */
2912 add_path(rel, (Path *)
2915 pathkeys, required_outer));
2916 }
2917
2918 /* If outer rel allows parallelism, do same for partial paths. */
2920 {
2921 /* If consider_parallel is false, there should be no partial paths. */
2922 Assert(sub_final_rel->consider_parallel ||
2923 sub_final_rel->partial_pathlist == NIL);
2924
2925 /* Same for partial paths. */
2926 foreach(lc, sub_final_rel->partial_pathlist)
2927 {
2928 Path *subpath = (Path *) lfirst(lc);
2929 List *pathkeys;
2930
2931 /* Convert subpath's pathkeys to outer representation */
2933 rel,
2934 subpath->pathkeys,
2935 make_tlist_from_pathtarget(subpath->pathtarget));
2936
2937 /* Generate outer path using this subpath */
2938 add_partial_path(rel, (Path *)
2941 pathkeys,
2943 }
2944 }
2945}
2946
2947/*
2948 * set_function_pathlist
2949 * Build the (single) access path for a function RTE
2950 */
2951static void
2953{
2955 List *pathkeys = NIL;
2956
2957 /*
2958 * We don't support pushing join clauses into the quals of a function
2959 * scan, but it could still have required parameterization due to LATERAL
2960 * refs in the function expression.
2961 */
2963
2964 /*
2965 * The result is considered unordered unless ORDINALITY was used, in which
2966 * case it is ordered by the ordinal column (the last one). See if we
2967 * care, by checking for uses of that Var in equivalence classes.
2968 */
2969 if (rte->funcordinality)
2970 {
2972 Var *var = NULL;
2973 ListCell *lc;
2974
2975 /*
2976 * Is there a Var for it in rel's targetlist? If not, the query did
2977 * not reference the ordinality column, or at least not in any way
2978 * that would be interesting for sorting.
2979 */
2980 foreach(lc, rel->reltarget->exprs)
2981 {
2982 Var *node = (Var *) lfirst(lc);
2983
2984 /* checking varno/varlevelsup is just paranoia */
2985 if (IsA(node, Var) &&
2986 node->varattno == ordattno &&
2987 node->varno == rel->relid &&
2988 node->varlevelsup == 0)
2989 {
2990 var = node;
2991 break;
2992 }
2993 }
2994
2995 /*
2996 * Try to build pathkeys for this Var with int8 sorting. We tell
2997 * build_expression_pathkey not to build any new equivalence class; if
2998 * the Var isn't already mentioned in some EC, it means that nothing
2999 * cares about the ordering.
3000 */
3001 if (var)
3002 pathkeys = build_expression_pathkey(root,
3003 (Expr *) var,
3005 rel->relids,
3006 false);
3007 }
3008
3009 /* Generate appropriate path */
3011 pathkeys, required_outer));
3012}
3013
3014/*
3015 * set_values_pathlist
3016 * Build the (single) access path for a VALUES RTE
3017 */
3018static void
3020{
3022
3023 /*
3024 * We don't support pushing join clauses into the quals of a values scan,
3025 * but it could still have required parameterization due to LATERAL refs
3026 * in the values expressions.
3027 */
3029
3030 /* Generate appropriate path */
3032}
3033
3034/*
3035 * set_tablefunc_pathlist
3036 * Build the (single) access path for a table func RTE
3037 */
3038static void
3040{
3042
3043 /*
3044 * We don't support pushing join clauses into the quals of a tablefunc
3045 * scan, but it could still have required parameterization due to LATERAL
3046 * refs in the function expression.
3047 */
3049
3050 /* Generate appropriate path */
3053}
3054
3055/*
3056 * set_cte_pathlist
3057 * Build the (single) access path for a non-self-reference CTE RTE
3058 *
3059 * There's no need for a separate set_cte_size phase, since we don't
3060 * support join-qual-parameterized paths for CTEs.
3061 */
3062static void
3064{
3065 Path *ctepath;
3066 Plan *cteplan;
3068 Index levelsup;
3069 List *pathkeys;
3070 int ndx;
3071 ListCell *lc;
3072 int plan_id;
3074
3075 /*
3076 * Find the referenced CTE, and locate the path and plan previously made
3077 * for it.
3078 */
3079 levelsup = rte->ctelevelsup;
3080 cteroot = root;
3081 while (levelsup-- > 0)
3082 {
3083 cteroot = cteroot->parent_root;
3084 if (!cteroot) /* shouldn't happen */
3085 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3086 }
3087
3088 /*
3089 * Note: cte_plan_ids can be shorter than cteList, if we are still working
3090 * on planning the CTEs (ie, this is a side-reference from another CTE).
3091 * So we mustn't use forboth here.
3092 */
3093 ndx = 0;
3094 foreach(lc, cteroot->parse->cteList)
3095 {
3097
3098 if (strcmp(cte->ctename, rte->ctename) == 0)
3099 break;
3100 ndx++;
3101 }
3102 if (lc == NULL) /* shouldn't happen */
3103 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3104 if (ndx >= list_length(cteroot->cte_plan_ids))
3105 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3106 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3107 if (plan_id <= 0)
3108 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
3109
3110 Assert(list_length(root->glob->subpaths) == list_length(root->glob->subplans));
3111 ctepath = (Path *) list_nth(root->glob->subpaths, plan_id - 1);
3112 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
3113
3114 /* Mark rel with estimated output rows, width, etc */
3115 set_cte_size_estimates(root, rel, cteplan->plan_rows);
3116
3117 /* Convert the ctepath's pathkeys to outer query's representation */
3119 rel,
3120 ctepath->pathkeys,
3121 cteplan->targetlist);
3122
3123 /*
3124 * We don't support pushing join clauses into the quals of a CTE scan, but
3125 * it could still have required parameterization due to LATERAL refs in
3126 * its tlist.
3127 */
3129
3130 /* Generate appropriate path */
3131 add_path(rel, create_ctescan_path(root, rel, pathkeys, required_outer));
3132}
3133
3134/*
3135 * set_namedtuplestore_pathlist
3136 * Build the (single) access path for a named tuplestore RTE
3137 *
3138 * There's no need for a separate set_namedtuplestore_size phase, since we
3139 * don't support join-qual-parameterized paths for tuplestores.
3140 */
3141static void
3144{
3146
3147 /* Mark rel with estimated output rows, width, etc */
3149
3150 /*
3151 * We don't support pushing join clauses into the quals of a tuplestore
3152 * scan, but it could still have required parameterization due to LATERAL
3153 * refs in its tlist.
3154 */
3156
3157 /* Generate appropriate path */
3159}
3160
3161/*
3162 * set_result_pathlist
3163 * Build the (single) access path for an RTE_RESULT RTE
3164 *
3165 * There's no need for a separate set_result_size phase, since we
3166 * don't support join-qual-parameterized paths for these RTEs.
3167 */
3168static void
3171{
3173
3174 /* Mark rel with estimated output rows, width, etc */
3176
3177 /*
3178 * We don't support pushing join clauses into the quals of a Result scan,
3179 * but it could still have required parameterization due to LATERAL refs
3180 * in its tlist.
3181 */
3183
3184 /* Generate appropriate path */
3186}
3187
3188/*
3189 * set_worktable_pathlist
3190 * Build the (single) access path for a self-reference CTE RTE
3191 *
3192 * There's no need for a separate set_worktable_size phase, since we don't
3193 * support join-qual-parameterized paths for CTEs.
3194 */
3195static void
3197{
3198 Path *ctepath;
3200 Index levelsup;
3202
3203 /*
3204 * We need to find the non-recursive term's path, which is in the plan
3205 * level that's processing the recursive UNION, which is one level *below*
3206 * where the CTE comes from.
3207 */
3208 levelsup = rte->ctelevelsup;
3209 if (levelsup == 0) /* shouldn't happen */
3210 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3211 levelsup--;
3212 cteroot = root;
3213 while (levelsup-- > 0)
3214 {
3215 cteroot = cteroot->parent_root;
3216 if (!cteroot) /* shouldn't happen */
3217 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3218 }
3219 ctepath = cteroot->non_recursive_path;
3220 if (!ctepath) /* shouldn't happen */
3221 elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
3222
3223 /* Mark rel with estimated output rows, width, etc */
3225
3226 /*
3227 * We don't support pushing join clauses into the quals of a worktable
3228 * scan, but it could still have required parameterization due to LATERAL
3229 * refs in its tlist. (I'm not sure this is actually possible given the
3230 * restrictions on recursive references, but it's easy enough to support.)
3231 */
3233
3234 /* Generate appropriate path */
3236}
3237
3238/*
3239 * generate_gather_paths
3240 * Generate parallel access paths for a relation by pushing a Gather or
3241 * Gather Merge on top of a partial path.
3242 *
3243 * This must not be called until after we're done creating all partial paths
3244 * for the specified relation. (Otherwise, add_partial_path might delete a
3245 * path that some GatherPath or GatherMergePath has a reference to.)
3246 *
3247 * If we're generating paths for a scan or join relation, override_rows will
3248 * be false, and we'll just use the relation's size estimate. When we're
3249 * being called for a partially-grouped or partially-distinct path, though, we
3250 * need to override the rowcount estimate. (It's not clear that the
3251 * particular value we're using here is actually best, but the underlying rel
3252 * has no estimate so we must do something.)
3253 */
3254void
3256{
3259 ListCell *lc;
3260 double rows;
3261 double *rowsp = NULL;
3262
3263 /* If there are no partial paths, there's nothing to do here. */
3264 if (rel->partial_pathlist == NIL)
3265 return;
3266
3267 /* Should we override the rel's rowcount estimate? */
3268 if (override_rows)
3269 rowsp = &rows;
3270
3271 /*
3272 * The output of Gather is always unsorted, so there's only one partial
3273 * path of interest: the cheapest one. That will be the one at the front
3274 * of partial_pathlist because of the way add_partial_path works.
3275 */
3280 NULL, rowsp);
3282
3283 /*
3284 * For each useful ordering, we can consider an order-preserving Gather
3285 * Merge.
3286 */
3287 foreach(lc, rel->partial_pathlist)
3288 {
3289 Path *subpath = (Path *) lfirst(lc);
3290 GatherMergePath *path;
3291
3292 if (subpath->pathkeys == NIL)
3293 continue;
3294
3297 subpath->pathkeys, NULL, rowsp);
3298 add_path(rel, &path->path);
3299 }
3300}
3301
3302/*
3303 * get_useful_pathkeys_for_relation
3304 * Determine which orderings of a relation might be useful.
3305 *
3306 * Getting data in sorted order can be useful either because the requested
3307 * order matches the final output ordering for the overall query we're
3308 * planning, or because it enables an efficient merge join. Here, we try
3309 * to figure out which pathkeys to consider.
3310 *
3311 * This allows us to do incremental sort on top of an index scan under a gather
3312 * merge node, i.e. parallelized.
3313 *
3314 * If the require_parallel_safe is true, we also require the expressions to
3315 * be parallel safe (which allows pushing the sort below Gather Merge).
3316 *
3317 * XXX At the moment this can only ever return a list with a single element,
3318 * because it looks at query_pathkeys only. So we might return the pathkeys
3319 * directly, but it seems plausible we'll want to consider other orderings
3320 * in the future. For example, we might want to consider pathkeys useful for
3321 * merge joins.
3322 */
3323static List *
3326{
3328
3329 /*
3330 * Considering query_pathkeys is always worth it, because it might allow
3331 * us to avoid a total sort when we have a partially presorted path
3332 * available or to push the total sort into the parallel portion of the
3333 * query.
3334 */
3335 if (root->query_pathkeys)
3336 {
3337 ListCell *lc;
3338 int npathkeys = 0; /* useful pathkeys */
3339
3340 foreach(lc, root->query_pathkeys)
3341 {
3343 EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3344
3345 /*
3346 * We can only build a sort for pathkeys that contain a
3347 * safe-to-compute-early EC member computable from the current
3348 * relation's reltarget, so ignore the remainder of the list as
3349 * soon as we find a pathkey without such a member.
3350 *
3351 * It's still worthwhile to return any prefix of the pathkeys list
3352 * that meets this requirement, as we may be able to do an
3353 * incremental sort.
3354 *
3355 * If requested, ensure the sort expression is parallel-safe too.
3356 */
3359 break;
3360
3361 npathkeys++;
3362 }
3363
3364 /*
3365 * The whole query_pathkeys list matches, so append it directly, to
3366 * allow comparing pathkeys easily by comparing list pointer. If we
3367 * have to truncate the pathkeys, we gotta do a copy though.
3368 */
3369 if (npathkeys == list_length(root->query_pathkeys))
3371 root->query_pathkeys);
3372 else if (npathkeys > 0)
3374 list_copy_head(root->query_pathkeys,
3375 npathkeys));
3376 }
3377
3378 return useful_pathkeys_list;
3379}
3380
3381/*
3382 * generate_useful_gather_paths
3383 * Generate parallel access paths for a relation by pushing a Gather or
3384 * Gather Merge on top of a partial path.
3385 *
3386 * Unlike plain generate_gather_paths, this looks both at pathkeys of input
3387 * paths (aiming to preserve the ordering), but also considers ordering that
3388 * might be useful for nodes above the gather merge node, and tries to add
3389 * a sort (regular or incremental) to provide that.
3390 */
3391void
3393{
3394 ListCell *lc;
3395 double rows;
3396 double *rowsp = NULL;
3399
3400 /* If there are no partial paths, there's nothing to do here. */
3401 if (rel->partial_pathlist == NIL)
3402 return;
3403
3404 /* Should we override the rel's rowcount estimate? */
3405 if (override_rows)
3406 rowsp = &rows;
3407
3408 /* generate the regular gather (merge) paths */
3410
3411 /* consider incremental sort for interesting orderings */
3413
3414 /* used for explicit (full) sort paths */
3416
3417 /*
3418 * Consider sorted paths for each interesting ordering. We generate both
3419 * incremental and full sort.
3420 */
3421 foreach(lc, useful_pathkeys_list)
3422 {
3424 ListCell *lc2;
3425 bool is_sorted;
3426 int presorted_keys;
3427
3428 foreach(lc2, rel->partial_pathlist)
3429 {
3430 Path *subpath = (Path *) lfirst(lc2);
3431 GatherMergePath *path;
3432
3434 subpath->pathkeys,
3435 &presorted_keys);
3436
3437 /*
3438 * We don't need to consider the case where a subpath is already
3439 * fully sorted because generate_gather_paths already creates a
3440 * gather merge path for every subpath that has pathkeys present.
3441 *
3442 * But since the subpath is already sorted, we know we don't need
3443 * to consider adding a sort (full or incremental) on top of it,
3444 * so we can continue here.
3445 */
3446 if (is_sorted)
3447 continue;
3448
3449 /*
3450 * Try at least sorting the cheapest path and also try
3451 * incrementally sorting any path which is partially sorted
3452 * already (no need to deal with paths which have presorted keys
3453 * when incremental sort is disabled unless it's the cheapest
3454 * input path).
3455 */
3457 (presorted_keys == 0 || !enable_incremental_sort))
3458 continue;
3459
3460 /*
3461 * Consider regular sort for any path that's not presorted or if
3462 * incremental sort is disabled. We've no need to consider both
3463 * sort and incremental sort on the same path. We assume that
3464 * incremental sort is always faster when there are presorted
3465 * keys.
3466 *
3467 * This is not redundant with the gather paths created in
3468 * generate_gather_paths, because that doesn't generate ordered
3469 * output. Here we add an explicit sort to match the useful
3470 * ordering.
3471 */
3472 if (presorted_keys == 0 || !enable_incremental_sort)
3473 {
3475 rel,
3476 subpath,
3478 -1.0);
3479 }
3480 else
3482 rel,
3483 subpath,
3485 presorted_keys,
3486 -1);
3488 path = create_gather_merge_path(root, rel,
3489 subpath,
3490 rel->reltarget,
3491 subpath->pathkeys,
3492 NULL,
3493 rowsp);
3494
3495 add_path(rel, &path->path);
3496 }
3497 }
3498}
3499
3500/*
3501 * generate_grouped_paths
3502 * Generate paths for a grouped relation by adding sorted and hashed
3503 * partial aggregation paths on top of paths of the ungrouped relation.
3504 *
3505 * The information needed is provided by the RelAggInfo structure stored in
3506 * "grouped_rel".
3507 */
3508void
3510 RelOptInfo *rel)
3511{
3512 RelAggInfo *agg_info = grouped_rel->agg_info;
3514 bool can_hash;
3515 bool can_sort;
3516 Path *cheapest_total_path = NULL;
3518 double dNumGroups = 0;
3519 double dNumPartialGroups = 0;
3520 List *group_pathkeys = NIL;
3521
3522 if (IS_DUMMY_REL(rel))
3523 {
3524 mark_dummy_rel(grouped_rel);
3525 return;
3526 }
3527
3528 /*
3529 * We push partial aggregation only to the lowest possible level in the
3530 * join tree that is deemed useful.
3531 */
3532 if (!bms_equal(agg_info->apply_agg_at, rel->relids) ||
3533 !agg_info->agg_useful)
3534 return;
3535
3536 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3538
3539 /*
3540 * Determine whether it's possible to perform sort-based implementations
3541 * of grouping, and generate the pathkeys that represent the grouping
3542 * requirements in that case.
3543 */
3545 if (can_sort)
3546 {
3549
3551 rel->top_parent->grouped_rel : grouped_rel;
3554
3555 group_pathkeys =
3558 }
3559
3560 /*
3561 * Determine whether we should consider hash-based implementations of
3562 * grouping.
3563 */
3564 Assert(root->numOrderedAggs == 0);
3565 can_hash = (agg_info->group_clauses != NIL &&
3567
3568 /*
3569 * Consider whether we should generate partially aggregated non-partial
3570 * paths. We can only do this if we have a non-partial path.
3571 */
3572 if (rel->pathlist != NIL)
3573 {
3574 cheapest_total_path = rel->cheapest_total_path;
3575 Assert(cheapest_total_path != NULL);
3576 }
3577
3578 /*
3579 * If parallelism is possible for grouped_rel, then we should consider
3580 * generating partially-grouped partial paths. However, if the ungrouped
3581 * rel has no partial paths, then we can't.
3582 */
3583 if (grouped_rel->consider_parallel && rel->partial_pathlist != NIL)
3584 {
3587 }
3588
3589 /* Estimate number of partial groups. */
3590 if (cheapest_total_path != NULL)
3592 agg_info->group_exprs,
3593 cheapest_total_path->rows,
3594 NULL, NULL);
3597 agg_info->group_exprs,
3599 NULL, NULL);
3600
3601 if (can_sort && cheapest_total_path != NULL)
3602 {
3603 ListCell *lc;
3604
3605 /*
3606 * Use any available suitably-sorted path as input, and also consider
3607 * sorting the cheapest-total path and incremental sort on any paths
3608 * with presorted keys.
3609 *
3610 * To save planning time, we ignore parameterized input paths unless
3611 * they are the cheapest-total path.
3612 */
3613 foreach(lc, rel->pathlist)
3614 {
3615 Path *input_path = (Path *) lfirst(lc);
3616 Path *path;
3617 bool is_sorted;
3618 int presorted_keys;
3619
3620 /*
3621 * Ignore parameterized paths that are not the cheapest-total
3622 * path.
3623 */
3624 if (input_path->param_info &&
3625 input_path != cheapest_total_path)
3626 continue;
3627
3628 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3629 input_path->pathkeys,
3630 &presorted_keys);
3631
3632 /*
3633 * Ignore paths that are not suitably or partially sorted, unless
3634 * they are the cheapest total path (no need to deal with paths
3635 * which have presorted keys when incremental sort is disabled).
3636 */
3637 if (!is_sorted && input_path != cheapest_total_path &&
3638 (presorted_keys == 0 || !enable_incremental_sort))
3639 continue;
3640
3641 /*
3642 * Since the path originates from a non-grouped relation that is
3643 * not aware of eager aggregation, we must ensure that it provides
3644 * the correct input for partial aggregation.
3645 */
3646 path = (Path *) create_projection_path(root,
3647 grouped_rel,
3648 input_path,
3649 agg_info->agg_input);
3650
3651 if (!is_sorted)
3652 {
3653 /*
3654 * We've no need to consider both a sort and incremental sort.
3655 * We'll just do a sort if there are no presorted keys and an
3656 * incremental sort when there are presorted keys.
3657 */
3658 if (presorted_keys == 0 || !enable_incremental_sort)
3659 path = (Path *) create_sort_path(root,
3660 grouped_rel,
3661 path,
3662 group_pathkeys,
3663 -1.0);
3664 else
3666 grouped_rel,
3667 path,
3668 group_pathkeys,
3669 presorted_keys,
3670 -1.0);
3671 }
3672
3673 /*
3674 * qual is NIL because the HAVING clause cannot be evaluated until
3675 * the final value of the aggregate is known.
3676 */
3677 path = (Path *) create_agg_path(root,
3678 grouped_rel,
3679 path,
3680 agg_info->target,
3681 AGG_SORTED,
3683 agg_info->group_clauses,
3684 NIL,
3685 &agg_costs,
3686 dNumGroups);
3687
3688 add_path(grouped_rel, path);
3689 }
3690 }
3691
3693 {
3694 ListCell *lc;
3695
3696 /* Similar to above logic, but for partial paths. */
3697 foreach(lc, rel->partial_pathlist)
3698 {
3699 Path *input_path = (Path *) lfirst(lc);
3700 Path *path;
3701 bool is_sorted;
3702 int presorted_keys;
3703
3704 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3705 input_path->pathkeys,
3706 &presorted_keys);
3707
3708 /*
3709 * Ignore paths that are not suitably or partially sorted, unless
3710 * they are the cheapest partial path (no need to deal with paths
3711 * which have presorted keys when incremental sort is disabled).
3712 */
3714 (presorted_keys == 0 || !enable_incremental_sort))
3715 continue;
3716
3717 /*
3718 * Since the path originates from a non-grouped relation that is
3719 * not aware of eager aggregation, we must ensure that it provides
3720 * the correct input for partial aggregation.
3721 */
3722 path = (Path *) create_projection_path(root,
3723 grouped_rel,
3724 input_path,
3725 agg_info->agg_input);
3726
3727 if (!is_sorted)
3728 {
3729 /*
3730 * We've no need to consider both a sort and incremental sort.
3731 * We'll just do a sort if there are no presorted keys and an
3732 * incremental sort when there are presorted keys.
3733 */
3734 if (presorted_keys == 0 || !enable_incremental_sort)
3735 path = (Path *) create_sort_path(root,
3736 grouped_rel,
3737 path,
3738 group_pathkeys,
3739 -1.0);
3740 else
3742 grouped_rel,
3743 path,
3744 group_pathkeys,
3745 presorted_keys,
3746 -1.0);
3747 }
3748
3749 /*
3750 * qual is NIL because the HAVING clause cannot be evaluated until
3751 * the final value of the aggregate is known.
3752 */
3753 path = (Path *) create_agg_path(root,
3754 grouped_rel,
3755 path,
3756 agg_info->target,
3757 AGG_SORTED,
3759 agg_info->group_clauses,
3760 NIL,
3761 &agg_costs,
3763
3764 add_partial_path(grouped_rel, path);
3765 }
3766 }
3767
3768 /*
3769 * Add a partially-grouped HashAgg Path where possible
3770 */
3771 if (can_hash && cheapest_total_path != NULL)
3772 {
3773 Path *path;
3774
3775 /*
3776 * Since the path originates from a non-grouped relation that is not
3777 * aware of eager aggregation, we must ensure that it provides the
3778 * correct input for partial aggregation.
3779 */
3780 path = (Path *) create_projection_path(root,
3781 grouped_rel,
3782 cheapest_total_path,
3783 agg_info->agg_input);
3784
3785 /*
3786 * qual is NIL because the HAVING clause cannot be evaluated until the
3787 * final value of the aggregate is known.
3788 */
3789 path = (Path *) create_agg_path(root,
3790 grouped_rel,
3791 path,
3792 agg_info->target,
3793 AGG_HASHED,
3795 agg_info->group_clauses,
3796 NIL,
3797 &agg_costs,
3798 dNumGroups);
3799
3800 add_path(grouped_rel, path);
3801 }
3802
3803 /*
3804 * Now add a partially-grouped HashAgg partial Path where possible
3805 */
3807 {
3808 Path *path;
3809
3810 /*
3811 * Since the path originates from a non-grouped relation that is not
3812 * aware of eager aggregation, we must ensure that it provides the
3813 * correct input for partial aggregation.
3814 */
3815 path = (Path *) create_projection_path(root,
3816 grouped_rel,
3818 agg_info->agg_input);
3819
3820 /*
3821 * qual is NIL because the HAVING clause cannot be evaluated until the
3822 * final value of the aggregate is known.
3823 */
3824 path = (Path *) create_agg_path(root,
3825 grouped_rel,
3826 path,
3827 agg_info->target,
3828 AGG_HASHED,
3830 agg_info->group_clauses,
3831 NIL,
3832 &agg_costs,
3834
3835 add_partial_path(grouped_rel, path);
3836 }
3837}
3838
3839/*
3840 * make_rel_from_joinlist
3841 * Build access paths using a "joinlist" to guide the join path search.
3842 *
3843 * See comments for deconstruct_jointree() for definition of the joinlist
3844 * data structure.
3845 */
3846static RelOptInfo *
3848{
3849 int levels_needed;
3850 List *initial_rels;
3851 ListCell *jl;
3852
3853 /*
3854 * Count the number of child joinlist nodes. This is the depth of the
3855 * dynamic-programming algorithm we must employ to consider all ways of
3856 * joining the child nodes.
3857 */
3859
3860 if (levels_needed <= 0)
3861 return NULL; /* nothing to do? */
3862
3863 /*
3864 * Construct a list of rels corresponding to the child joinlist nodes.
3865 * This may contain both base rels and rels constructed according to
3866 * sub-joinlists.
3867 */
3868 initial_rels = NIL;
3869 foreach(jl, joinlist)
3870 {
3871 Node *jlnode = (Node *) lfirst(jl);
3873
3874 if (IsA(jlnode, RangeTblRef))
3875 {
3876 int varno = ((RangeTblRef *) jlnode)->rtindex;
3877
3878 thisrel = find_base_rel(root, varno);
3879 }
3880 else if (IsA(jlnode, List))
3881 {
3882 /* Recurse to handle subproblem */
3884 }
3885 else
3886 {
3887 elog(ERROR, "unrecognized joinlist node type: %d",
3888 (int) nodeTag(jlnode));
3889 thisrel = NULL; /* keep compiler quiet */
3890 }
3891
3892 initial_rels = lappend(initial_rels, thisrel);
3893 }
3894
3895 if (levels_needed == 1)
3896 {
3897 /*
3898 * Single joinlist node, so we're done.
3899 */
3900 return (RelOptInfo *) linitial(initial_rels);
3901 }
3902 else
3903 {
3904 /*
3905 * Consider the different orders in which we could join the rels,
3906 * using a plugin, GEQO, or the regular join search code.
3907 *
3908 * We put the initial_rels list into a PlannerInfo field because
3909 * has_legal_joinclause() needs to look at it (ugly :-().
3910 */
3911 root->initial_rels = initial_rels;
3912
3913 if (join_search_hook)
3914 return (*join_search_hook) (root, levels_needed, initial_rels);
3916 return geqo(root, levels_needed, initial_rels);
3917 else
3918 return standard_join_search(root, levels_needed, initial_rels);
3919 }
3920}
3921
3922/*
3923 * standard_join_search
3924 * Find possible joinpaths for a query by successively finding ways
3925 * to join component relations into join relations.
3926 *
3927 * 'levels_needed' is the number of iterations needed, ie, the number of
3928 * independent jointree items in the query. This is > 1.
3929 *
3930 * 'initial_rels' is a list of RelOptInfo nodes for each independent
3931 * jointree item. These are the components to be joined together.
3932 * Note that levels_needed == list_length(initial_rels).
3933 *
3934 * Returns the final level of join relations, i.e., the relation that is
3935 * the result of joining all the original relations together.
3936 * At least one implementation path must be provided for this relation and
3937 * all required sub-relations.
3938 *
3939 * To support loadable plugins that modify planner behavior by changing the
3940 * join searching algorithm, we provide a hook variable that lets a plugin
3941 * replace or supplement this function. Any such hook must return the same
3942 * final join relation as the standard code would, but it might have a
3943 * different set of implementation paths attached, and only the sub-joinrels
3944 * needed for these paths need have been instantiated.
3945 *
3946 * Note to plugin authors: the functions invoked during standard_join_search()
3947 * modify root->join_rel_list and root->join_rel_hash. If you want to do more
3948 * than one join-order search, you'll probably need to save and restore the
3949 * original states of those data structures. See geqo_eval() for an example.
3950 */
3951RelOptInfo *
3953{
3954 int lev;
3955 RelOptInfo *rel;
3956
3957 /*
3958 * This function cannot be invoked recursively within any one planning
3959 * problem, so join_rel_level[] can't be in use already.
3960 */
3961 Assert(root->join_rel_level == NULL);
3962
3963 /*
3964 * We employ a simple "dynamic programming" algorithm: we first find all
3965 * ways to build joins of two jointree items, then all ways to build joins
3966 * of three items (from two-item joins and single items), then four-item
3967 * joins, and so on until we have considered all ways to join all the
3968 * items into one rel.
3969 *
3970 * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3971 * set root->join_rel_level[1] to represent all the single-jointree-item
3972 * relations.
3973 */
3974 root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3975
3976 root->join_rel_level[1] = initial_rels;
3977
3978 for (lev = 2; lev <= levels_needed; lev++)
3979 {
3980 ListCell *lc;
3981
3982 /*
3983 * Determine all possible pairs of relations to be joined at this
3984 * level, and build paths for making each one from every available
3985 * pair of lower-level relations.
3986 */
3988
3989 /*
3990 * Run generate_partitionwise_join_paths() and
3991 * generate_useful_gather_paths() for each just-processed joinrel. We
3992 * could not do this earlier because both regular and partial paths
3993 * can get added to a particular joinrel at multiple times within
3994 * join_search_one_level.
3995 *
3996 * After that, we're done creating paths for the joinrel, so run
3997 * set_cheapest().
3998 *
3999 * In addition, we also run generate_grouped_paths() for the grouped
4000 * relation of each just-processed joinrel, and run set_cheapest() for
4001 * the grouped relation afterwards.
4002 */
4003 foreach(lc, root->join_rel_level[lev])
4004 {
4005 bool is_top_rel;
4006
4007 rel = (RelOptInfo *) lfirst(lc);
4008
4009 is_top_rel = bms_equal(rel->relids, root->all_query_rels);
4010
4011 /* Create paths for partitionwise joins. */
4013
4014 /*
4015 * Except for the topmost scan/join rel, consider gathering
4016 * partial paths. We'll do the same for the topmost scan/join rel
4017 * once we know the final targetlist (see grouping_planner's and
4018 * its call to apply_scanjoin_target_to_paths).
4019 */
4020 if (!is_top_rel)
4022
4023 /* Find and save the cheapest paths for this rel */
4024 set_cheapest(rel);
4025
4026 /*
4027 * Except for the topmost scan/join rel, consider generating
4028 * partial aggregation paths for the grouped relation on top of
4029 * the paths of this rel. After that, we're done creating paths
4030 * for the grouped relation, so run set_cheapest().
4031 */
4032 if (rel->grouped_rel != NULL && !is_top_rel)
4033 {
4034 RelOptInfo *grouped_rel = rel->grouped_rel;
4035
4036 Assert(IS_GROUPED_REL(grouped_rel));
4037
4038 generate_grouped_paths(root, grouped_rel, rel);
4039 set_cheapest(grouped_rel);
4040 }
4041
4042#ifdef OPTIMIZER_DEBUG
4043 pprint(rel);
4044#endif
4045 }
4046 }
4047
4048 /*
4049 * We should have a single rel at the final level.
4050 */
4051 if (root->join_rel_level[levels_needed] == NIL)
4052 elog(ERROR, "failed to build any %d-way joins", levels_needed);
4053 Assert(list_length(root->join_rel_level[levels_needed]) == 1);
4054
4055 rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
4056
4057 root->join_rel_level = NULL;
4058
4059 return rel;
4060}
4061
4062/*****************************************************************************
4063 * PUSHING QUALS DOWN INTO SUBQUERIES
4064 *****************************************************************************/
4065
4066/*
4067 * subquery_is_pushdown_safe - is a subquery safe for pushing down quals?
4068 *
4069 * subquery is the particular component query being checked. topquery
4070 * is the top component of a set-operations tree (the same Query if no
4071 * set-op is involved).
4072 *
4073 * Conditions checked here:
4074 *
4075 * 1. If the subquery has a LIMIT clause, we must not push down any quals,
4076 * since that could change the set of rows returned.
4077 *
4078 * 2. If the subquery contains EXCEPT or EXCEPT ALL set ops we cannot push
4079 * quals into it, because that could change the results.
4080 *
4081 * 3. If the subquery uses DISTINCT, we cannot push volatile quals into it.
4082 * This is because upper-level quals should semantically be evaluated only
4083 * once per distinct row, not once per original row, and if the qual is
4084 * volatile then extra evaluations could change the results. (This issue
4085 * does not apply to other forms of aggregation such as GROUP BY, because
4086 * when those are present we push into HAVING not WHERE, so that the quals
4087 * are still applied after aggregation.)
4088 *
4089 * 4. If the subquery contains window functions, we cannot push volatile quals
4090 * into it. The issue here is a bit different from DISTINCT: a volatile qual
4091 * might succeed for some rows of a window partition and fail for others,
4092 * thereby changing the partition contents and thus the window functions'
4093 * results for rows that remain.
4094 *
4095 * 5. If the subquery contains any set-returning functions in its targetlist,
4096 * we cannot push volatile quals into it. That would push them below the SRFs
4097 * and thereby change the number of times they are evaluated. Also, a
4098 * volatile qual could succeed for some SRF output rows and fail for others,
4099 * a behavior that cannot occur if it's evaluated before SRF expansion.
4100 *
4101 * 6. If the subquery has nonempty grouping sets, we cannot push down any
4102 * quals. The concern here is that a qual referencing a "constant" grouping
4103 * column could get constant-folded, which would be improper because the value
4104 * is potentially nullable by grouping-set expansion. This restriction could
4105 * be removed if we had a parsetree representation that shows that such
4106 * grouping columns are not really constant. (There are other ideas that
4107 * could be used to relax this restriction, but that's the approach most
4108 * likely to get taken in the future. Note that there's not much to be gained
4109 * so long as subquery_planner can't move HAVING clauses to WHERE within such
4110 * a subquery.)
4111 *
4112 * In addition, we make several checks on the subquery's output columns to see
4113 * if it is safe to reference them in pushed-down quals. If output column k
4114 * is found to be unsafe to reference, we set the reason for that inside
4115 * safetyInfo->unsafeFlags[k], but we don't reject the subquery overall since
4116 * column k might not be referenced by some/all quals. The unsafeFlags[]
4117 * array will be consulted later by qual_is_pushdown_safe(). It's better to
4118 * do it this way than to make the checks directly in qual_is_pushdown_safe(),
4119 * because when the subquery involves set operations we have to check the
4120 * output expressions in each arm of the set op.
4121 *
4122 * Note: pushing quals into a DISTINCT subquery is theoretically dubious:
4123 * we're effectively assuming that the quals cannot distinguish values that
4124 * the DISTINCT's equality operator sees as equal, yet there are many
4125 * counterexamples to that assumption. However use of such a qual with a
4126 * DISTINCT subquery would be unsafe anyway, since there's no guarantee which
4127 * "equal" value will be chosen as the output value by the DISTINCT operation.
4128 * So we don't worry too much about that. Another objection is that if the
4129 * qual is expensive to evaluate, running it for each original row might cost
4130 * more than we save by eliminating rows before the DISTINCT step. But it
4131 * would be very hard to estimate that at this stage, and in practice pushdown
4132 * seldom seems to make things worse, so we ignore that problem too.
4133 *
4134 * Note: likewise, pushing quals into a subquery with window functions is a
4135 * bit dubious: the quals might remove some rows of a window partition while
4136 * leaving others, causing changes in the window functions' results for the
4137 * surviving rows. We insist that such a qual reference only partitioning
4138 * columns, but again that only protects us if the qual does not distinguish
4139 * values that the partitioning equality operator sees as equal. The risks
4140 * here are perhaps larger than for DISTINCT, since no de-duplication of rows
4141 * occurs and thus there is no theoretical problem with such a qual. But
4142 * we'll do this anyway because the potential performance benefits are very
4143 * large, and we've seen no field complaints about the longstanding comparable
4144 * behavior with DISTINCT.
4145 */
4146static bool
4149{
4151
4152 /* Check point 1 */
4153 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
4154 return false;
4155
4156 /* Check point 6 */
4157 if (subquery->groupClause && subquery->groupingSets)
4158 return false;
4159
4160 /* Check points 3, 4, and 5 */
4161 if (subquery->distinctClause ||
4162 subquery->hasWindowFuncs ||
4163 subquery->hasTargetSRFs)
4164 safetyInfo->unsafeVolatile = true;
4165
4166 /*
4167 * If we're at a leaf query, check for unsafe expressions in its target
4168 * list, and mark any reasons why they're unsafe in unsafeFlags[].
4169 * (Non-leaf nodes in setop trees have only simple Vars in their tlists,
4170 * so no need to check them.)
4171 */
4172 if (subquery->setOperations == NULL)
4174
4175 /* Are we at top level, or looking at a setop component? */
4176 if (subquery == topquery)
4177 {
4178 /* Top level, so check any component queries */
4179 if (subquery->setOperations != NULL)
4181 safetyInfo))
4182 return false;
4183 }
4184 else
4185 {
4186 /* Setop component must not have more components (too weird) */
4187 if (subquery->setOperations != NULL)
4188 return false;
4189 /* Check whether setop component output types match top level */
4190 topop = castNode(SetOperationStmt, topquery->setOperations);
4191 Assert(topop);
4193 topop->colTypes,
4194 safetyInfo);
4195 }
4196 return true;
4197}
4198
4199/*
4200 * Helper routine to recurse through setOperations tree
4201 */
4202static bool
4205{
4206 if (IsA(setOp, RangeTblRef))
4207 {
4209 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
4210 Query *subquery = rte->subquery;
4211
4212 Assert(subquery != NULL);
4214 }
4215 else if (IsA(setOp, SetOperationStmt))
4216 {
4218
4219 /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
4220 if (op->op == SETOP_EXCEPT)
4221 return false;
4222 /* Else recurse */
4224 return false;
4226 return false;
4227 }
4228 else
4229 {
4230 elog(ERROR, "unrecognized node type: %d",
4231 (int) nodeTag(setOp));
4232 }
4233 return true;
4234}
4235
4236/*
4237 * check_output_expressions - check subquery's output expressions for safety
4238 *
4239 * There are several cases in which it's unsafe to push down an upper-level
4240 * qual if it references a particular output column of a subquery. We check
4241 * each output column of the subquery and set flags in unsafeFlags[k] when we
4242 * see that column is unsafe for a pushed-down qual to reference. The
4243 * conditions checked here are:
4244 *
4245 * 1. We must not push down any quals that refer to subselect outputs that
4246 * return sets, else we'd introduce functions-returning-sets into the
4247 * subquery's WHERE/HAVING quals.
4248 *
4249 * 2. We must not push down any quals that refer to subselect outputs that
4250 * contain volatile functions, for fear of introducing strange results due
4251 * to multiple evaluation of a volatile function.
4252 *
4253 * 3. If the subquery uses DISTINCT ON, we must not push down any quals that
4254 * refer to non-DISTINCT output columns, because that could change the set
4255 * of rows returned. (This condition is vacuous for DISTINCT, because then
4256 * there are no non-DISTINCT output columns, so we needn't check. Note that
4257 * subquery_is_pushdown_safe already reported that we can't use volatile
4258 * quals if there's DISTINCT or DISTINCT ON.)
4259 *
4260 * 4. If the subquery has any window functions, we must not push down quals
4261 * that reference any output columns that are not listed in all the subquery's
4262 * window PARTITION BY clauses. We can push down quals that use only
4263 * partitioning columns because they should succeed or fail identically for
4264 * every row of any one window partition, and totally excluding some
4265 * partitions will not change a window function's results for remaining
4266 * partitions. (Again, this also requires nonvolatile quals, but
4267 * subquery_is_pushdown_safe handles that.). Subquery columns marked as
4268 * unsafe for this reason can still have WindowClause run conditions pushed
4269 * down.
4270 */
4271static void
4273{
4275 ListCell *lc;
4276
4277 /*
4278 * We must be careful with grouping Vars and join alias Vars in the
4279 * subquery's outputs, as they hide the underlying expressions.
4280 *
4281 * We need to expand grouping Vars to their underlying expressions (the
4282 * grouping clauses) because the grouping expressions themselves might be
4283 * volatile or set-returning. However, we do not need to expand join
4284 * alias Vars, as their underlying structure does not introduce volatile
4285 * or set-returning functions at the current level.
4286 *
4287 * In neither case do we need to recursively examine the Vars contained in
4288 * these underlying expressions. Even if they reference outputs from
4289 * lower-level subqueries (at any depth), those references are guaranteed
4290 * not to expand to volatile or set-returning functions, because
4291 * subqueries containing such functions in their targetlists are never
4292 * pulled up.
4293 */
4294 if (subquery->hasGroupRTE)
4295 {
4296 /*
4297 * We can safely pass NULL for the root here. This function uses the
4298 * expanded expressions solely to check for volatile or set-returning
4299 * functions, which is independent of the Vars' nullingrels.
4300 */
4302 flatten_group_exprs(NULL, subquery, (Node *) subquery->targetList);
4303 }
4304
4305 foreach(lc, flattened_targetList)
4306 {
4308
4309 if (tle->resjunk)
4310 continue; /* ignore resjunk columns */
4311
4312 /* Functions returning sets are unsafe (point 1) */
4313 if (subquery->hasTargetSRFs &&
4314 (safetyInfo->unsafeFlags[tle->resno] &
4315 UNSAFE_HAS_SET_FUNC) == 0 &&
4316 expression_returns_set((Node *) tle->expr))
4317 {
4318 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_SET_FUNC;
4319 continue;
4320 }
4321
4322 /* Volatile functions are unsafe (point 2) */
4323 if ((safetyInfo->unsafeFlags[tle->resno] &
4326 {
4327 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_VOLATILE_FUNC;
4328 continue;
4329 }
4330
4331 /* If subquery uses DISTINCT ON, check point 3 */
4332 if (subquery->hasDistinctOn &&
4333 (safetyInfo->unsafeFlags[tle->resno] &
4336 {
4337 /* non-DISTINCT column, so mark it unsafe */
4338 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_DISTINCTON_CLAUSE;
4339 continue;
4340 }
4341
4342 /* If subquery uses window functions, check point 4 */
4343 if (subquery->hasWindowFuncs &&
4344 (safetyInfo->unsafeFlags[tle->resno] &
4346 !targetIsInAllPartitionLists(tle, subquery))
4347 {
4348 /* not present in all PARTITION BY clauses, so mark it unsafe */
4349 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_PARTITIONBY_CLAUSE;
4350 continue;
4351 }
4352 }
4353}
4354
4355/*
4356 * For subqueries using UNION/UNION ALL/INTERSECT/INTERSECT ALL, we can
4357 * push quals into each component query, but the quals can only reference
4358 * subquery columns that suffer no type coercions in the set operation.
4359 * Otherwise there are possible semantic gotchas. So, we check the
4360 * component queries to see if any of them have output types different from
4361 * the top-level setop outputs. We set the UNSAFE_TYPE_MISMATCH bit in
4362 * unsafeFlags[k] if column k has different type in any component.
4363 *
4364 * We don't have to care about typmods here: the only allowed difference
4365 * between set-op input and output typmods is input is a specific typmod
4366 * and output is -1, and that does not require a coercion.
4367 *
4368 * tlist is a subquery tlist.
4369 * colTypes is an OID list of the top-level setop's output column types.
4370 * safetyInfo is the pushdown_safety_info to set unsafeFlags[] for.
4371 */
4372static void
4375{
4376 ListCell *l;
4378
4379 foreach(l, tlist)
4380 {
4382
4383 if (tle->resjunk)
4384 continue; /* ignore resjunk columns */
4385 if (colType == NULL)
4386 elog(ERROR, "wrong number of tlist entries");
4387 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
4388 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_TYPE_MISMATCH;
4390 }
4391 if (colType != NULL)
4392 elog(ERROR, "wrong number of tlist entries");
4393}
4394
4395/*
4396 * targetIsInAllPartitionLists
4397 * True if the TargetEntry is listed in the PARTITION BY clause
4398 * of every window defined in the query.
4399 *
4400 * It would be safe to ignore windows not actually used by any window
4401 * function, but it's not easy to get that info at this stage; and it's
4402 * unlikely to be useful to spend any extra cycles getting it, since
4403 * unreferenced window definitions are probably infrequent in practice.
4404 */
4405static bool
4407{
4408 ListCell *lc;
4409
4410 foreach(lc, query->windowClause)
4411 {
4413
4415 return false;
4416 }
4417 return true;
4418}
4419
4420/*
4421 * qual_is_pushdown_safe - is a particular rinfo safe to push down?
4422 *
4423 * rinfo is a restriction clause applying to the given subquery (whose RTE
4424 * has index rti in the parent query).
4425 *
4426 * Conditions checked here:
4427 *
4428 * 1. rinfo's clause must not contain any SubPlans (mainly because it's
4429 * unclear that it will work correctly: SubLinks will already have been
4430 * transformed into SubPlans in the qual, but not in the subquery). Note that
4431 * SubLinks that transform to initplans are safe, and will be accepted here
4432 * because what we'll see in the qual is just a Param referencing the initplan
4433 * output.
4434 *
4435 * 2. If unsafeVolatile is set, rinfo's clause must not contain any volatile
4436 * functions.
4437 *
4438 * 3. If unsafeLeaky is set, rinfo's clause must not contain any leaky
4439 * functions that are passed Var nodes, and therefore might reveal values from
4440 * the subquery as side effects.
4441 *
4442 * 4. rinfo's clause must not refer to the whole-row output of the subquery
4443 * (since there is no easy way to name that within the subquery itself).
4444 *
4445 * 5. rinfo's clause must not refer to any subquery output columns that were
4446 * found to be unsafe to reference by subquery_is_pushdown_safe().
4447 *
4448 * 6. If the subquery has a grouping layer (DISTINCT, DISTINCT ON, window
4449 * PARTITION BY, or a set operation that groups rows by equality), rinfo's
4450 * clause must not apply a different equivalence relation to a grouping column
4451 * than the grouping uses; otherwise it would distinguish rows the grouping
4452 * considers equal, and pushing such a clause past the grouping would drop
4453 * members of a group and change which row becomes the group's representative
4454 * (or, for window functions, change per-partition values such as ranks and
4455 * counts). See expression_has_grouping_conflict for the kinds of conflict
4456 * detected.
4457 */
4458static pushdown_safe_type
4461{
4463 Node *qual = (Node *) rinfo->clause;
4464 List *vars;
4465 ListCell *vl;
4466
4467 /* Refuse subselects (point 1) */
4468 if (contain_subplans(qual))
4469 return PUSHDOWN_UNSAFE;
4470
4471 /* Refuse volatile quals if we found they'd be unsafe (point 2) */
4472 if (safetyInfo->unsafeVolatile &&
4474 return PUSHDOWN_UNSAFE;
4475
4476 /* Refuse leaky quals if told to (point 3) */
4477 if (safetyInfo->unsafeLeaky &&
4478 contain_leaked_vars(qual))
4479 return PUSHDOWN_UNSAFE;
4480
4481 /*
4482 * Examine all Vars used in clause. Since it's a restriction clause, all
4483 * such Vars must refer to subselect output columns ... unless this is
4484 * part of a LATERAL subquery, in which case there could be lateral
4485 * references.
4486 *
4487 * By omitting the relevant flags, this also gives us a cheap sanity check
4488 * that no aggregates or window functions appear in the qual. Those would
4489 * be unsafe to push down, but at least for the moment we could never see
4490 * any in a qual anyhow.
4491 */
4493 foreach(vl, vars)
4494 {
4495 Var *var = (Var *) lfirst(vl);
4496
4497 /*
4498 * XXX Punt if we find any PlaceHolderVars in the restriction clause.
4499 * It's not clear whether a PHV could safely be pushed down, and even
4500 * less clear whether such a situation could arise in any cases of
4501 * practical interest anyway. So for the moment, just refuse to push
4502 * down.
4503 */
4504 if (!IsA(var, Var))
4505 {
4507 break;
4508 }
4509
4510 /*
4511 * Punt if we find any lateral references. It would be safe to push
4512 * these down, but we'd have to convert them into outer references,
4513 * which subquery_push_qual lacks the infrastructure to do. The case
4514 * arises so seldom that it doesn't seem worth working hard on.
4515 */
4516 if (var->varno != rti)
4517 {
4519 break;
4520 }
4521
4522 /* Subqueries have no system columns */
4523 Assert(var->varattno >= 0);
4524
4525 /* Check point 4 */
4526 if (var->varattno == 0)
4527 {
4529 break;
4530 }
4531
4532 /* Check point 5 */
4533 if (safetyInfo->unsafeFlags[var->varattno] != 0)
4534 {
4535 if (safetyInfo->unsafeFlags[var->varattno] &
4538 {
4540 break;
4541 }
4542 else
4543 {
4544 /* UNSAFE_NOTIN_PARTITIONBY_CLAUSE is ok for run conditions */
4546 /* don't break, we might find another Var that's unsafe */
4547 }
4548 }
4549 }
4550
4551 list_free(vars);
4552
4553 /* Check point 6 */
4554 if (safe == PUSHDOWN_SAFE &&
4555 (subquery->hasWindowFuncs ||
4556 subquery->distinctClause != NIL ||
4557 (subquery->setOperations != NULL &&
4558 setop_has_grouping(subquery->setOperations))))
4559 {
4561 subquery))
4563 }
4564
4565 return safe;
4566}
4567
4568/*
4569 * pushdown_var_grouping_eqop
4570 * grouping_eqop_callback for qual_is_pushdown_safe.
4571 *
4572 * Returns the grouping equality operator for 'var' if it references a subquery
4573 * output column that participates in the subquery's grouping layer; InvalidOid
4574 * otherwise.
4575 *
4576 * 'context' is the subquery Query whose pushdown safety we're checking.
4577 */
4578static Oid
4580{
4581 Query *subquery = (Query *) context;
4582 Oid eqop;
4583
4584 if (var->varlevelsup != 0)
4585 return InvalidOid;
4586
4587 eqop = subquery_column_grouping_eqop(subquery, var->varattno);
4588
4589 /*
4590 * qual_is_pushdown_safe ensures any level-0 subquery Var that reaches us
4591 * references a grouping column.
4592 */
4593 Assert(OidIsValid(eqop));
4594
4595 return eqop;
4596}
4597
4598/*
4599 * subquery_column_grouping_eqop
4600 * Return the equality operator that the subquery uses to group rows on
4601 * the given output column, or InvalidOid if the column doesn't
4602 * participate in any grouping mechanism.
4603 *
4604 * A subquery output column is grouping-relevant if it appears in
4605 * subquery->distinctClause (covering both DISTINCT and DISTINCT ON), in every
4606 * window's PARTITION BY clause, or is grouped by some node in a set-operation
4607 * tree. In all of these cases the parser builds the SortGroupClause with the
4608 * column's type-default equality operator via get_sort_group_operators, so any
4609 * matching SortGroupClause carries the correct eqop.
4610 */
4611static Oid
4613{
4615 ListCell *lc;
4616
4618 return InvalidOid;
4619
4620 tle = list_nth_node(TargetEntry, subquery->targetList, attno - 1);
4621
4622 /* DISTINCT or DISTINCT ON */
4623 foreach(lc, subquery->distinctClause)
4624 {
4626
4627 if (sgc->tleSortGroupRef == tle->ressortgroupref)
4628 return sgc->eqop;
4629 }
4630
4631 /* Window function PARTITION BY: must appear in every window's list. */
4632 if (subquery->hasWindowFuncs && subquery->windowClause != NIL)
4633 {
4634 Oid eqop = InvalidOid;
4635
4636 foreach(lc, subquery->windowClause)
4637 {
4639 ListCell *lc2;
4640
4641 foreach(lc2, wc->partitionClause)
4642 {
4644
4645 if (sgc->tleSortGroupRef == tle->ressortgroupref)
4646 break;
4647 }
4648 if (lc2 == NULL)
4649 break; /* not present in this window's list */
4650 eqop = lfirst_node(SortGroupClause, lc2)->eqop;
4651 }
4652 if (lc == NULL)
4653 return eqop; /* matched in every window */
4654 }
4655
4656 /* Set operation */
4657 if (subquery->setOperations != NULL)
4658 return setop_column_grouping_eqop(subquery->setOperations, attno);
4659
4660 return InvalidOid;
4661}
4662
4663/*
4664 * setop_column_grouping_eqop
4665 * Recursively search a SetOperationStmt tree for any node that groups
4666 * rows by equality, and return the equality operator used for the given
4667 * output column. Returns InvalidOid if no node in the tree groups (i.e.,
4668 * an entirely-UNION-ALL tree).
4669 *
4670 * For any set operation other than UNION ALL, groupClauses is a positional
4671 * list of SortGroupClauses, with element N-1 corresponding to output column N
4672 * (see makeSortGroupClauseForSetOp).
4673 */
4674static Oid
4676{
4677 SetOperationStmt *op;
4678 Oid eqop;
4679
4680 if (setop == NULL || !IsA(setop, SetOperationStmt))
4681 return InvalidOid;
4682
4683 op = (SetOperationStmt *) setop;
4684
4685 if (op->groupClauses != NIL &&
4686 attno >= 1 && attno <= list_length(op->groupClauses))
4687 {
4689 op->groupClauses, attno - 1);
4690
4691 return sgc->eqop;
4692 }
4693
4694 /* Recurse into children to find any inner grouping */
4695 eqop = setop_column_grouping_eqop(op->larg, attno);
4696 if (OidIsValid(eqop))
4697 return eqop;
4698 return setop_column_grouping_eqop(op->rarg, attno);
4699}
4700
4701/*
4702 * setop_has_grouping
4703 * Return true if any node in the SetOperationStmt tree groups rows by
4704 * equality (i.e., has non-NIL groupClauses).
4705 */
4706static bool
4708{
4709 SetOperationStmt *op;
4710
4711 if (setop == NULL || !IsA(setop, SetOperationStmt))
4712 return false;
4713
4714 op = (SetOperationStmt *) setop;
4715 if (op->groupClauses != NIL)
4716 return true;
4717
4718 return setop_has_grouping(op->larg) || setop_has_grouping(op->rarg);
4719}
4720
4721/*
4722 * subquery_push_qual - push down a qual that we have determined is safe
4723 */
4724static void
4726{
4727 if (subquery->setOperations != NULL)
4728 {
4729 /* Recurse to push it separately to each component query */
4730 recurse_push_qual(subquery->setOperations, subquery,
4731 rte, rti, qual);
4732 }
4733 else
4734 {
4735 /*
4736 * We need to replace Vars in the qual (which must refer to outputs of
4737 * the subquery) with copies of the subquery's targetlist expressions.
4738 * Note that at this point, any uplevel Vars in the qual should have
4739 * been replaced with Params, so they need no work.
4740 *
4741 * This step also ensures that when we are pushing into a setop tree,
4742 * each component query gets its own copy of the qual.
4743 */
4744 qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
4745 subquery->targetList,
4746 subquery->resultRelation,
4748 &subquery->hasSubLinks);
4749
4750 /*
4751 * Now attach the qual to the proper place: normally WHERE, but if the
4752 * subquery uses grouping or aggregation, put it in HAVING (since the
4753 * qual really refers to the group-result rows).
4754 */
4755 if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
4756 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
4757 else
4758 subquery->jointree->quals =
4759 make_and_qual(subquery->jointree->quals, qual);
4760
4761 /*
4762 * We need not change the subquery's hasAggs or hasSubLinks flags,
4763 * since we can't be pushing down any aggregates that weren't there
4764 * before, and we don't push down subselects at all.
4765 */
4766 }
4767}
4768
4769/*
4770 * Helper routine to recurse through setOperations tree
4771 */
4772static void
4774 RangeTblEntry *rte, Index rti, Node *qual)
4775{
4776 if (IsA(setOp, RangeTblRef))
4777 {
4779 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
4780 Query *subquery = subrte->subquery;
4781
4782 Assert(subquery != NULL);
4783 subquery_push_qual(subquery, rte, rti, qual);
4784 }
4785 else if (IsA(setOp, SetOperationStmt))
4786 {
4788
4789 recurse_push_qual(op->larg, topquery, rte, rti, qual);
4790 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
4791 }
4792 else
4793 {
4794 elog(ERROR, "unrecognized node type: %d",
4795 (int) nodeTag(setOp));
4796 }
4797}
4798
4799/*****************************************************************************
4800 * SIMPLIFYING SUBQUERY TARGETLISTS
4801 *****************************************************************************/
4802
4803/*
4804 * remove_unused_subquery_outputs
4805 * Remove subquery targetlist items we don't need
4806 *
4807 * It's possible, even likely, that the upper query does not read all the
4808 * output columns of the subquery. We can remove any such outputs that are
4809 * not needed by the subquery itself (e.g., as sort/group columns) and do not
4810 * affect semantics otherwise (e.g., volatile functions can't be removed).
4811 * This is useful not only because we might be able to remove expensive-to-
4812 * compute expressions, but because deletion of output columns might allow
4813 * optimizations such as join removal to occur within the subquery.
4814 *
4815 * extra_used_attrs can be passed as non-NULL to mark any columns (offset by
4816 * FirstLowInvalidHeapAttributeNumber) that we should not remove. This
4817 * parameter is modified by the function, so callers must make a copy if they
4818 * need to use the passed in Bitmapset after calling this function.
4819 *
4820 * To avoid affecting column numbering in the targetlist, we don't physically
4821 * remove unused tlist entries, but rather replace their expressions with NULL
4822 * constants. This is implemented by modifying subquery->targetList.
4823 */
4824static void
4827{
4828 Bitmapset *attrs_used;
4829 ListCell *lc;
4830
4831 /*
4832 * Just point directly to extra_used_attrs. No need to bms_copy as none of
4833 * the current callers use the Bitmapset after calling this function.
4834 */
4835 attrs_used = extra_used_attrs;
4836
4837 /*
4838 * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4839 * could update all the child SELECTs' tlists, but it seems not worth the
4840 * trouble presently.
4841 */
4842 if (subquery->setOperations)
4843 return;
4844
4845 /*
4846 * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4847 * time: all its output columns must be used in the distinctClause.
4848 */
4849 if (subquery->distinctClause && !subquery->hasDistinctOn)
4850 return;
4851
4852 /*
4853 * Collect a bitmap of all the output column numbers used by the upper
4854 * query.
4855 *
4856 * Add all the attributes needed for joins or final output. Note: we must
4857 * look at rel's targetlist, not the attr_needed data, because attr_needed
4858 * isn't computed for inheritance child rels, cf set_append_rel_size().
4859 * (XXX might be worth changing that sometime.)
4860 */
4861 pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4862
4863 /* Add all the attributes used by un-pushed-down restriction clauses. */
4864 foreach(lc, rel->baserestrictinfo)
4865 {
4866 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4867
4868 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4869 }
4870
4871 /*
4872 * If there's a whole-row reference to the subquery, we can't remove
4873 * anything.
4874 */
4876 return;
4877
4878 /*
4879 * Run through the tlist and zap entries we don't need. It's okay to
4880 * modify the tlist items in-place because set_subquery_pathlist made a
4881 * copy of the subquery.
4882 */
4883 foreach(lc, subquery->targetList)
4884 {
4886 Node *texpr = (Node *) tle->expr;
4887
4888 /*
4889 * If it has a sortgroupref number, it's used in some sort/group
4890 * clause so we'd better not remove it. Also, don't remove any
4891 * resjunk columns, since their reason for being has nothing to do
4892 * with anybody reading the subquery's output. (It's likely that
4893 * resjunk columns in a sub-SELECT would always have ressortgroupref
4894 * set, but even if they don't, it seems imprudent to remove them.)
4895 */
4896 if (tle->ressortgroupref || tle->resjunk)
4897 continue;
4898
4899 /*
4900 * If it's used by the upper query, we can't remove it.
4901 */
4903 attrs_used))
4904 continue;
4905
4906 /*
4907 * If it contains a set-returning function, we can't remove it since
4908 * that could change the number of rows returned by the subquery.
4909 */
4910 if (subquery->hasTargetSRFs &&
4912 continue;
4913
4914 /*
4915 * If it contains volatile functions, we daren't remove it for fear
4916 * that the user is expecting their side-effects to happen.
4917 */
4919 continue;
4920
4921 /*
4922 * OK, we don't need it. Replace the expression with a NULL constant.
4923 * Preserve the exposed type of the expression, in case something
4924 * looks at the rowtype of the subquery's result.
4925 */
4926 tle->expr = (Expr *) makeNullConst(exprType(texpr),
4929 }
4930}
4931
4932/*
4933 * create_partial_bitmap_paths
4934 * Build partial bitmap heap path for the relation
4935 */
4936void
4938 Path *bitmapqual)
4939{
4940 int parallel_workers;
4941 double pages_fetched;
4942
4943 /* Compute heap pages for bitmap heap scan */
4944 pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4945 NULL, NULL);
4946
4947 parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4949
4950 if (parallel_workers <= 0)
4951 return;
4952
4954 bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4955}
4956
4957/*
4958 * Compute the number of parallel workers that should be used to scan a
4959 * relation. We compute the parallel workers based on the size of the heap to
4960 * be scanned and the size of the index to be scanned, then choose a minimum
4961 * of those.
4962 *
4963 * "heap_pages" is the number of pages from the table that we expect to scan, or
4964 * -1 if we don't expect to scan any.
4965 *
4966 * "index_pages" is the number of pages from the index that we expect to scan, or
4967 * -1 if we don't expect to scan any.
4968 *
4969 * "max_workers" is caller's limit on the number of workers. This typically
4970 * comes from a GUC.
4971 */
4972int
4974 int max_workers)
4975{
4976 int parallel_workers = 0;
4977
4978 /*
4979 * If the user has set the parallel_workers reloption, use that; otherwise
4980 * select a default number of workers.
4981 */
4982 if (rel->rel_parallel_workers != -1)
4983 parallel_workers = rel->rel_parallel_workers;
4984 else
4985 {
4986 /*
4987 * If the number of pages being scanned is insufficient to justify a
4988 * parallel scan, just return zero ... unless it's an inheritance
4989 * child. In that case, we want to generate a parallel path here
4990 * anyway. It might not be worthwhile just for this relation, but
4991 * when combined with all of its inheritance siblings it may well pay
4992 * off.
4993 */
4994 if (rel->reloptkind == RELOPT_BASEREL &&
4997 return 0;
4998
4999 if (heap_pages >= 0)
5000 {
5002 int heap_parallel_workers = 1;
5003
5004 /*
5005 * Select the number of workers based on the log of the size of
5006 * the relation. This probably needs to be a good deal more
5007 * sophisticated, but we need something here for now. Note that
5008 * the upper limit of the min_parallel_table_scan_size GUC is
5009 * chosen to prevent overflow here.
5010 */
5013 {
5017 break; /* avoid overflow */
5018 }
5019
5020 parallel_workers = heap_parallel_workers;
5021 }
5022
5023 if (index_pages >= 0)
5024 {
5025 int index_parallel_workers = 1;
5027
5028 /* same calculation as for heap_pages above */
5031 {
5035 break; /* avoid overflow */
5036 }
5037
5038 if (parallel_workers > 0)
5039 parallel_workers = Min(parallel_workers, index_parallel_workers);
5040 else
5041 parallel_workers = index_parallel_workers;
5042 }
5043 }
5044
5045 /* In no case use more than caller supplied maximum number of workers */
5046 parallel_workers = Min(parallel_workers, max_workers);
5047
5048 return parallel_workers;
5049}
5050
5051/*
5052 * generate_partitionwise_join_paths
5053 * Create paths representing partitionwise join for given partitioned
5054 * join relation.
5055 *
5056 * This must not be called until after we are done adding paths for all
5057 * child-joins. Otherwise, add_path might delete a path to which some path
5058 * generated here has a reference.
5059 */
5060void
5062{
5064 int cnt_parts;
5065 int num_parts;
5067
5068 /* Handle only join relations here. */
5069 if (!IS_JOIN_REL(rel))
5070 return;
5071
5072 /* We've nothing to do if the relation is not partitioned. */
5073 if (!IS_PARTITIONED_REL(rel))
5074 return;
5075
5076 /* The relation should have consider_partitionwise_join set. */
5078
5079 /* Guard against stack overflow due to overly deep partition hierarchy. */
5081
5082 num_parts = rel->nparts;
5083 part_rels = rel->part_rels;
5084
5085 /* Collect non-dummy child-joins. */
5086 for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
5087 {
5089
5090 /* If it's been pruned entirely, it's certainly dummy. */
5091 if (child_rel == NULL)
5092 continue;
5093
5094 /* Make partitionwise join paths for this partitioned child-join. */
5096
5097 /* If we failed to make any path for this child, we must give up. */
5098 if (child_rel->pathlist == NIL)
5099 {
5100 /*
5101 * Mark the parent joinrel as unpartitioned so that later
5102 * functions treat it correctly.
5103 */
5104 rel->nparts = 0;
5105 return;
5106 }
5107
5108 /* Else, identify the cheapest path for it. */
5110
5111 /* Dummy children need not be scanned, so ignore those. */
5113 continue;
5114
5115 /*
5116 * Except for the topmost scan/join rel, consider generating partial
5117 * aggregation paths for the grouped relation on top of the paths of
5118 * this partitioned child-join. After that, we're done creating paths
5119 * for the grouped relation, so run set_cheapest().
5120 */
5121 if (child_rel->grouped_rel != NULL &&
5122 !bms_equal(IS_OTHER_REL(rel) ?
5123 rel->top_parent_relids : rel->relids,
5124 root->all_query_rels))
5125 {
5126 RelOptInfo *grouped_rel = child_rel->grouped_rel;
5127
5128 Assert(IS_GROUPED_REL(grouped_rel));
5129
5130 generate_grouped_paths(root, grouped_rel, child_rel);
5131 set_cheapest(grouped_rel);
5132 }
5133
5134#ifdef OPTIMIZER_DEBUG
5136#endif
5137
5139 }
5140
5141 /* If all child-joins are dummy, parent join is also dummy. */
5142 if (!live_children)
5143 {
5144 mark_dummy_rel(rel);
5145 return;
5146 }
5147
5148 /* Build additional paths for this rel from child-join paths. */
5151}
static void set_base_rel_sizes(PlannerInfo *root)
Definition allpaths.c:308
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition allpaths.c:3324
static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition allpaths.c:2683
#define UNSAFE_TYPE_MISMATCH
Definition allpaths.c:59
static Oid setop_column_grouping_eqop(Node *setop, AttrNumber attno)
Definition allpaths.c:4675
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition allpaths.c:2168
static void set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:3142
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition allpaths.c:4725
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition allpaths.c:5061
static bool setop_has_grouping(Node *setop)
Definition allpaths.c:4707
void generate_grouped_paths(PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *rel)
Definition allpaths.c:3509
static void set_base_rel_consider_startup(PlannerInfo *root)
Definition allpaths.c:265
#define UNSAFE_HAS_VOLATILE_FUNC
Definition allpaths.c:55
#define UNSAFE_NOTIN_DISTINCTON_CLAUSE
Definition allpaths.c:57
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition allpaths.c:520
static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:896
static void set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:936
static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:1008
static void set_base_rel_pathlists(PlannerInfo *root)
Definition allpaths.c:384
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition allpaths.c:3952
int geqo_threshold
Definition allpaths.c:83
static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition allpaths.c:1321
static pushdown_safe_type qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4459
static void set_result_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:3169
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition allpaths.c:4973
static bool check_and_push_window_quals(Query *subquery, Node *clause, Bitmapset **run_cond_attrs)
Definition allpaths.c:2610
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition allpaths.c:3255
static void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition allpaths.c:2370
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4373
static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:3196
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition allpaths.c:4406
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition allpaths.c:876
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4147
join_search_hook_type join_search_hook
Definition allpaths.c:92
bool enable_geqo
Definition allpaths.c:81
static Oid pushdown_var_grouping_eqop(Var *var, void *context)
Definition allpaths.c:4579
static Path * get_singleton_append_subpath(Path *path, List **child_append_relid_sets)
Definition allpaths.c:2322
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition allpaths.c:3392
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition allpaths.c:3847
static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:2952
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition allpaths.c:4773
static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:838
static void setup_simple_grouped_rels(PlannerInfo *root)
Definition allpaths.c:350
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
Definition allpaths.c:4825
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4272
static void set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:3039
static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:984
set_rel_pathlist_hook_type set_rel_pathlist_hook
Definition allpaths.c:89
static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:3019
RelOptInfo * make_one_rel(PlannerInfo *root, List *joinlist)
Definition allpaths.c:183
#define UNSAFE_HAS_SET_FUNC
Definition allpaths.c:56
static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:3063
bool enable_eager_aggregate
Definition allpaths.c:82
static Oid subquery_column_grouping_eqop(Query *subquery, AttrNumber attno)
Definition allpaths.c:4612
static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:649
static void set_grouped_rel_pathlist(PlannerInfo *root, RelOptInfo *rel)
Definition allpaths.c:1384
static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition allpaths.c:1026
void create_partial_bitmap_paths(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual)
Definition allpaths.c:4937
static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition allpaths.c:632
double min_eager_agg_group_size
Definition allpaths.c:84
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition allpaths.c:1420
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths, List **child_append_relid_sets)
Definition allpaths.c:2256
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition allpaths.c:411
static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
Definition allpaths.c:1852
#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE
Definition allpaths.c:58
static bool find_window_run_conditions(Query *subquery, AttrNumber attno, WindowFunc *wfunc, OpExpr *opexpr, bool wfunc_left, bool *keep_original, Bitmapset **run_cond_attrs)
Definition allpaths.c:2420
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4203
pushdown_safe_type
Definition allpaths.c:73
@ PUSHDOWN_WINDOWCLAUSE_RUNCOND
Definition allpaths.c:76
@ PUSHDOWN_UNSAFE
Definition allpaths.c:74
@ PUSHDOWN_SAFE
Definition allpaths.c:75
int min_parallel_index_scan_size
Definition allpaths.c:86
int min_parallel_table_scan_size
Definition allpaths.c:85
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition appendinfo.c:201
int16 AttrNumber
Definition attnum.h:21
#define InvalidAttrNumber
Definition attnum.h:23
void pprint(const void *obj)
Definition print.c:54
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:143
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:547
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:645
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:934
BMS_Membership bms_membership(const Bitmapset *a)
Definition bitmapset.c:900
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:710
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition bitmapset.c:843
#define bms_is_empty(a)
Definition bitmapset.h:119
@ BMS_SINGLETON
Definition bitmapset.h:72
@ BMS_MULTIPLE
Definition bitmapset.h:73
uint32 BlockNumber
Definition block.h:31
#define Min(x, y)
Definition c.h:1131
#define Max(x, y)
Definition c.h:1125
#define Assert(condition)
Definition c.h:1002
int32_t int32
Definition c.h:679
unsigned int Index
Definition c.h:757
#define MemSet(start, val, len)
Definition c.h:1147
#define OidIsValid(objectId)
Definition c.h:917
bool expression_has_grouping_conflict(Node *expr, grouping_eqop_callback get_eqop, void *context)
Definition clauses.c:6318
bool is_pseudo_constant_clause(Node *clause)
Definition clauses.c:2349
bool contain_leaked_vars(Node *clause)
Definition clauses.c:1294
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition clauses.c:782
bool contain_subplans(Node *clause)
Definition clauses.c:359
bool contain_volatile_functions(Node *clause)
Definition clauses.c:567
CompareType
Definition cmptype.h:32
@ COMPARE_LE
Definition cmptype.h:35
@ COMPARE_GT
Definition cmptype.h:38
@ COMPARE_EQ
Definition cmptype.h:36
@ COMPARE_GE
Definition cmptype.h:37
@ COMPARE_LT
Definition cmptype.h:34
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6280
int max_parallel_workers_per_gather
Definition costsize.c:144
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:5516
void set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6150
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition costsize.c:6242
double compute_gather_rows(Path *path)
Definition costsize.c:6792
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6313
bool enable_partitionwise_join
Definition costsize.c:161
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition costsize.c:6681
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6070
bool enable_parallel_append
Definition costsize.c:163
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6342
double clamp_row_est(double nrows)
Definition costsize.c:215
void set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6188
void set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6210
bool enable_incremental_sort
Definition costsize.c:152
Datum arg
Definition elog.c:1323
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
void add_child_rel_equivalences(PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:726
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition geqo_main.c:75
void parse(int)
Definition parse.c:49
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition indxpath.c:3940
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition indxpath.c:239
int i
Definition isn.c:77
void join_search_one_level(PlannerInfo *root, int level)
Definition joinrels.c:78
void mark_dummy_rel(RelOptInfo *rel)
Definition joinrels.c:1513
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_copy_tail(const List *oldlist, int nskip)
Definition list.c:1613
List * list_concat(List *list1, const List *list2)
Definition list.c:561
void list_free(List *list)
Definition list.c:1546
List * list_copy_head(const List *oldlist, int len)
Definition list.c:1593
char get_rel_persistence(Oid relid)
Definition lsyscache.c:2392
char func_parallel(Oid funcid)
Definition lsyscache.c:2113
Oid get_opfamily_member_for_cmptype(Oid opfamily, Oid lefttype, Oid righttype, CompareType cmptype)
Definition lsyscache.c:199
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2172
bool func_strict(Oid funcid)
Definition lsyscache.c:2075
List * get_op_index_interpretation(Oid opno)
Definition lsyscache.c:729
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition lsyscache.c:2894
Datum subpath(PG_FUNCTION_ARGS)
Definition ltree_op.c:348
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition makefuncs.c:388
Node * make_and_qual(Node *qual1, Node *qual2)
Definition makefuncs.c:780
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc0(Size size)
Definition mcxt.c:1420
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
bool expression_returns_set(Node *clause)
Definition nodeFuncs.c:768
void set_opfuncid(OpExpr *opexpr)
Definition nodeFuncs.c:1890
#define IsA(nodeptr, _type_)
Definition nodes.h:162
#define copyObject(obj)
Definition nodes.h:230
#define nodeTag(nodeptr)
Definition nodes.h:137
@ AGG_SORTED
Definition nodes.h:363
@ AGG_HASHED
Definition nodes.h:364
@ AGGSPLIT_INITIAL_SERIAL
Definition nodes.h:387
#define makeNode(_type_)
Definition nodes.h:159
#define castNode(_type_, nodeptr)
Definition nodes.h:180
@ JOIN_SEMI
Definition nodes.h:315
@ JOIN_ANTI
Definition nodes.h:316
#define PVC_INCLUDE_PLACEHOLDERS
Definition optimizer.h:201
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
@ SETOP_EXCEPT
@ RTE_JOIN
@ RTE_CTE
@ RTE_NAMEDTUPLESTORE
@ RTE_VALUES
@ RTE_SUBQUERY
@ RTE_RESULT
@ RTE_FUNCTION
@ RTE_TABLEFUNC
@ RTE_GROUP
@ RTE_GRAPH_TABLE
@ RTE_RELATION
#define rt_fetch(rangetable_index, rangetable)
Definition parsetree.h:31
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition pathkeys.c:666
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition pathkeys.c:620
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition pathkeys.c:558
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition pathkeys.c:2291
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition pathkeys.c:1336
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Oid opno, Relids rel, bool create_it)
Definition pathkeys.c:1000
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition pathkeys.c:919
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition pathkeys.c:1054
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition pathkeys.c:343
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition pathkeys.c:304
Path * get_cheapest_parallel_safe_total_inner(List *paths)
Definition pathkeys.c:699
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition pathnode.c:1939
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1991
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath, bool enabled)
Definition pathnode.c:1712
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2095
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition pathnode.c:2587
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition pathnode.c:1026
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition pathnode.c:1813
void set_cheapest(RelOptInfo *parent_rel)
Definition pathnode.c:268
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition pathnode.c:793
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2043
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, bool trivial_pathtarget, List *pathkeys, Relids required_outer)
Definition pathnode.c:1909
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition pathnode.c:2855
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition pathnode.c:1149
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1965
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition pathnode.c:2904
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *child_append_relid_sets, List *pathkeys, Relids required_outer)
Definition pathnode.c:1524
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition pathnode.c:1865
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1051
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition pathnode.c:459
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition pathnode.c:68
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2069
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, AppendPathInput input, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition pathnode.c:1352
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition pathnode.c:2017
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition pathnode.c:3067
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition pathnode.c:3937
#define IS_SIMPLE_REL(rel)
Definition pathnodes.h:989
#define IS_DUMMY_REL(r)
Definition pathnodes.h:2299
#define IS_JOIN_REL(rel)
Definition pathnodes.h:994
@ TOTAL_COST
Definition pathnodes.h:111
@ STARTUP_COST
Definition pathnodes.h:111
#define IS_PARTITIONED_REL(rel)
Definition pathnodes.h:1231
#define IS_GROUPED_REL(rel)
Definition pathnodes.h:1257
#define PATH_REQ_OUTER(path)
Definition pathnodes.h:2015
Bitmapset * Relids
Definition pathnodes.h:103
@ UPPERREL_FINAL
Definition pathnodes.h:152
@ RELOPT_BASEREL
Definition pathnodes.h:977
@ RELOPT_OTHER_MEMBER_REL
Definition pathnodes.h:979
#define IS_OTHER_REL(rel)
Definition pathnodes.h:1004
void(* set_rel_pathlist_hook_type)(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition paths.h:39
RelOptInfo *(* join_search_hook_type)(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition paths.h:55
@ PATHKEYS_EQUAL
Definition paths.h:219
static int pg_leftmost_one_pos32(uint32 word)
Definition pg_bitutils.h:41
#define lfirst(lc)
Definition pg_list.h:172
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
#define foreach_current_index(var_or_cell)
Definition pg_list.h:435
#define list_make1(x1)
Definition pg_list.h:244
#define for_each_from(cell, lst, N)
Definition pg_list.h:446
static void * list_nth(const List *list, int n)
Definition pg_list.h:331
#define linitial(l)
Definition pg_list.h:178
#define lsecond(l)
Definition pg_list.h:183
static ListCell * list_head(const List *l)
Definition pg_list.h:128
#define list_nth_node(type, list, n)
Definition pg_list.h:359
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:375
#define lfirst_oid(lc)
Definition pg_list.h:174
static int list_nth_int(const List *list, int n)
Definition pg_list.h:342
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition plancat.c:1852
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, PlannerInfo *parent_root, PlannerInfo *alternative_root, bool hasRecursion, double tuple_fraction, SetOperationStmt *setops)
Definition planner.c:770
char * choose_plan_name(PlannerGlobal *glob, const char *name, bool always_number)
Definition planner.c:9215
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition planner.c:6848
bool limit_needed(Query *parse)
Definition planner.c:3032
@ MONOTONICFUNC_NONE
Definition plannodes.h:1841
@ MONOTONICFUNC_DECREASING
Definition plannodes.h:1843
@ MONOTONICFUNC_INCREASING
Definition plannodes.h:1842
@ MONOTONICFUNC_BOTH
Definition plannodes.h:1844
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define PointerGetDatum(X)
Definition postgres.h:354
#define InvalidOid
unsigned int Oid
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition prepagg.c:559
static int fb(int x)
tree ctl root
Definition radixtree.h:1857
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition relnode.c:544
RelOptInfo * build_simple_grouped_rel(PlannerInfo *root, RelOptInfo *rel)
Definition relnode.c:448
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition relnode.c:1617
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, int result_relation, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
@ REPLACEVARS_REPORT_ERROR
@ BackwardScanDirection
Definition sdir.h:26
@ ForwardScanDirection
Definition sdir.h:28
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition selfuncs.c:3804
void check_stack_depth(void)
Definition stack_depth.c:96
List * subpaths
Definition pathnode.h:36
List * child_append_relid_sets
Definition pathnode.h:38
List * partial_subpaths
Definition pathnode.h:37
Node * quals
Definition primnodes.h:2380
Definition pg_list.h:54
Definition nodes.h:133
Oid opno
Definition primnodes.h:835
List * args
Definition primnodes.h:853
CompareType cmptype
Definition lsyscache.h:28
List * exprs
Definition pathnodes.h:1878
List * pathkeys
Definition pathnodes.h:2011
Cardinality rows
Definition pathnodes.h:2005
int parallel_workers
Definition pathnodes.h:2002
bool parallel_aware
Definition pathnodes.h:1998
Node * limitCount
Definition parsenodes.h:235
FromExpr * jointree
Definition parsenodes.h:187
Node * setOperations
Definition parsenodes.h:240
List * groupClause
Definition parsenodes.h:221
Node * havingQual
Definition parsenodes.h:226
Node * limitOffset
Definition parsenodes.h:234
List * windowClause
Definition parsenodes.h:228
List * targetList
Definition parsenodes.h:203
List * groupingSets
Definition parsenodes.h:224
List * distinctClause
Definition parsenodes.h:230
Relids apply_agg_at
Definition pathnodes.h:1302
List * group_exprs
Definition pathnodes.h:1299
bool agg_useful
Definition pathnodes.h:1308
List * group_clauses
Definition pathnodes.h:1297
struct PathTarget * agg_input
Definition pathnodes.h:1294
struct PathTarget * target
Definition pathnodes.h:1291
List * baserestrictinfo
Definition pathnodes.h:1142
bool consider_param_startup
Definition pathnodes.h:1035
List * subplan_params
Definition pathnodes.h:1101
List * joininfo
Definition pathnodes.h:1148
Relids relids
Definition pathnodes.h:1021
struct PathTarget * reltarget
Definition pathnodes.h:1045
Index relid
Definition pathnodes.h:1069
struct RelAggInfo * agg_info
Definition pathnodes.h:1162
Cardinality tuples
Definition pathnodes.h:1096
bool consider_parallel
Definition pathnodes.h:1037
Relids top_parent_relids
Definition pathnodes.h:1174
BlockNumber pages
Definition pathnodes.h:1095
Relids lateral_relids
Definition pathnodes.h:1064
List * pathlist
Definition pathnodes.h:1050
RelOptKind reloptkind
Definition pathnodes.h:1015
struct Path * cheapest_total_path
Definition pathnodes.h:1054
struct RelOptInfo * grouped_rel
Definition pathnodes.h:1164
bool has_eclass_joins
Definition pathnodes.h:1150
bool consider_startup
Definition pathnodes.h:1033
Bitmapset * live_parts
Definition pathnodes.h:1204
int rel_parallel_workers
Definition pathnodes.h:1103
bool consider_partitionwise_join
Definition pathnodes.h:1156
List * partial_pathlist
Definition pathnodes.h:1052
PlannerInfo * subroot
Definition pathnodes.h:1100
AttrNumber max_attr
Definition pathnodes.h:1077
Relids nulling_relids
Definition pathnodes.h:1085
Cardinality rows
Definition pathnodes.h:1027
AttrNumber min_attr
Definition pathnodes.h:1075
RTEKind rtekind
Definition pathnodes.h:1073
Expr * clause
Definition pathnodes.h:2901
SetOperation op
JoinType jointype
Definition pathnodes.h:3230
Relids syn_righthand
Definition pathnodes.h:3229
MonotonicFunction monotonic
bool repeatable_across_scans
Definition tsmapi.h:65
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295
List * partitionClause
Index winref
Definition primnodes.h:604
unsigned char * unsafeFlags
Definition allpaths.c:64
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition tablesample.c:27
bool create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel)
Definition tidpath.c:497
bool grouping_is_sortable(List *groupClause)
Definition tlist.c:549
List * make_tlist_from_pathtarget(PathTarget *target)
Definition tlist.c:633
bool grouping_is_hashable(List *groupClause)
Definition tlist.c:569
Node * flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
Definition var.c:999
List * pull_var_clause(Node *node, int flags)
Definition var.c:653
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition var.c:296