Coverage Report

Created: 2026-12-01 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/optimizer/util/relnode.c
Line
Count
Source
1
/*-------------------------------------------------------------------------
2
 *
3
 * relnode.c
4
 *    Relation-node lookup/construction routines
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/util/relnode.c
12
 *
13
 *-------------------------------------------------------------------------
14
 */
15
#include "postgres.h"
16
17
#include <limits.h>
18
19
#include "access/nbtree.h"
20
#include "catalog/pg_constraint.h"
21
#include "miscadmin.h"
22
#include "nodes/nodeFuncs.h"
23
#include "optimizer/appendinfo.h"
24
#include "optimizer/clauses.h"
25
#include "optimizer/cost.h"
26
#include "optimizer/inherit.h"
27
#include "optimizer/optimizer.h"
28
#include "optimizer/pathnode.h"
29
#include "optimizer/paths.h"
30
#include "optimizer/placeholder.h"
31
#include "optimizer/plancat.h"
32
#include "optimizer/planner.h"
33
#include "optimizer/restrictinfo.h"
34
#include "optimizer/tlist.h"
35
#include "parser/parse_oper.h"
36
#include "parser/parse_relation.h"
37
#include "rewrite/rewriteManip.h"
38
#include "utils/hsearch.h"
39
#include "utils/lsyscache.h"
40
#include "utils/selfuncs.h"
41
#include "utils/typcache.h"
42
43
44
typedef struct JoinHashEntry
45
{
46
  Relids    join_relids;  /* hash key --- MUST BE FIRST */
47
  RelOptInfo *join_rel;
48
} JoinHashEntry;
49
50
/* Hook for plugins to get control in build_simple_rel() */
51
build_simple_rel_hook_type build_simple_rel_hook = NULL;
52
53
/* Hook for plugins to get control during joinrel setup */
54
joinrel_setup_hook_type joinrel_setup_hook = NULL;
55
56
static void build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
57
                RelOptInfo *input_rel,
58
                SpecialJoinInfo *sjinfo,
59
                List *pushed_down_joins,
60
                bool can_null);
61
static List *build_joinrel_restrictlist(PlannerInfo *root,
62
                    RelOptInfo *joinrel,
63
                    RelOptInfo *outer_rel,
64
                    RelOptInfo *inner_rel,
65
                    SpecialJoinInfo *sjinfo);
66
#ifdef USE_ASSERT_CHECKING
67
static bool no_duplicate_clause_serials(List *clauses);
68
#endif
69
static void build_joinrel_joinlist(RelOptInfo *joinrel,
70
                   RelOptInfo *outer_rel,
71
                   RelOptInfo *inner_rel);
72
static List *subbuild_joinrel_restrictlist(PlannerInfo *root,
73
                       RelOptInfo *joinrel,
74
                       RelOptInfo *input_rel,
75
                       Relids both_input_relids,
76
                       List *new_restrictlist);
77
static List *subbuild_joinrel_joinlist(RelOptInfo *joinrel,
78
                     List *joininfo_list,
79
                     List *new_joininfo);
80
static void set_foreign_rel_properties(RelOptInfo *joinrel,
81
                     RelOptInfo *outer_rel, RelOptInfo *inner_rel);
82
static void add_join_rel(PlannerInfo *root, RelOptInfo *joinrel);
83
static void build_joinrel_partition_info(PlannerInfo *root,
84
                     RelOptInfo *joinrel,
85
                     RelOptInfo *outer_rel, RelOptInfo *inner_rel,
86
                     SpecialJoinInfo *sjinfo,
87
                     List *restrictlist);
88
static bool have_partkey_equi_join(PlannerInfo *root, RelOptInfo *joinrel,
89
                   RelOptInfo *rel1, RelOptInfo *rel2,
90
                   JoinType jointype, List *restrictlist);
91
static int  match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel,
92
                     bool strict_op);
93
static void set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
94
                      RelOptInfo *outer_rel, RelOptInfo *inner_rel,
95
                      JoinType jointype);
96
static void build_child_join_reltarget(PlannerInfo *root,
97
                     RelOptInfo *parentrel,
98
                     RelOptInfo *childrel,
99
                     int nappinfos,
100
                     AppendRelInfo **appinfos);
101
static bool eager_aggregation_possible_for_relation(PlannerInfo *root,
102
                          RelOptInfo *rel);
103
static bool init_grouping_targets(PlannerInfo *root, RelOptInfo *rel,
104
                  PathTarget *target, PathTarget *agg_input,
105
                  List **group_clauses, List **group_exprs);
106
static bool is_var_in_aggref_only(PlannerInfo *root, Var *var);
107
static bool is_var_needed_by_join(PlannerInfo *root, Var *var, RelOptInfo *rel);
108
static Index get_expression_sortgroupref(PlannerInfo *root, Expr *expr);
109
110
111
/*
112
 * setup_simple_rel_arrays
113
 *    Prepare the arrays we use for quickly accessing base relations
114
 *    and AppendRelInfos.
115
 */
116
void
117
setup_simple_rel_arrays(PlannerInfo *root)
118
0
{
119
0
  int     size;
120
0
  Index   rti;
121
0
  ListCell   *lc;
122
123
  /* Arrays are accessed using RT indexes (1..N) */
124
0
  size = list_length(root->parse->rtable) + 1;
125
0
  root->simple_rel_array_size = size;
126
127
  /*
128
   * simple_rel_array is initialized to all NULLs, since no RelOptInfos
129
   * exist yet.  It'll be filled by later calls to build_simple_rel().
130
   */
131
0
  root->simple_rel_array = (RelOptInfo **)
132
0
    palloc0_array(RelOptInfo *, size);
133
134
  /* simple_rte_array is an array equivalent of the rtable list */
135
0
  root->simple_rte_array = (RangeTblEntry **)
136
0
    palloc0_array(RangeTblEntry *, size);
137
0
  rti = 1;
138
0
  foreach(lc, root->parse->rtable)
139
0
  {
140
0
    RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
141
142
0
    root->simple_rte_array[rti++] = rte;
143
0
  }
144
145
  /* append_rel_array is not needed if there are no AppendRelInfos */
146
0
  if (root->append_rel_list == NIL)
147
0
  {
148
0
    root->append_rel_array = NULL;
149
0
    return;
150
0
  }
151
152
0
  root->append_rel_array = (AppendRelInfo **)
153
0
    palloc0_array(AppendRelInfo *, size);
154
155
  /*
156
   * append_rel_array is filled with any already-existing AppendRelInfos,
157
   * which currently could only come from UNION ALL flattening.  We might
158
   * add more later during inheritance expansion, but it's the
159
   * responsibility of the expansion code to update the array properly.
160
   */
161
0
  foreach(lc, root->append_rel_list)
162
0
  {
163
0
    AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
164
0
    int     child_relid = appinfo->child_relid;
165
166
    /* Sanity check */
167
0
    Assert(child_relid < size);
168
169
0
    if (root->append_rel_array[child_relid])
170
0
      elog(ERROR, "child relation already exists");
171
172
0
    root->append_rel_array[child_relid] = appinfo;
173
0
  }
174
0
}
175
176
/*
177
 * expand_planner_arrays
178
 *    Expand the PlannerInfo's per-RTE arrays by add_size members
179
 *    and initialize the newly added entries to NULLs
180
 *
181
 * Note: this causes the append_rel_array to become allocated even if
182
 * it was not before.  This is okay for current uses, because we only call
183
 * this when adding child relations, which always have AppendRelInfos.
184
 */
185
void
186
expand_planner_arrays(PlannerInfo *root, int add_size)
187
0
{
188
0
  int     new_size;
189
190
0
  Assert(add_size > 0);
191
192
0
  new_size = root->simple_rel_array_size + add_size;
193
194
0
  root->simple_rel_array =
195
0
    repalloc0_array(root->simple_rel_array, RelOptInfo *, root->simple_rel_array_size, new_size);
196
197
0
  root->simple_rte_array =
198
0
    repalloc0_array(root->simple_rte_array, RangeTblEntry *, root->simple_rel_array_size, new_size);
199
200
0
  if (root->append_rel_array)
201
0
    root->append_rel_array =
202
0
      repalloc0_array(root->append_rel_array, AppendRelInfo *, root->simple_rel_array_size, new_size);
203
0
  else
204
0
    root->append_rel_array =
205
0
      palloc0_array(AppendRelInfo *, new_size);
206
207
0
  root->simple_rel_array_size = new_size;
208
0
}
209
210
/*
211
 * build_simple_rel
212
 *    Construct a new RelOptInfo for a base relation or 'other' relation.
213
 */
214
RelOptInfo *
215
build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
216
0
{
217
0
  RelOptInfo *rel;
218
0
  RangeTblEntry *rte;
219
220
  /* Rel should not exist already */
221
0
  Assert(relid > 0 && relid < root->simple_rel_array_size);
222
0
  if (root->simple_rel_array[relid] != NULL)
223
0
    elog(ERROR, "rel %d already exists", relid);
224
225
  /* Fetch RTE for relation */
226
0
  rte = root->simple_rte_array[relid];
227
0
  Assert(rte != NULL);
228
229
0
  rel = makeNode(RelOptInfo);
230
0
  rel->reloptkind = parent ? RELOPT_OTHER_MEMBER_REL : RELOPT_BASEREL;
231
0
  rel->relids = bms_make_singleton(relid);
232
0
  rel->rows = 0;
233
  /* cheap startup cost is interesting iff not all tuples to be retrieved */
234
0
  rel->consider_startup = (root->tuple_fraction > 0);
235
0
  rel->consider_param_startup = false;  /* might get changed later */
236
0
  rel->consider_parallel = false; /* might get changed later */
237
0
  rel->pgs_mask = root->glob->default_pgs_mask;
238
0
  rel->reltarget = create_empty_pathtarget();
239
0
  rel->pathlist = NIL;
240
0
  rel->ppilist = NIL;
241
0
  rel->partial_pathlist = NIL;
242
0
  rel->cheapest_startup_path = NULL;
243
0
  rel->cheapest_total_path = NULL;
244
0
  rel->cheapest_parameterized_paths = NIL;
245
0
  rel->relid = relid;
246
0
  rel->rtekind = rte->rtekind;
247
  /* min_attr, max_attr, attr_needed, attr_widths are set below */
248
0
  rel->notnullattnums = NULL;
249
0
  rel->lateral_vars = NIL;
250
0
  rel->indexlist = NIL;
251
0
  rel->statlist = NIL;
252
0
  rel->pages = 0;
253
0
  rel->tuples = 0;
254
0
  rel->allvisfrac = 0;
255
0
  rel->eclass_indexes = NULL;
256
0
  rel->subroot = NULL;
257
0
  rel->subplan_params = NIL;
258
0
  rel->rel_parallel_workers = -1; /* set up in get_relation_info */
259
0
  rel->amflags = 0;
260
0
  rel->serverid = InvalidOid;
261
0
  if (rte->rtekind == RTE_RELATION)
262
0
  {
263
0
    Assert(parent == NULL ||
264
0
         parent->rtekind == RTE_RELATION ||
265
0
         parent->rtekind == RTE_SUBQUERY);
266
267
    /*
268
     * For any RELATION rte, we need a userid with which to check
269
     * permission access. Baserels simply use their own
270
     * RTEPermissionInfo's checkAsUser.
271
     *
272
     * For otherrels normally there's no RTEPermissionInfo, so we use the
273
     * parent's, which normally has one. The exceptional case is that the
274
     * parent is a subquery, in which case the otherrel will have its own.
275
     */
276
0
    if (rel->reloptkind == RELOPT_BASEREL ||
277
0
      (rel->reloptkind == RELOPT_OTHER_MEMBER_REL &&
278
0
       parent->rtekind == RTE_SUBQUERY))
279
0
    {
280
0
      RTEPermissionInfo *perminfo;
281
282
0
      perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte);
283
0
      rel->userid = perminfo->checkAsUser;
284
0
    }
285
0
    else
286
0
      rel->userid = parent->userid;
287
0
  }
288
0
  else
289
0
    rel->userid = InvalidOid;
290
0
  rel->useridiscurrent = false;
291
0
  rel->fdwroutine = NULL;
292
0
  rel->fdw_private = NULL;
293
0
  rel->unique_for_rels = NIL;
294
0
  rel->non_unique_for_rels = NIL;
295
0
  rel->unique_rel = NULL;
296
0
  rel->unique_pathkeys = NIL;
297
0
  rel->unique_groupclause = NIL;
298
0
  rel->baserestrictinfo = NIL;
299
0
  rel->baserestrictcost.startup = 0;
300
0
  rel->baserestrictcost.per_tuple = 0;
301
0
  rel->baserestrict_min_security = UINT_MAX;
302
0
  rel->joininfo = NIL;
303
0
  rel->has_eclass_joins = false;
304
0
  rel->consider_partitionwise_join = false;  /* might get changed later */
305
0
  rel->agg_info = NULL;
306
0
  rel->grouped_rel = NULL;
307
0
  rel->part_scheme = NULL;
308
0
  rel->nparts = -1;
309
0
  rel->boundinfo = NULL;
310
0
  rel->partbounds_merged = false;
311
0
  rel->partition_qual = NIL;
312
0
  rel->part_rels = NULL;
313
0
  rel->live_parts = NULL;
314
0
  rel->all_partrels = NULL;
315
0
  rel->partexprs = NULL;
316
0
  rel->nullable_partexprs = NULL;
317
318
  /*
319
   * Pass assorted information down the inheritance hierarchy.
320
   */
321
0
  if (parent)
322
0
  {
323
    /* We keep back-links to immediate parent and topmost parent. */
324
0
    rel->parent = parent;
325
0
    rel->top_parent = parent->top_parent ? parent->top_parent : parent;
326
0
    rel->top_parent_relids = rel->top_parent->relids;
327
328
    /*
329
     * A child rel is below the same outer joins as its parent.  (We
330
     * presume this info was already calculated for the parent.)
331
     */
332
0
    rel->nulling_relids = parent->nulling_relids;
333
334
    /*
335
     * Also propagate lateral-reference information from appendrel parent
336
     * rels to their child rels.  We intentionally give each child rel the
337
     * same minimum parameterization, even though it's quite possible that
338
     * some don't reference all the lateral rels.  This is because any
339
     * append path for the parent will have to have the same
340
     * parameterization for every child anyway, and there's no value in
341
     * forcing extra reparameterize_path() calls.  Similarly, a lateral
342
     * reference to the parent prevents use of otherwise-movable join rels
343
     * for each child.
344
     *
345
     * It's possible for child rels to have their own children, in which
346
     * case the topmost parent's lateral info propagates all the way down.
347
     */
348
0
    rel->direct_lateral_relids = parent->direct_lateral_relids;
349
0
    rel->lateral_relids = parent->lateral_relids;
350
0
    rel->lateral_referencers = parent->lateral_referencers;
351
0
  }
352
0
  else
353
0
  {
354
0
    rel->parent = NULL;
355
0
    rel->top_parent = NULL;
356
0
    rel->top_parent_relids = NULL;
357
0
    rel->nulling_relids = NULL;
358
0
    rel->direct_lateral_relids = NULL;
359
0
    rel->lateral_relids = NULL;
360
0
    rel->lateral_referencers = NULL;
361
0
  }
362
363
  /* Check type of rtable entry */
364
0
  switch (rte->rtekind)
365
0
  {
366
0
    case RTE_RELATION:
367
      /* Table --- retrieve statistics from the system catalogs */
368
0
      get_relation_info(root, rte->relid, rte->inh, rel);
369
0
      break;
370
0
    case RTE_SUBQUERY:
371
0
    case RTE_FUNCTION:
372
0
    case RTE_TABLEFUNC:
373
0
    case RTE_VALUES:
374
0
    case RTE_CTE:
375
0
    case RTE_NAMEDTUPLESTORE:
376
377
      /*
378
       * Subquery, function, tablefunc, values list, CTE, or ENR --- set
379
       * up attr range and arrays
380
       *
381
       * Note: 0 is included in range to support whole-row Vars
382
       */
383
0
      rel->min_attr = 0;
384
0
      rel->max_attr = list_length(rte->eref->colnames);
385
0
      rel->attr_needed = (Relids *)
386
0
        palloc0_array(Relids, rel->max_attr - rel->min_attr + 1);
387
0
      rel->attr_widths = (int32 *)
388
0
        palloc0_array(int32, rel->max_attr - rel->min_attr + 1);
389
0
      break;
390
0
    case RTE_RESULT:
391
      /* RTE_RESULT has no columns, nor could it have whole-row Var */
392
0
      rel->min_attr = 0;
393
0
      rel->max_attr = -1;
394
0
      rel->attr_needed = NULL;
395
0
      rel->attr_widths = NULL;
396
0
      break;
397
0
    default:
398
0
      elog(ERROR, "unrecognized RTE kind: %d",
399
0
         (int) rte->rtekind);
400
0
      break;
401
0
  }
402
403
  /*
404
   * Allow a plugin to editorialize on the new RelOptInfo. This could
405
   * involve editorializing on the information which get_relation_info
406
   * obtained from the catalogs, such as altering the assumed relation size,
407
   * removing an index, or adding a hypothetical index to the indexlist.
408
   *
409
   * An extension can also modify rel->pgs_mask here to control path
410
   * generation.
411
   */
412
0
  if (build_simple_rel_hook)
413
0
    (*build_simple_rel_hook) (root, rel, rte);
414
415
  /*
416
   * Apply the parent's quals to the child, with appropriate substitution of
417
   * variables.  If any resulting clause is reduced to constant FALSE or
418
   * NULL, apply_child_basequals returns false to indicate that scanning
419
   * this relation won't yield any rows.  In this case, we mark the child as
420
   * dummy right away.  (We must do this immediately so that pruning works
421
   * correctly when recursing in expand_partitioned_rtentry.)
422
   */
423
0
  if (parent)
424
0
  {
425
0
    AppendRelInfo *appinfo = root->append_rel_array[relid];
426
427
0
    Assert(appinfo != NULL);
428
0
    if (!apply_child_basequals(root, parent, rel, rte, appinfo))
429
0
    {
430
      /*
431
       * A restriction clause reduced to constant FALSE or NULL after
432
       * substitution.  Mark the child as dummy so that it need not be
433
       * scanned.
434
       */
435
0
      mark_dummy_rel(rel);
436
0
    }
437
0
  }
438
439
  /* Save the finished struct in the query's simple_rel_array */
440
0
  root->simple_rel_array[relid] = rel;
441
442
0
  return rel;
443
0
}
444
445
/*
446
 * build_simple_grouped_rel
447
 *    Construct a new RelOptInfo representing a grouped version of the input
448
 *    simple relation.
449
 */
450
RelOptInfo *
451
build_simple_grouped_rel(PlannerInfo *root, RelOptInfo *rel)
452
0
{
453
0
  RelOptInfo *grouped_rel;
454
0
  RelAggInfo *agg_info;
455
456
  /*
457
   * We should have available aggregate expressions and grouping
458
   * expressions, otherwise we cannot reach here.
459
   */
460
0
  Assert(root->agg_clause_list != NIL);
461
0
  Assert(root->group_expr_list != NIL);
462
463
  /* nothing to do for dummy rel */
464
0
  if (IS_DUMMY_REL(rel))
465
0
    return NULL;
466
467
  /*
468
   * Prepare the information needed to create grouped paths for this simple
469
   * relation.
470
   */
471
0
  agg_info = create_rel_agg_info(root, rel, true);
472
0
  if (agg_info == NULL)
473
0
    return NULL;
474
475
  /*
476
   * If grouped paths for the given simple relation are not considered
477
   * useful, skip building the grouped relation.
478
   */
479
0
  if (!agg_info->agg_useful)
480
0
    return NULL;
481
482
  /* Track the set of relids at which partial aggregation is applied */
483
0
  agg_info->apply_agg_at = bms_copy(rel->relids);
484
485
  /* build the grouped relation */
486
0
  grouped_rel = build_grouped_rel(root, rel);
487
0
  grouped_rel->reltarget = agg_info->target;
488
0
  grouped_rel->rows = agg_info->grouped_rows;
489
0
  grouped_rel->agg_info = agg_info;
490
491
0
  rel->grouped_rel = grouped_rel;
492
493
0
  return grouped_rel;
494
0
}
495
496
/*
497
 * build_grouped_rel
498
 *    Build a grouped relation by flat copying the input relation and resetting
499
 *    the necessary fields.
500
 */
501
RelOptInfo *
502
build_grouped_rel(PlannerInfo *root, RelOptInfo *rel)
503
0
{
504
0
  RelOptInfo *grouped_rel;
505
506
0
  grouped_rel = makeNode(RelOptInfo);
507
0
  memcpy(grouped_rel, rel, sizeof(RelOptInfo));
508
509
  /*
510
   * clear path info
511
   */
512
0
  grouped_rel->pathlist = NIL;
513
0
  grouped_rel->ppilist = NIL;
514
0
  grouped_rel->partial_pathlist = NIL;
515
0
  grouped_rel->cheapest_startup_path = NULL;
516
0
  grouped_rel->cheapest_total_path = NULL;
517
0
  grouped_rel->cheapest_parameterized_paths = NIL;
518
519
  /*
520
   * clear partition info
521
   */
522
0
  grouped_rel->part_scheme = NULL;
523
0
  grouped_rel->nparts = -1;
524
0
  grouped_rel->boundinfo = NULL;
525
0
  grouped_rel->partbounds_merged = false;
526
0
  grouped_rel->partition_qual = NIL;
527
0
  grouped_rel->part_rels = NULL;
528
0
  grouped_rel->live_parts = NULL;
529
0
  grouped_rel->all_partrels = NULL;
530
0
  grouped_rel->partexprs = NULL;
531
0
  grouped_rel->nullable_partexprs = NULL;
532
0
  grouped_rel->consider_partitionwise_join = false;
533
534
  /*
535
   * clear FDW info; FDWs don't know how to handle grouped relations
536
   */
537
0
  grouped_rel->serverid = InvalidOid;
538
0
  grouped_rel->fdwroutine = NULL;
539
0
  grouped_rel->fdw_private = NULL;
540
541
  /*
542
   * clear size estimates
543
   */
544
0
  grouped_rel->rows = 0;
545
546
0
  return grouped_rel;
547
0
}
548
549
/*
550
 * find_base_rel
551
 *    Find a base or otherrel relation entry, which must already exist.
552
 */
553
RelOptInfo *
554
find_base_rel(PlannerInfo *root, int relid)
555
0
{
556
0
  RelOptInfo *rel;
557
558
  /* use an unsigned comparison to prevent negative array element access */
559
0
  if ((uint32) relid < (uint32) root->simple_rel_array_size)
560
0
  {
561
0
    rel = root->simple_rel_array[relid];
562
0
    if (rel)
563
0
      return rel;
564
0
  }
565
566
0
  elog(ERROR, "no relation entry for relid %d", relid);
567
568
0
  return NULL;       /* keep compiler quiet */
569
0
}
570
571
/*
572
 * find_base_rel_noerr
573
 *    Find a base or otherrel relation entry, returning NULL if there's none
574
 */
575
RelOptInfo *
576
find_base_rel_noerr(PlannerInfo *root, int relid)
577
0
{
578
  /* use an unsigned comparison to prevent negative array element access */
579
0
  if ((uint32) relid < (uint32) root->simple_rel_array_size)
580
0
    return root->simple_rel_array[relid];
581
0
  return NULL;
582
0
}
583
584
/*
585
 * find_base_rel_ignore_join
586
 *    Find a base or otherrel relation entry, which must already exist.
587
 *
588
 * Unlike find_base_rel, if relid references an outer join then this
589
 * will return NULL rather than raising an error.  This is convenient
590
 * for callers that must deal with relid sets including both base and
591
 * outer joins.
592
 */
593
RelOptInfo *
594
find_base_rel_ignore_join(PlannerInfo *root, int relid)
595
0
{
596
  /* use an unsigned comparison to prevent negative array element access */
597
0
  if ((uint32) relid < (uint32) root->simple_rel_array_size)
598
0
  {
599
0
    RelOptInfo *rel;
600
0
    RangeTblEntry *rte;
601
602
0
    rel = root->simple_rel_array[relid];
603
0
    if (rel)
604
0
      return rel;
605
606
    /*
607
     * We could just return NULL here, but for debugging purposes it seems
608
     * best to actually verify that the relid is an outer join and not
609
     * something weird.
610
     */
611
0
    rte = root->simple_rte_array[relid];
612
0
    if (rte && rte->rtekind == RTE_JOIN && rte->jointype != JOIN_INNER)
613
0
      return NULL;
614
0
  }
615
616
0
  elog(ERROR, "no relation entry for relid %d", relid);
617
618
0
  return NULL;       /* keep compiler quiet */
619
0
}
620
621
/*
622
 * build_join_rel_hash
623
 *    Construct the auxiliary hash table for join relations.
624
 */
625
static void
626
build_join_rel_hash(PlannerInfo *root)
627
0
{
628
0
  HTAB     *hashtab;
629
0
  HASHCTL   hash_ctl;
630
0
  ListCell   *l;
631
632
  /* Create the hash table */
633
0
  hash_ctl.keysize = sizeof(Relids);
634
0
  hash_ctl.entrysize = sizeof(JoinHashEntry);
635
0
  hash_ctl.hash = bitmap_hash;
636
0
  hash_ctl.match = bitmap_match;
637
0
  hash_ctl.hcxt = CurrentMemoryContext;
638
0
  hashtab = hash_create("JoinRelHashTable",
639
0
              256L,
640
0
              &hash_ctl,
641
0
              HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
642
643
  /* Insert all the already-existing joinrels */
644
0
  foreach(l, root->join_rel_list)
645
0
  {
646
0
    RelOptInfo *rel = (RelOptInfo *) lfirst(l);
647
0
    JoinHashEntry *hentry;
648
0
    bool    found;
649
650
0
    hentry = (JoinHashEntry *) hash_search(hashtab,
651
0
                         &(rel->relids),
652
0
                         HASH_ENTER,
653
0
                         &found);
654
0
    Assert(!found);
655
0
    hentry->join_rel = rel;
656
0
  }
657
658
0
  root->join_rel_hash = hashtab;
659
0
}
660
661
/*
662
 * find_join_rel
663
 *    Returns relation entry corresponding to 'relids' (a set of RT indexes),
664
 *    or NULL if none exists.  This is for join relations.
665
 */
666
RelOptInfo *
667
find_join_rel(PlannerInfo *root, Relids relids)
668
0
{
669
  /*
670
   * Switch to using hash lookup when list grows "too long".  The threshold
671
   * is arbitrary and is known only here.
672
   */
673
0
  if (!root->join_rel_hash && list_length(root->join_rel_list) > 32)
674
0
    build_join_rel_hash(root);
675
676
  /*
677
   * Use either hashtable lookup or linear search, as appropriate.
678
   *
679
   * Note: the seemingly redundant hashkey variable is used to avoid taking
680
   * the address of relids; unless the compiler is exceedingly smart, doing
681
   * so would force relids out of a register and thus probably slow down the
682
   * list-search case.
683
   */
684
0
  if (root->join_rel_hash)
685
0
  {
686
0
    Relids    hashkey = relids;
687
0
    JoinHashEntry *hentry;
688
689
0
    hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
690
0
                         &hashkey,
691
0
                         HASH_FIND,
692
0
                         NULL);
693
0
    if (hentry)
694
0
      return hentry->join_rel;
695
0
  }
696
0
  else
697
0
  {
698
0
    ListCell   *l;
699
700
0
    foreach(l, root->join_rel_list)
701
0
    {
702
0
      RelOptInfo *rel = (RelOptInfo *) lfirst(l);
703
704
0
      if (bms_equal(rel->relids, relids))
705
0
        return rel;
706
0
    }
707
0
  }
708
709
0
  return NULL;
710
0
}
711
712
/*
713
 * set_foreign_rel_properties
714
 *    Set up foreign-join fields if outer and inner relation are foreign
715
 *    tables (or joins) belonging to the same server and assigned to the same
716
 *    user to check access permissions as.
717
 *
718
 * In addition to an exact match of userid, we allow the case where one side
719
 * has zero userid (implying current user) and the other side has explicit
720
 * userid that happens to equal the current user; but in that case, pushdown of
721
 * the join is only valid for the current user.  The useridiscurrent field
722
 * records whether we had to make such an assumption for this join or any
723
 * sub-join.
724
 *
725
 * Otherwise these fields are left invalid, so GetForeignJoinPaths will not be
726
 * called for the join relation.
727
 */
728
static void
729
set_foreign_rel_properties(RelOptInfo *joinrel, RelOptInfo *outer_rel,
730
               RelOptInfo *inner_rel)
731
0
{
732
0
  if (OidIsValid(outer_rel->serverid) &&
733
0
    inner_rel->serverid == outer_rel->serverid)
734
0
  {
735
0
    if (inner_rel->userid == outer_rel->userid)
736
0
    {
737
0
      joinrel->serverid = outer_rel->serverid;
738
0
      joinrel->userid = outer_rel->userid;
739
0
      joinrel->useridiscurrent = outer_rel->useridiscurrent || inner_rel->useridiscurrent;
740
0
      joinrel->fdwroutine = outer_rel->fdwroutine;
741
0
    }
742
0
    else if (!OidIsValid(inner_rel->userid) &&
743
0
         outer_rel->userid == GetUserId())
744
0
    {
745
0
      joinrel->serverid = outer_rel->serverid;
746
0
      joinrel->userid = outer_rel->userid;
747
0
      joinrel->useridiscurrent = true;
748
0
      joinrel->fdwroutine = outer_rel->fdwroutine;
749
0
    }
750
0
    else if (!OidIsValid(outer_rel->userid) &&
751
0
         inner_rel->userid == GetUserId())
752
0
    {
753
0
      joinrel->serverid = outer_rel->serverid;
754
0
      joinrel->userid = inner_rel->userid;
755
0
      joinrel->useridiscurrent = true;
756
0
      joinrel->fdwroutine = outer_rel->fdwroutine;
757
0
    }
758
0
  }
759
0
  else if (OidIsValid(outer_rel->serverid) &&
760
0
       inner_rel->rtekind == RTE_FUNCTION)
761
0
  {
762
    /*
763
     * One side is a foreign relation, the other side is a function RTE.
764
     * If the function is IMMUTABLE, the FDW can absorb the function call
765
     * into the remote query (the result is identical regardless of which
766
     * server evaluates it).  Let the FDW decide whether the join is
767
     * actually shippable; here we just propagate the FDW routine so the
768
     * FDW gets a chance.
769
     */
770
0
    joinrel->serverid = outer_rel->serverid;
771
0
    joinrel->userid = outer_rel->userid;
772
0
    joinrel->useridiscurrent = outer_rel->useridiscurrent;
773
0
    joinrel->fdwroutine = outer_rel->fdwroutine;
774
0
  }
775
0
  else if (OidIsValid(inner_rel->serverid) &&
776
0
       outer_rel->rtekind == RTE_FUNCTION)
777
0
  {
778
    /* Same as just above, with the two sides swapped. */
779
0
    joinrel->serverid = inner_rel->serverid;
780
0
    joinrel->userid = inner_rel->userid;
781
0
    joinrel->useridiscurrent = inner_rel->useridiscurrent;
782
0
    joinrel->fdwroutine = inner_rel->fdwroutine;
783
0
  }
784
0
}
785
786
/*
787
 * add_join_rel
788
 *    Add given join relation to the list of join relations in the given
789
 *    PlannerInfo. Also add it to the auxiliary hashtable if there is one.
790
 */
791
static void
792
add_join_rel(PlannerInfo *root, RelOptInfo *joinrel)
793
0
{
794
  /* GEQO requires us to append the new joinrel to the end of the list! */
795
0
  root->join_rel_list = lappend(root->join_rel_list, joinrel);
796
797
  /* store it into the auxiliary hashtable if there is one. */
798
0
  if (root->join_rel_hash)
799
0
  {
800
0
    JoinHashEntry *hentry;
801
0
    bool    found;
802
803
0
    hentry = (JoinHashEntry *) hash_search(root->join_rel_hash,
804
0
                         &(joinrel->relids),
805
0
                         HASH_ENTER,
806
0
                         &found);
807
0
    Assert(!found);
808
0
    hentry->join_rel = joinrel;
809
0
  }
810
0
}
811
812
/*
813
 * build_join_rel
814
 *    Returns relation entry corresponding to the union of two given rels,
815
 *    creating a new relation entry if none already exists.
816
 *
817
 * 'joinrelids' is the Relids set that uniquely identifies the join
818
 * 'outer_rel' and 'inner_rel' are relation nodes for the relations to be
819
 *    joined
820
 * 'sjinfo': join context info
821
 * 'pushed_down_joins': any pushed-down outer joins that are now completed
822
 * 'restrictlist_ptr': result variable.  If not NULL, *restrictlist_ptr
823
 *    receives the list of RestrictInfo nodes that apply to this
824
 *    particular pair of joinable relations.
825
 *
826
 * restrictlist_ptr makes the routine's API a little grotty, but it saves
827
 * duplicated calculation of the restrictlist...
828
 */
829
RelOptInfo *
830
build_join_rel(PlannerInfo *root,
831
         Relids joinrelids,
832
         RelOptInfo *outer_rel,
833
         RelOptInfo *inner_rel,
834
         SpecialJoinInfo *sjinfo,
835
         List *pushed_down_joins,
836
         List **restrictlist_ptr)
837
0
{
838
0
  RelOptInfo *joinrel;
839
0
  List     *restrictlist;
840
841
  /* This function should be used only for join between parents. */
842
0
  Assert(!IS_OTHER_REL(outer_rel) && !IS_OTHER_REL(inner_rel));
843
844
  /*
845
   * See if we already have a joinrel for this set of base rels.
846
   */
847
0
  joinrel = find_join_rel(root, joinrelids);
848
849
0
  if (joinrel)
850
0
  {
851
    /*
852
     * Yes, so we only need to figure the restrictlist for this particular
853
     * pair of component relations.
854
     */
855
0
    if (restrictlist_ptr)
856
0
      *restrictlist_ptr = build_joinrel_restrictlist(root,
857
0
                               joinrel,
858
0
                               outer_rel,
859
0
                               inner_rel,
860
0
                               sjinfo);
861
0
    return joinrel;
862
0
  }
863
864
  /*
865
   * Nope, so make one.
866
   */
867
0
  joinrel = makeNode(RelOptInfo);
868
0
  joinrel->reloptkind = RELOPT_JOINREL;
869
0
  joinrel->relids = bms_copy(joinrelids);
870
0
  joinrel->rows = 0;
871
  /* cheap startup cost is interesting iff not all tuples to be retrieved */
872
0
  joinrel->consider_startup = (root->tuple_fraction > 0);
873
0
  joinrel->consider_param_startup = false;
874
0
  joinrel->consider_parallel = false;
875
0
  joinrel->pgs_mask = root->glob->default_pgs_mask;
876
0
  joinrel->reltarget = create_empty_pathtarget();
877
0
  joinrel->pathlist = NIL;
878
0
  joinrel->ppilist = NIL;
879
0
  joinrel->partial_pathlist = NIL;
880
0
  joinrel->cheapest_startup_path = NULL;
881
0
  joinrel->cheapest_total_path = NULL;
882
0
  joinrel->cheapest_parameterized_paths = NIL;
883
  /* init direct_lateral_relids from children; we'll finish it up below */
884
0
  joinrel->direct_lateral_relids =
885
0
    bms_union(outer_rel->direct_lateral_relids,
886
0
          inner_rel->direct_lateral_relids);
887
0
  joinrel->lateral_relids = min_join_parameterization(root, joinrel->relids,
888
0
                            outer_rel, inner_rel);
889
0
  joinrel->relid = 0;     /* indicates not a baserel */
890
0
  joinrel->rtekind = RTE_JOIN;
891
0
  joinrel->min_attr = 0;
892
0
  joinrel->max_attr = 0;
893
0
  joinrel->attr_needed = NULL;
894
0
  joinrel->attr_widths = NULL;
895
0
  joinrel->notnullattnums = NULL;
896
0
  joinrel->nulling_relids = NULL;
897
0
  joinrel->lateral_vars = NIL;
898
0
  joinrel->lateral_referencers = NULL;
899
0
  joinrel->indexlist = NIL;
900
0
  joinrel->statlist = NIL;
901
0
  joinrel->pages = 0;
902
0
  joinrel->tuples = 0;
903
0
  joinrel->allvisfrac = 0;
904
0
  joinrel->eclass_indexes = NULL;
905
0
  joinrel->subroot = NULL;
906
0
  joinrel->subplan_params = NIL;
907
0
  joinrel->rel_parallel_workers = -1;
908
0
  joinrel->amflags = 0;
909
0
  joinrel->serverid = InvalidOid;
910
0
  joinrel->userid = InvalidOid;
911
0
  joinrel->useridiscurrent = false;
912
0
  joinrel->fdwroutine = NULL;
913
0
  joinrel->fdw_private = NULL;
914
0
  joinrel->unique_for_rels = NIL;
915
0
  joinrel->non_unique_for_rels = NIL;
916
0
  joinrel->unique_rel = NULL;
917
0
  joinrel->unique_pathkeys = NIL;
918
0
  joinrel->unique_groupclause = NIL;
919
0
  joinrel->baserestrictinfo = NIL;
920
0
  joinrel->baserestrictcost.startup = 0;
921
0
  joinrel->baserestrictcost.per_tuple = 0;
922
0
  joinrel->baserestrict_min_security = UINT_MAX;
923
0
  joinrel->joininfo = NIL;
924
0
  joinrel->has_eclass_joins = false;
925
0
  joinrel->consider_partitionwise_join = false;  /* might get changed later */
926
0
  joinrel->agg_info = NULL;
927
0
  joinrel->grouped_rel = NULL;
928
0
  joinrel->parent = NULL;
929
0
  joinrel->top_parent = NULL;
930
0
  joinrel->top_parent_relids = NULL;
931
0
  joinrel->part_scheme = NULL;
932
0
  joinrel->nparts = -1;
933
0
  joinrel->boundinfo = NULL;
934
0
  joinrel->partbounds_merged = false;
935
0
  joinrel->partition_qual = NIL;
936
0
  joinrel->part_rels = NULL;
937
0
  joinrel->live_parts = NULL;
938
0
  joinrel->all_partrels = NULL;
939
0
  joinrel->partexprs = NULL;
940
0
  joinrel->nullable_partexprs = NULL;
941
942
  /* Compute information relevant to the foreign relations. */
943
0
  set_foreign_rel_properties(joinrel, outer_rel, inner_rel);
944
945
  /*
946
   * Fill the joinrel's tlist with just the Vars and PHVs that need to be
947
   * output from this join (ie, are needed for higher joinclauses or final
948
   * output).
949
   *
950
   * NOTE: the tlist order for a join rel will depend on which pair of outer
951
   * and inner rels we first try to build it from.  But the contents should
952
   * be the same regardless.
953
   */
954
0
  build_joinrel_tlist(root, joinrel, outer_rel, sjinfo, pushed_down_joins,
955
0
            (sjinfo->jointype == JOIN_FULL));
956
0
  build_joinrel_tlist(root, joinrel, inner_rel, sjinfo, pushed_down_joins,
957
0
            (sjinfo->jointype != JOIN_INNER));
958
0
  add_placeholders_to_joinrel(root, joinrel, outer_rel, inner_rel, sjinfo);
959
960
  /*
961
   * add_placeholders_to_joinrel also took care of adding the ph_lateral
962
   * sets of any PlaceHolderVars computed here to direct_lateral_relids, so
963
   * now we can finish computing that.  This is much like the computation of
964
   * the transitively-closed lateral_relids in min_join_parameterization,
965
   * except that here we *do* have to consider the added PHVs.
966
   */
967
0
  joinrel->direct_lateral_relids =
968
0
    bms_del_members(joinrel->direct_lateral_relids, joinrel->relids);
969
970
  /*
971
   * Construct restrict and join clause lists for the new joinrel. (The
972
   * caller might or might not need the restrictlist, but I need it anyway
973
   * for set_joinrel_size_estimates().)
974
   */
975
0
  restrictlist = build_joinrel_restrictlist(root, joinrel,
976
0
                        outer_rel, inner_rel,
977
0
                        sjinfo);
978
0
  if (restrictlist_ptr)
979
0
    *restrictlist_ptr = restrictlist;
980
0
  build_joinrel_joinlist(joinrel, outer_rel, inner_rel);
981
982
  /*
983
   * This is also the right place to check whether the joinrel has any
984
   * pending EquivalenceClass joins.
985
   */
986
0
  joinrel->has_eclass_joins = has_relevant_eclass_joinclause(root, joinrel);
987
988
  /*
989
   * Set estimates of the joinrel's size.
990
   */
991
0
  set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
992
0
                 sjinfo, restrictlist);
993
994
  /*
995
   * Set the consider_parallel flag if this joinrel could potentially be
996
   * scanned within a parallel worker.  If this flag is false for either
997
   * inner_rel or outer_rel, then it must be false for the joinrel also.
998
   * Even if both are true, there might be parallel-restricted expressions
999
   * in the targetlist or quals.
1000
   *
1001
   * Note that if there are more than two rels in this relation, they could
1002
   * be divided between inner_rel and outer_rel in any arbitrary way.  We
1003
   * assume this doesn't matter, because we should hit all the same baserels
1004
   * and joinclauses while building up to this joinrel no matter which we
1005
   * take; therefore, we should make the same decision here however we get
1006
   * here.
1007
   */
1008
0
  if (inner_rel->consider_parallel && outer_rel->consider_parallel &&
1009
0
    is_parallel_safe(root, (Node *) restrictlist) &&
1010
0
    is_parallel_safe(root, (Node *) joinrel->reltarget->exprs))
1011
0
    joinrel->consider_parallel = true;
1012
1013
  /*
1014
   * Allow a plugin to editorialize on the new joinrel's properties. Actions
1015
   * might include altering the size estimate, clearing consider_parallel,
1016
   * or adjusting pgs_mask.
1017
   */
1018
0
  if (joinrel_setup_hook)
1019
0
    (*joinrel_setup_hook) (root, joinrel, outer_rel, inner_rel, sjinfo,
1020
0
                 restrictlist);
1021
1022
  /* Store the partition information. */
1023
0
  build_joinrel_partition_info(root, joinrel, outer_rel, inner_rel, sjinfo,
1024
0
                 restrictlist);
1025
1026
  /* Add the joinrel to the PlannerInfo. */
1027
0
  add_join_rel(root, joinrel);
1028
1029
  /*
1030
   * Also, if dynamic-programming join search is active, add the new joinrel
1031
   * to the appropriate sublist.  Note: you might think the Assert on number
1032
   * of members should be for equality, but some of the level 1 rels might
1033
   * have been joinrels already, so we can only assert <=.
1034
   */
1035
0
  if (root->join_rel_level)
1036
0
  {
1037
0
    Assert(root->join_cur_level > 0);
1038
0
    Assert(root->join_cur_level <= bms_num_members(joinrel->relids));
1039
0
    root->join_rel_level[root->join_cur_level] =
1040
0
      lappend(root->join_rel_level[root->join_cur_level], joinrel);
1041
0
  }
1042
1043
0
  return joinrel;
1044
0
}
1045
1046
/*
1047
 * build_child_join_rel
1048
 *    Builds RelOptInfo representing join between given two child relations.
1049
 *
1050
 * 'outer_rel' and 'inner_rel' are the RelOptInfos of child relations being
1051
 *    joined
1052
 * 'parent_joinrel' is the RelOptInfo representing the join between parent
1053
 *    relations. Some of the members of new RelOptInfo are produced by
1054
 *    translating corresponding members of this RelOptInfo
1055
 * 'restrictlist': list of RestrictInfo nodes that apply to this particular
1056
 *    pair of joinable relations
1057
 * 'sjinfo': child join's join-type details
1058
 * 'nappinfos' and 'appinfos': AppendRelInfo array for child relids
1059
 */
1060
RelOptInfo *
1061
build_child_join_rel(PlannerInfo *root, RelOptInfo *outer_rel,
1062
           RelOptInfo *inner_rel, RelOptInfo *parent_joinrel,
1063
           List *restrictlist, SpecialJoinInfo *sjinfo,
1064
           int nappinfos, AppendRelInfo **appinfos)
1065
0
{
1066
0
  RelOptInfo *joinrel = makeNode(RelOptInfo);
1067
1068
  /* Only joins between "other" relations land here. */
1069
0
  Assert(IS_OTHER_REL(outer_rel) && IS_OTHER_REL(inner_rel));
1070
1071
  /* The parent joinrel should have consider_partitionwise_join set. */
1072
0
  Assert(parent_joinrel->consider_partitionwise_join);
1073
1074
0
  joinrel->reloptkind = RELOPT_OTHER_JOINREL;
1075
0
  joinrel->relids = adjust_child_relids(parent_joinrel->relids,
1076
0
                      nappinfos, appinfos);
1077
0
  joinrel->rows = 0;
1078
  /* cheap startup cost is interesting iff not all tuples to be retrieved */
1079
0
  joinrel->consider_startup = (root->tuple_fraction > 0);
1080
0
  joinrel->consider_param_startup = false;
1081
0
  joinrel->consider_parallel = false;
1082
0
  joinrel->pgs_mask = root->glob->default_pgs_mask;
1083
0
  joinrel->reltarget = create_empty_pathtarget();
1084
0
  joinrel->pathlist = NIL;
1085
0
  joinrel->ppilist = NIL;
1086
0
  joinrel->partial_pathlist = NIL;
1087
0
  joinrel->cheapest_startup_path = NULL;
1088
0
  joinrel->cheapest_total_path = NULL;
1089
0
  joinrel->cheapest_parameterized_paths = NIL;
1090
0
  joinrel->direct_lateral_relids = NULL;
1091
0
  joinrel->lateral_relids = NULL;
1092
0
  joinrel->relid = 0;     /* indicates not a baserel */
1093
0
  joinrel->rtekind = RTE_JOIN;
1094
0
  joinrel->min_attr = 0;
1095
0
  joinrel->max_attr = 0;
1096
0
  joinrel->attr_needed = NULL;
1097
0
  joinrel->attr_widths = NULL;
1098
0
  joinrel->notnullattnums = NULL;
1099
0
  joinrel->nulling_relids = NULL;
1100
0
  joinrel->lateral_vars = NIL;
1101
0
  joinrel->lateral_referencers = NULL;
1102
0
  joinrel->indexlist = NIL;
1103
0
  joinrel->pages = 0;
1104
0
  joinrel->tuples = 0;
1105
0
  joinrel->allvisfrac = 0;
1106
0
  joinrel->eclass_indexes = NULL;
1107
0
  joinrel->subroot = NULL;
1108
0
  joinrel->subplan_params = NIL;
1109
0
  joinrel->amflags = 0;
1110
0
  joinrel->serverid = InvalidOid;
1111
0
  joinrel->userid = InvalidOid;
1112
0
  joinrel->useridiscurrent = false;
1113
0
  joinrel->fdwroutine = NULL;
1114
0
  joinrel->fdw_private = NULL;
1115
0
  joinrel->unique_rel = NULL;
1116
0
  joinrel->unique_pathkeys = NIL;
1117
0
  joinrel->unique_groupclause = NIL;
1118
0
  joinrel->baserestrictinfo = NIL;
1119
0
  joinrel->baserestrictcost.startup = 0;
1120
0
  joinrel->baserestrictcost.per_tuple = 0;
1121
0
  joinrel->joininfo = NIL;
1122
0
  joinrel->has_eclass_joins = false;
1123
0
  joinrel->consider_partitionwise_join = false;  /* might get changed later */
1124
0
  joinrel->agg_info = NULL;
1125
0
  joinrel->grouped_rel = NULL;
1126
0
  joinrel->parent = parent_joinrel;
1127
0
  joinrel->top_parent = parent_joinrel->top_parent ? parent_joinrel->top_parent : parent_joinrel;
1128
0
  joinrel->top_parent_relids = joinrel->top_parent->relids;
1129
0
  joinrel->part_scheme = NULL;
1130
0
  joinrel->nparts = -1;
1131
0
  joinrel->boundinfo = NULL;
1132
0
  joinrel->partbounds_merged = false;
1133
0
  joinrel->partition_qual = NIL;
1134
0
  joinrel->part_rels = NULL;
1135
0
  joinrel->live_parts = NULL;
1136
0
  joinrel->all_partrels = NULL;
1137
0
  joinrel->partexprs = NULL;
1138
0
  joinrel->nullable_partexprs = NULL;
1139
1140
  /* Compute information relevant to foreign relations. */
1141
0
  set_foreign_rel_properties(joinrel, outer_rel, inner_rel);
1142
1143
  /* Set up reltarget struct */
1144
0
  build_child_join_reltarget(root, parent_joinrel, joinrel,
1145
0
                 nappinfos, appinfos);
1146
1147
  /* Construct joininfo list. */
1148
0
  joinrel->joininfo = (List *) adjust_appendrel_attrs(root,
1149
0
                            (Node *) parent_joinrel->joininfo,
1150
0
                            nappinfos,
1151
0
                            appinfos);
1152
1153
  /*
1154
   * Lateral relids referred in child join will be same as that referred in
1155
   * the parent relation.
1156
   */
1157
0
  joinrel->direct_lateral_relids = (Relids) bms_copy(parent_joinrel->direct_lateral_relids);
1158
0
  joinrel->lateral_relids = (Relids) bms_copy(parent_joinrel->lateral_relids);
1159
1160
  /*
1161
   * If the parent joinrel has pending equivalence classes, so does the
1162
   * child.
1163
   */
1164
0
  joinrel->has_eclass_joins = parent_joinrel->has_eclass_joins;
1165
1166
  /* Child joinrel is parallel safe if parent is parallel safe. */
1167
0
  joinrel->consider_parallel = parent_joinrel->consider_parallel;
1168
1169
  /* Set estimates of the child-joinrel's size. */
1170
0
  set_joinrel_size_estimates(root, joinrel, outer_rel, inner_rel,
1171
0
                 sjinfo, restrictlist);
1172
1173
  /*
1174
   * Allow a plugin to editorialize on the new joinrel's properties. Actions
1175
   * might include altering the size estimate, clearing consider_parallel,
1176
   * or adjusting pgs_mask. (However, note that clearing consider_parallel
1177
   * would be better done in the parent joinrel rather than here.)
1178
   */
1179
0
  if (joinrel_setup_hook)
1180
0
    (*joinrel_setup_hook) (root, joinrel, outer_rel, inner_rel, sjinfo,
1181
0
                 restrictlist);
1182
1183
  /* Is the join between partitions itself partitioned? */
1184
0
  build_joinrel_partition_info(root, joinrel, outer_rel, inner_rel, sjinfo,
1185
0
                 restrictlist);
1186
1187
  /* We build the join only once. */
1188
0
  Assert(!find_join_rel(root, joinrel->relids));
1189
1190
  /* Add the relation to the PlannerInfo. */
1191
0
  add_join_rel(root, joinrel);
1192
1193
  /*
1194
   * We might need EquivalenceClass members corresponding to the child join,
1195
   * so that we can represent sort pathkeys for it.  As with children of
1196
   * baserels, we shouldn't need this unless there are relevant eclass joins
1197
   * (implying that a merge join might be possible) or pathkeys to sort by.
1198
   */
1199
0
  if (joinrel->has_eclass_joins || has_useful_pathkeys(root, parent_joinrel))
1200
0
    add_child_join_rel_equivalences(root,
1201
0
                    nappinfos, appinfos,
1202
0
                    parent_joinrel, joinrel);
1203
1204
0
  return joinrel;
1205
0
}
1206
1207
/*
1208
 * min_join_parameterization
1209
 *
1210
 * Determine the minimum possible parameterization of a joinrel, that is, the
1211
 * set of other rels it contains LATERAL references to.  We save this value in
1212
 * the join's RelOptInfo.  This function is split out of build_join_rel()
1213
 * because join_is_legal() needs the value to check a prospective join.
1214
 */
1215
Relids
1216
min_join_parameterization(PlannerInfo *root,
1217
              Relids joinrelids,
1218
              RelOptInfo *outer_rel,
1219
              RelOptInfo *inner_rel)
1220
0
{
1221
0
  Relids    result;
1222
1223
  /*
1224
   * Basically we just need the union of the inputs' lateral_relids, less
1225
   * whatever is already in the join.
1226
   *
1227
   * It's not immediately obvious that this is a valid way to compute the
1228
   * result, because it might seem that we're ignoring possible lateral refs
1229
   * of PlaceHolderVars that are due to be computed at the join but not in
1230
   * either input.  However, because create_lateral_join_info() already
1231
   * charged all such PHV refs to each member baserel of the join, they'll
1232
   * be accounted for already in the inputs' lateral_relids.  Likewise, we
1233
   * do not need to worry about doing transitive closure here, because that
1234
   * was already accounted for in the original baserel lateral_relids.
1235
   */
1236
0
  result = bms_union(outer_rel->lateral_relids, inner_rel->lateral_relids);
1237
0
  result = bms_del_members(result, joinrelids);
1238
0
  return result;
1239
0
}
1240
1241
/*
1242
 * build_joinrel_tlist
1243
 *    Builds a join relation's target list from an input relation.
1244
 *    (This is invoked twice to handle the two input relations.)
1245
 *
1246
 * The join's targetlist includes all Vars of its member relations that
1247
 * will still be needed above the join.  This subroutine adds all such
1248
 * Vars from the specified input rel's tlist to the join rel's tlist.
1249
 * Likewise for any PlaceHolderVars emitted by the input rel.
1250
 *
1251
 * We also compute the expected width of the join's output, making use
1252
 * of data that was cached at the baserel level by set_rel_width().
1253
 *
1254
 * Pass can_null as true if the join is an outer join that can null Vars
1255
 * from this input relation.  If so, we will (normally) add the join's relid
1256
 * to the nulling bitmaps of Vars and PHVs bubbled up from the input.
1257
 *
1258
 * When forming an outer join's target list, special handling is needed in
1259
 * case the outer join was commuted with another one per outer join identity 3
1260
 * (see optimizer/README).  We must take steps to ensure that the output Vars
1261
 * have the same nulling bitmaps that they would if the two joins had been
1262
 * done in syntactic order; else they won't match Vars appearing higher in
1263
 * the query tree.  An exception to the match-the-syntactic-order rule is
1264
 * that when an outer join is pushed down into another one's RHS per identity
1265
 * 3, we can't mark its Vars as nulled until the now-upper outer join is also
1266
 * completed.  So we need to do three things:
1267
 *
1268
 * First, we add the outer join's relid to the nulling bitmap only if the
1269
 * outer join has been completely performed and the Var or PHV actually
1270
 * comes from within the syntactically nullable side(s) of the outer join.
1271
 * This takes care of the possibility that we have transformed
1272
 *    (A leftjoin B on (Pab)) leftjoin C on (Pbc)
1273
 * to
1274
 *    A leftjoin (B leftjoin C on (Pbc)) on (Pab)
1275
 * Here the pushed-down B/C join cannot mark C columns as nulled yet,
1276
 * while the now-upper A/B join must not mark C columns as nulled by itself.
1277
 *
1278
 * Second, perform the same operation for each SpecialJoinInfo listed in
1279
 * pushed_down_joins (which, in this example, would be the B/C join when
1280
 * we are at the now-upper A/B join).  This allows the now-upper join to
1281
 * complete the marking of "C" Vars that now have fully valid values.
1282
 *
1283
 * Third, any relid in sjinfo->commute_above_r that is already part of
1284
 * the joinrel is added to the nulling bitmaps of nullable Vars and PHVs.
1285
 * This takes care of the reverse case where we implement
1286
 *    A leftjoin (B leftjoin C on (Pbc)) on (Pab)
1287
 * as
1288
 *    (A leftjoin B on (Pab)) leftjoin C on (Pbc)
1289
 * The C columns emitted by the B/C join need to be shown as nulled by both
1290
 * the B/C and A/B joins, even though they've not physically traversed the
1291
 * A/B join.
1292
 */
1293
static void
1294
build_joinrel_tlist(PlannerInfo *root, RelOptInfo *joinrel,
1295
          RelOptInfo *input_rel,
1296
          SpecialJoinInfo *sjinfo,
1297
          List *pushed_down_joins,
1298
          bool can_null)
1299
0
{
1300
0
  Relids    relids = joinrel->relids;
1301
0
  int64   tuple_width = joinrel->reltarget->width;
1302
0
  ListCell   *vars;
1303
0
  ListCell   *lc;
1304
1305
0
  foreach(vars, input_rel->reltarget->exprs)
1306
0
  {
1307
0
    Var      *var = (Var *) lfirst(vars);
1308
1309
    /*
1310
     * For a PlaceHolderVar, we have to look up the PlaceHolderInfo.
1311
     */
1312
0
    if (IsA(var, PlaceHolderVar))
1313
0
    {
1314
0
      PlaceHolderVar *phv = (PlaceHolderVar *) var;
1315
0
      PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
1316
1317
      /* Is it still needed above this joinrel? */
1318
0
      if (bms_nonempty_difference(phinfo->ph_needed, relids))
1319
0
      {
1320
        /*
1321
         * Yup, add it to the output.  If this join potentially nulls
1322
         * this input, we have to update the PHV's phnullingrels,
1323
         * which means making a copy.
1324
         */
1325
0
        if (can_null)
1326
0
        {
1327
0
          phv = copyObject(phv);
1328
          /* See comments above to understand this logic */
1329
0
          if (sjinfo->ojrelid != 0 &&
1330
0
            bms_is_member(sjinfo->ojrelid, relids) &&
1331
0
            (bms_is_subset(phv->phrels, sjinfo->syn_righthand) ||
1332
0
             (sjinfo->jointype == JOIN_FULL &&
1333
0
              bms_is_subset(phv->phrels, sjinfo->syn_lefthand))))
1334
0
            phv->phnullingrels = bms_add_member(phv->phnullingrels,
1335
0
                              sjinfo->ojrelid);
1336
0
          foreach(lc, pushed_down_joins)
1337
0
          {
1338
0
            SpecialJoinInfo *othersj = (SpecialJoinInfo *) lfirst(lc);
1339
1340
0
            Assert(bms_is_member(othersj->ojrelid, relids));
1341
0
            if (bms_is_subset(phv->phrels, othersj->syn_righthand))
1342
0
              phv->phnullingrels = bms_add_member(phv->phnullingrels,
1343
0
                                othersj->ojrelid);
1344
0
          }
1345
0
          phv->phnullingrels =
1346
0
            bms_join(phv->phnullingrels,
1347
0
                 bms_intersect(sjinfo->commute_above_r,
1348
0
                         relids));
1349
0
        }
1350
1351
0
        joinrel->reltarget->exprs = lappend(joinrel->reltarget->exprs,
1352
0
                          phv);
1353
        /* Bubbling up the precomputed result has cost zero */
1354
0
        tuple_width += phinfo->ph_width;
1355
0
      }
1356
0
      continue;
1357
0
    }
1358
1359
    /*
1360
     * Otherwise, anything in a baserel or joinrel targetlist ought to be
1361
     * a Var.  (More general cases can only appear in appendrel child
1362
     * rels, which will never be seen here.)
1363
     */
1364
0
    if (!IsA(var, Var))
1365
0
      elog(ERROR, "unexpected node type in rel targetlist: %d",
1366
0
         (int) nodeTag(var));
1367
1368
0
    if (var->varno == ROWID_VAR)
1369
0
    {
1370
      /* UPDATE/DELETE/MERGE row identity vars are always needed */
1371
0
      RowIdentityVarInfo *ridinfo = (RowIdentityVarInfo *)
1372
0
        list_nth(root->row_identity_vars, var->varattno - 1);
1373
1374
      /* Update reltarget width estimate from RowIdentityVarInfo */
1375
0
      tuple_width += ridinfo->rowidwidth;
1376
0
    }
1377
0
    else
1378
0
    {
1379
0
      RelOptInfo *baserel;
1380
0
      int     ndx;
1381
1382
      /* Get the Var's original base rel */
1383
0
      baserel = find_base_rel(root, var->varno);
1384
1385
      /* Is it still needed above this joinrel? */
1386
0
      ndx = var->varattno - baserel->min_attr;
1387
0
      if (!bms_nonempty_difference(baserel->attr_needed[ndx], relids))
1388
0
        continue;   /* nope, skip it */
1389
1390
      /* Update reltarget width estimate from baserel's attr_widths */
1391
0
      tuple_width += baserel->attr_widths[ndx];
1392
0
    }
1393
1394
    /*
1395
     * Add the Var to the output.  If this join potentially nulls this
1396
     * input, we have to update the Var's varnullingrels, which means
1397
     * making a copy.  But note that we don't ever add nullingrel bits to
1398
     * row identity Vars (cf. comments in setrefs.c).
1399
     */
1400
0
    if (can_null && var->varno != ROWID_VAR)
1401
0
    {
1402
0
      var = copyObject(var);
1403
      /* See comments above to understand this logic */
1404
0
      if (sjinfo->ojrelid != 0 &&
1405
0
        bms_is_member(sjinfo->ojrelid, relids) &&
1406
0
        (bms_is_member(var->varno, sjinfo->syn_righthand) ||
1407
0
         (sjinfo->jointype == JOIN_FULL &&
1408
0
          bms_is_member(var->varno, sjinfo->syn_lefthand))))
1409
0
        var->varnullingrels = bms_add_member(var->varnullingrels,
1410
0
                           sjinfo->ojrelid);
1411
0
      foreach(lc, pushed_down_joins)
1412
0
      {
1413
0
        SpecialJoinInfo *othersj = (SpecialJoinInfo *) lfirst(lc);
1414
1415
0
        Assert(bms_is_member(othersj->ojrelid, relids));
1416
0
        if (bms_is_member(var->varno, othersj->syn_righthand))
1417
0
          var->varnullingrels = bms_add_member(var->varnullingrels,
1418
0
                             othersj->ojrelid);
1419
0
      }
1420
0
      var->varnullingrels =
1421
0
        bms_join(var->varnullingrels,
1422
0
             bms_intersect(sjinfo->commute_above_r,
1423
0
                     relids));
1424
0
    }
1425
1426
0
    joinrel->reltarget->exprs = lappend(joinrel->reltarget->exprs,
1427
0
                      var);
1428
1429
    /* Vars have cost zero, so no need to adjust reltarget->cost */
1430
0
  }
1431
1432
0
  joinrel->reltarget->width = clamp_width_est(tuple_width);
1433
0
}
1434
1435
#ifdef USE_ASSERT_CHECKING
1436
/*
1437
 * Check that a list of restriction clauses contains no two clauses with the
1438
 * same rinfo_serial, ie, that we have not accepted more than one clone of the
1439
 * same clause for evaluation at the same plan level.
1440
 */
1441
static bool
1442
no_duplicate_clause_serials(List *clauses)
1443
{
1444
  Bitmapset  *serials = NULL;
1445
1446
  foreach_node(RestrictInfo, rinfo, clauses)
1447
  {
1448
    if (bms_is_member(rinfo->rinfo_serial, serials))
1449
      return false;
1450
    serials = bms_add_member(serials, rinfo->rinfo_serial);
1451
  }
1452
  return true;
1453
}
1454
#endif
1455
1456
/*
1457
 * build_joinrel_restrictlist
1458
 * build_joinrel_joinlist
1459
 *    These routines build lists of restriction and join clauses for a
1460
 *    join relation from the joininfo lists of the relations it joins.
1461
 *
1462
 *    These routines are separate because the restriction list must be
1463
 *    built afresh for each pair of input sub-relations we consider, whereas
1464
 *    the join list need only be computed once for any join RelOptInfo.
1465
 *    The join list is fully determined by the set of rels making up the
1466
 *    joinrel, so we should get the same results (up to ordering) from any
1467
 *    candidate pair of sub-relations.  But the restriction list is whatever
1468
 *    is not handled in the sub-relations, so it depends on which
1469
 *    sub-relations are considered.
1470
 *
1471
 *    If a join clause from an input relation refers to base+OJ rels still not
1472
 *    present in the joinrel, then it is still a join clause for the joinrel;
1473
 *    we put it into the joininfo list for the joinrel.  Otherwise,
1474
 *    the clause is now a restrict clause for the joined relation, and we
1475
 *    return it to the caller of build_joinrel_restrictlist() to be stored in
1476
 *    join paths made from this pair of sub-relations.  (It will not need to
1477
 *    be considered further up the join tree.)
1478
 *
1479
 *    In many cases we will find the same RestrictInfos in both input
1480
 *    relations' joinlists, so be careful to eliminate duplicates.
1481
 *    Pointer equality should be a sufficient test for dups, since all
1482
 *    the various joinlist entries ultimately refer to RestrictInfos
1483
 *    pushed into them by distribute_restrictinfo_to_rels().
1484
 *
1485
 * 'joinrel' is a join relation node
1486
 * 'outer_rel' and 'inner_rel' are a pair of relations that can be joined
1487
 *    to form joinrel.
1488
 * 'sjinfo': join context info
1489
 *
1490
 * build_joinrel_restrictlist() returns a list of relevant restrictinfos,
1491
 * whereas build_joinrel_joinlist() stores its results in the joinrel's
1492
 * joininfo list.  One or the other must accept each given clause!
1493
 *
1494
 * NB: Formerly, we made deep(!) copies of each input RestrictInfo to pass
1495
 * up to the join relation.  I believe this is no longer necessary, because
1496
 * RestrictInfo nodes are no longer context-dependent.  Instead, just include
1497
 * the original nodes in the lists made for the join relation.
1498
 */
1499
static List *
1500
build_joinrel_restrictlist(PlannerInfo *root,
1501
               RelOptInfo *joinrel,
1502
               RelOptInfo *outer_rel,
1503
               RelOptInfo *inner_rel,
1504
               SpecialJoinInfo *sjinfo)
1505
0
{
1506
0
  List     *result;
1507
0
  Relids    both_input_relids;
1508
1509
0
  both_input_relids = bms_union(outer_rel->relids, inner_rel->relids);
1510
1511
  /*
1512
   * Collect all the clauses that syntactically belong at this level,
1513
   * eliminating any duplicates (important since we will see many of the
1514
   * same clauses arriving from both input relations).
1515
   */
1516
0
  result = subbuild_joinrel_restrictlist(root, joinrel, outer_rel,
1517
0
                       both_input_relids, NIL);
1518
0
  result = subbuild_joinrel_restrictlist(root, joinrel, inner_rel,
1519
0
                       both_input_relids, result);
1520
1521
  /*
1522
   * Add on any clauses derived from EquivalenceClasses.  These cannot be
1523
   * redundant with the clauses in the joininfo lists, so don't bother
1524
   * checking.
1525
   */
1526
0
  result = list_concat(result,
1527
0
             generate_join_implied_equalities(root,
1528
0
                              joinrel->relids,
1529
0
                              outer_rel->relids,
1530
0
                              inner_rel,
1531
0
                              sjinfo));
1532
1533
  /* We should not have accepted multiple clones of the same clause */
1534
0
  Assert(no_duplicate_clause_serials(result));
1535
1536
0
  return result;
1537
0
}
1538
1539
static void
1540
build_joinrel_joinlist(RelOptInfo *joinrel,
1541
             RelOptInfo *outer_rel,
1542
             RelOptInfo *inner_rel)
1543
0
{
1544
0
  List     *result;
1545
1546
  /*
1547
   * Collect all the clauses that syntactically belong above this level,
1548
   * eliminating any duplicates (important since we will see many of the
1549
   * same clauses arriving from both input relations).
1550
   */
1551
0
  result = subbuild_joinrel_joinlist(joinrel, outer_rel->joininfo, NIL);
1552
0
  result = subbuild_joinrel_joinlist(joinrel, inner_rel->joininfo, result);
1553
1554
0
  joinrel->joininfo = result;
1555
0
}
1556
1557
static List *
1558
subbuild_joinrel_restrictlist(PlannerInfo *root,
1559
                RelOptInfo *joinrel,
1560
                RelOptInfo *input_rel,
1561
                Relids both_input_relids,
1562
                List *new_restrictlist)
1563
0
{
1564
0
  ListCell   *l;
1565
1566
0
  foreach(l, input_rel->joininfo)
1567
0
  {
1568
0
    RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1569
1570
0
    if (bms_is_subset(rinfo->required_relids, joinrel->relids))
1571
0
    {
1572
      /*
1573
       * This clause should become a restriction clause for the joinrel,
1574
       * since it refers to no outside rels.  However, if it's a clone
1575
       * clause then it might be too late to evaluate it, so we have to
1576
       * check.  (If it is too late, just ignore the clause, taking it
1577
       * on faith that another clone was or will be selected.)  Clone
1578
       * clauses should always be outer-join clauses, so we compare
1579
       * against both_input_relids.
1580
       */
1581
0
      if (rinfo->has_clone || rinfo->is_clone)
1582
0
      {
1583
0
        Assert(!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids));
1584
0
        if (!bms_is_subset(rinfo->required_relids, both_input_relids))
1585
0
          continue;
1586
0
        if (bms_overlap(rinfo->incompatible_relids, both_input_relids))
1587
0
          continue;
1588
0
      }
1589
0
      else
1590
0
      {
1591
        /*
1592
         * For non-clone clauses, we just Assert it's OK.  These might
1593
         * be either join or filter clauses; if it's a join clause
1594
         * then it should not refer to the current join's output.
1595
         * (There is little point in checking incompatible_relids,
1596
         * because it'll be NULL.)
1597
         */
1598
0
        Assert(RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids) ||
1599
0
             bms_is_subset(rinfo->required_relids,
1600
0
                   both_input_relids));
1601
0
      }
1602
1603
      /*
1604
       * OK, so add it to the list, being careful to eliminate
1605
       * duplicates.  (Since RestrictInfo nodes in different joinlists
1606
       * will have been multiply-linked rather than copied, pointer
1607
       * equality should be a sufficient test.)
1608
       */
1609
0
      new_restrictlist = list_append_unique_ptr(new_restrictlist, rinfo);
1610
0
    }
1611
0
    else
1612
0
    {
1613
      /*
1614
       * This clause is still a join clause at this level, so we ignore
1615
       * it in this routine.
1616
       */
1617
0
    }
1618
0
  }
1619
1620
0
  return new_restrictlist;
1621
0
}
1622
1623
static List *
1624
subbuild_joinrel_joinlist(RelOptInfo *joinrel,
1625
              List *joininfo_list,
1626
              List *new_joininfo)
1627
0
{
1628
0
  ListCell   *l;
1629
1630
  /* Expected to be called only for join between parent relations. */
1631
0
  Assert(joinrel->reloptkind == RELOPT_JOINREL);
1632
1633
0
  foreach(l, joininfo_list)
1634
0
  {
1635
0
    RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1636
1637
0
    if (bms_is_subset(rinfo->required_relids, joinrel->relids))
1638
0
    {
1639
      /*
1640
       * This clause becomes a restriction clause for the joinrel, since
1641
       * it refers to no outside rels.  So we can ignore it in this
1642
       * routine.
1643
       */
1644
0
    }
1645
0
    else
1646
0
    {
1647
      /*
1648
       * This clause is still a join clause at this level, so add it to
1649
       * the new joininfo list, being careful to eliminate duplicates.
1650
       * (Since RestrictInfo nodes in different joinlists will have been
1651
       * multiply-linked rather than copied, pointer equality should be
1652
       * a sufficient test.)
1653
       */
1654
0
      new_joininfo = list_append_unique_ptr(new_joininfo, rinfo);
1655
0
    }
1656
0
  }
1657
1658
0
  return new_joininfo;
1659
0
}
1660
1661
1662
/*
1663
 * fetch_upper_rel
1664
 *    Build a RelOptInfo describing some post-scan/join query processing,
1665
 *    or return a pre-existing one if somebody already built it.
1666
 *
1667
 * An "upper" relation is identified by an UpperRelationKind and a Relids set.
1668
 * The meaning of the Relids set is not specified here, and very likely will
1669
 * vary for different relation kinds.
1670
 *
1671
 * Most of the fields in an upper-level RelOptInfo are not used and are not
1672
 * set here (though makeNode should ensure they're zeroes).  We basically only
1673
 * care about fields that are of interest to add_path() and set_cheapest().
1674
 */
1675
RelOptInfo *
1676
fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
1677
0
{
1678
0
  RelOptInfo *upperrel;
1679
0
  ListCell   *lc;
1680
1681
  /*
1682
   * For the moment, our indexing data structure is just a List for each
1683
   * relation kind.  If we ever get so many of one kind that this stops
1684
   * working well, we can improve it.  No code outside this function should
1685
   * assume anything about how to find a particular upperrel.
1686
   */
1687
1688
  /* If we already made this upperrel for the query, return it */
1689
0
  foreach(lc, root->upper_rels[kind])
1690
0
  {
1691
0
    upperrel = (RelOptInfo *) lfirst(lc);
1692
1693
0
    if (bms_equal(upperrel->relids, relids))
1694
0
      return upperrel;
1695
0
  }
1696
1697
0
  upperrel = makeNode(RelOptInfo);
1698
0
  upperrel->reloptkind = RELOPT_UPPER_REL;
1699
0
  upperrel->relids = bms_copy(relids);
1700
0
  upperrel->pgs_mask = root->glob->default_pgs_mask;
1701
1702
  /* cheap startup cost is interesting iff not all tuples to be retrieved */
1703
0
  upperrel->consider_startup = (root->tuple_fraction > 0);
1704
0
  upperrel->consider_param_startup = false;
1705
0
  upperrel->consider_parallel = false;  /* might get changed later */
1706
0
  upperrel->reltarget = create_empty_pathtarget();
1707
0
  upperrel->pathlist = NIL;
1708
0
  upperrel->cheapest_startup_path = NULL;
1709
0
  upperrel->cheapest_total_path = NULL;
1710
0
  upperrel->cheapest_parameterized_paths = NIL;
1711
1712
0
  root->upper_rels[kind] = lappend(root->upper_rels[kind], upperrel);
1713
1714
0
  return upperrel;
1715
0
}
1716
1717
1718
/*
1719
 * find_childrel_parents
1720
 *    Compute the set of parent relids of an appendrel child rel.
1721
 *
1722
 * Since appendrels can be nested, a child could have multiple levels of
1723
 * appendrel ancestors.  This function computes a Relids set of all the
1724
 * parent relation IDs.
1725
 */
1726
Relids
1727
find_childrel_parents(PlannerInfo *root, RelOptInfo *rel)
1728
0
{
1729
0
  Relids    result = NULL;
1730
1731
0
  Assert(rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1732
0
  Assert(rel->relid > 0 && rel->relid < root->simple_rel_array_size);
1733
1734
0
  do
1735
0
  {
1736
0
    AppendRelInfo *appinfo = root->append_rel_array[rel->relid];
1737
0
    Index   prelid = appinfo->parent_relid;
1738
1739
0
    result = bms_add_member(result, prelid);
1740
1741
    /* traverse up to the parent rel, loop if it's also a child rel */
1742
0
    rel = find_base_rel(root, prelid);
1743
0
  } while (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1744
1745
0
  Assert(rel->reloptkind == RELOPT_BASEREL);
1746
1747
0
  return result;
1748
0
}
1749
1750
1751
/*
1752
 * get_baserel_parampathinfo
1753
 *    Get the ParamPathInfo for a parameterized path for a base relation,
1754
 *    constructing one if we don't have one already.
1755
 *
1756
 * This centralizes estimating the rowcounts for parameterized paths.
1757
 * We need to cache those to be sure we use the same rowcount for all paths
1758
 * of the same parameterization for a given rel.  This is also a convenient
1759
 * place to determine which movable join clauses the parameterized path will
1760
 * be responsible for evaluating.
1761
 */
1762
ParamPathInfo *
1763
get_baserel_parampathinfo(PlannerInfo *root, RelOptInfo *baserel,
1764
              Relids required_outer)
1765
0
{
1766
0
  ParamPathInfo *ppi;
1767
0
  Relids    joinrelids;
1768
0
  List     *pclauses;
1769
0
  List     *eqclauses;
1770
0
  Bitmapset  *pserials;
1771
0
  double    rows;
1772
0
  ListCell   *lc;
1773
1774
  /* If rel has LATERAL refs, every path for it should account for them */
1775
0
  Assert(bms_is_subset(baserel->lateral_relids, required_outer));
1776
1777
  /* Unparameterized paths have no ParamPathInfo */
1778
0
  if (bms_is_empty(required_outer))
1779
0
    return NULL;
1780
1781
0
  Assert(!bms_overlap(baserel->relids, required_outer));
1782
1783
  /* If we already have a PPI for this parameterization, just return it */
1784
0
  if ((ppi = find_param_path_info(baserel, required_outer)))
1785
0
    return ppi;
1786
1787
  /*
1788
   * Identify all joinclauses that are movable to this base rel given this
1789
   * parameterization.
1790
   */
1791
0
  joinrelids = bms_union(baserel->relids, required_outer);
1792
0
  pclauses = NIL;
1793
0
  pserials = NULL;
1794
0
  foreach(lc, baserel->joininfo)
1795
0
  {
1796
0
    RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1797
1798
0
    if (!join_clause_is_movable_into(rinfo,
1799
0
                     baserel->relids,
1800
0
                     joinrelids))
1801
0
      continue;
1802
1803
    /*
1804
     * If it's a clone clause, drop variants that are incompatible with an
1805
     * outer join already computed below the point of evaluation; some
1806
     * other variant is the right one to apply.
1807
     *
1808
     * Multiple variants can survive that test under one parameterization,
1809
     * but only when they are parse-tree identical, which happens when a
1810
     * commuting outer join nulls no Var actually referenced by the
1811
     * clause.  (Otherwise, a variant's extra nullingrels put that outer
1812
     * join into its clause_relids, so being movable here means the join
1813
     * is part of the parameterization, and the lesser variant is rejected
1814
     * above.)  Identical variants still differ in required_relids and
1815
     * incompatible_relids, and join-level clause selection needs all of
1816
     * them: each is the sole legal choice in some join order.  Here,
1817
     * though, that distinction is not meaningful, since the same
1818
     * ParamPathInfo serves every join order that can use the path, and an
1819
     * identical variant is correct in any of them.  So enforce just the
1820
     * first survivor, identifying later ones by matching rinfo_serial;
1821
     * enforcing them too would waste execution effort and apply the
1822
     * clause's selectivity multiple times.
1823
     */
1824
0
    if (rinfo->has_clone || rinfo->is_clone)
1825
0
    {
1826
0
      if (bms_overlap(rinfo->incompatible_relids, joinrelids))
1827
0
        continue;
1828
0
      if (bms_is_member(rinfo->rinfo_serial, pserials))
1829
0
        continue;
1830
0
    }
1831
1832
0
    pclauses = lappend(pclauses, rinfo);
1833
0
    pserials = bms_add_member(pserials, rinfo->rinfo_serial);
1834
0
  }
1835
1836
  /*
1837
   * Add in joinclauses generated by EquivalenceClasses, too, folding their
1838
   * serial numbers into pserials.  (These clauses necessarily satisfy
1839
   * join_clause_is_movable_into; but in assert-enabled builds, let's verify
1840
   * that.)
1841
   */
1842
0
  eqclauses = generate_join_implied_equalities(root,
1843
0
                         joinrelids,
1844
0
                         required_outer,
1845
0
                         baserel,
1846
0
                         NULL);
1847
0
  foreach(lc, eqclauses)
1848
0
  {
1849
0
    RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1850
1851
0
    Assert(join_clause_is_movable_into(rinfo,
1852
0
                       baserel->relids,
1853
0
                       joinrelids));
1854
0
    pserials = bms_add_member(pserials, rinfo->rinfo_serial);
1855
0
  }
1856
0
  pclauses = list_concat(pclauses, eqclauses);
1857
1858
  /* We should not have accepted multiple clones of the same clause */
1859
0
  Assert(no_duplicate_clause_serials(pclauses));
1860
1861
  /* Estimate the number of rows returned by the parameterized scan */
1862
0
  rows = get_parameterized_baserel_size(root, baserel, pclauses);
1863
1864
  /* And now we can build the ParamPathInfo */
1865
0
  ppi = makeNode(ParamPathInfo);
1866
0
  ppi->ppi_req_outer = required_outer;
1867
0
  ppi->ppi_rows = rows;
1868
0
  ppi->ppi_clauses = pclauses;
1869
0
  ppi->ppi_serials = pserials;
1870
0
  baserel->ppilist = lappend(baserel->ppilist, ppi);
1871
1872
0
  return ppi;
1873
0
}
1874
1875
/*
1876
 * get_joinrel_parampathinfo
1877
 *    Get the ParamPathInfo for a parameterized path for a join relation,
1878
 *    constructing one if we don't have one already.
1879
 *
1880
 * This centralizes estimating the rowcounts for parameterized paths.
1881
 * We need to cache those to be sure we use the same rowcount for all paths
1882
 * of the same parameterization for a given rel.  This is also a convenient
1883
 * place to determine which movable join clauses the parameterized path will
1884
 * be responsible for evaluating.
1885
 *
1886
 * outer_path and inner_path are a pair of input paths that can be used to
1887
 * construct the join, and restrict_clauses is the list of regular join
1888
 * clauses (including clauses derived from EquivalenceClasses) that must be
1889
 * applied at the join node when using these inputs.
1890
 *
1891
 * Unlike the situation for base rels, the set of movable join clauses to be
1892
 * enforced at a join varies with the selected pair of input paths, so we
1893
 * must calculate that and pass it back, even if we already have a matching
1894
 * ParamPathInfo.  We handle this by adding any clauses moved down to this
1895
 * join to *restrict_clauses, which is an in/out parameter.  (The addition
1896
 * is done in such a way as to not modify the passed-in List structure.)
1897
 *
1898
 * Note: when considering a nestloop join, the caller must have removed from
1899
 * restrict_clauses any movable clauses that are themselves scheduled to be
1900
 * pushed into the right-hand path.  We do not do that here since it's
1901
 * unnecessary for other join types.
1902
 */
1903
ParamPathInfo *
1904
get_joinrel_parampathinfo(PlannerInfo *root, RelOptInfo *joinrel,
1905
              Path *outer_path,
1906
              Path *inner_path,
1907
              SpecialJoinInfo *sjinfo,
1908
              Relids required_outer,
1909
              List **restrict_clauses)
1910
0
{
1911
0
  ParamPathInfo *ppi;
1912
0
  Relids    join_and_req;
1913
0
  Relids    outer_and_req;
1914
0
  Relids    inner_and_req;
1915
0
  List     *pclauses;
1916
0
  Bitmapset  *pserials;
1917
0
  List     *eclauses;
1918
0
  List     *dropped_ecs;
1919
0
  double    rows;
1920
0
  ListCell   *lc;
1921
1922
  /* If rel has LATERAL refs, every path for it should account for them */
1923
0
  Assert(bms_is_subset(joinrel->lateral_relids, required_outer));
1924
1925
  /* Unparameterized paths have no ParamPathInfo or extra join clauses */
1926
0
  if (bms_is_empty(required_outer))
1927
0
    return NULL;
1928
1929
0
  Assert(!bms_overlap(joinrel->relids, required_outer));
1930
1931
  /*
1932
   * Identify all joinclauses that are movable to this join rel given this
1933
   * parameterization.  These are the clauses that are movable into this
1934
   * join, but not movable into either input path.  Treat an unparameterized
1935
   * input path as not accepting parameterized clauses (because it won't,
1936
   * per the shortcut exit above), even though the joinclause movement rules
1937
   * might allow the same clauses to be moved into a parameterized path for
1938
   * that rel.
1939
   */
1940
0
  join_and_req = bms_union(joinrel->relids, required_outer);
1941
0
  if (outer_path->param_info)
1942
0
    outer_and_req = bms_union(outer_path->parent->relids,
1943
0
                  PATH_REQ_OUTER(outer_path));
1944
0
  else
1945
0
    outer_and_req = NULL; /* outer path does not accept parameters */
1946
0
  if (inner_path->param_info)
1947
0
    inner_and_req = bms_union(inner_path->parent->relids,
1948
0
                  PATH_REQ_OUTER(inner_path));
1949
0
  else
1950
0
    inner_and_req = NULL; /* inner path does not accept parameters */
1951
1952
0
  pclauses = NIL;
1953
0
  pserials = NULL;
1954
0
  foreach(lc, joinrel->joininfo)
1955
0
  {
1956
0
    RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1957
1958
0
    if (!join_clause_is_movable_into(rinfo,
1959
0
                     joinrel->relids,
1960
0
                     join_and_req) ||
1961
0
      join_clause_is_movable_into(rinfo,
1962
0
                    outer_path->parent->relids,
1963
0
                    outer_and_req) ||
1964
0
      join_clause_is_movable_into(rinfo,
1965
0
                    inner_path->parent->relids,
1966
0
                    inner_and_req))
1967
0
      continue;
1968
1969
    /* As above, apply only one variant of a clone clause */
1970
0
    if (rinfo->has_clone || rinfo->is_clone)
1971
0
    {
1972
0
      if (bms_overlap(rinfo->incompatible_relids, join_and_req))
1973
0
        continue;
1974
0
      if (bms_is_member(rinfo->rinfo_serial, pserials))
1975
0
        continue;
1976
0
    }
1977
1978
0
    pclauses = lappend(pclauses, rinfo);
1979
0
    pserials = bms_add_member(pserials, rinfo->rinfo_serial);
1980
0
  }
1981
1982
  /* Consider joinclauses generated by EquivalenceClasses, too */
1983
0
  eclauses = generate_join_implied_equalities(root,
1984
0
                        join_and_req,
1985
0
                        required_outer,
1986
0
                        joinrel,
1987
0
                        NULL);
1988
  /* We only want ones that aren't movable to lower levels */
1989
0
  dropped_ecs = NIL;
1990
0
  foreach(lc, eclauses)
1991
0
  {
1992
0
    RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1993
1994
0
    Assert(join_clause_is_movable_into(rinfo,
1995
0
                       joinrel->relids,
1996
0
                       join_and_req));
1997
0
    if (join_clause_is_movable_into(rinfo,
1998
0
                    outer_path->parent->relids,
1999
0
                    outer_and_req))
2000
0
      continue;     /* drop if movable into LHS */
2001
0
    if (join_clause_is_movable_into(rinfo,
2002
0
                    inner_path->parent->relids,
2003
0
                    inner_and_req))
2004
0
    {
2005
      /* drop if movable into RHS, but remember EC for use below */
2006
0
      Assert(rinfo->left_ec == rinfo->right_ec);
2007
0
      dropped_ecs = lappend(dropped_ecs, rinfo->left_ec);
2008
0
      continue;
2009
0
    }
2010
0
    pclauses = lappend(pclauses, rinfo);
2011
0
  }
2012
2013
  /*
2014
   * EquivalenceClasses are harder to deal with than we could wish, because
2015
   * of the fact that a given EC can generate different clauses depending on
2016
   * context.  Suppose we have an EC {X.X, Y.Y, Z.Z} where X and Y are the
2017
   * LHS and RHS of the current join and Z is in required_outer, and further
2018
   * suppose that the inner_path is parameterized by both X and Z.  The code
2019
   * above will have produced either Z.Z = X.X or Z.Z = Y.Y from that EC,
2020
   * and in the latter case will have discarded it as being movable into the
2021
   * RHS.  However, the EC machinery might have produced either Y.Y = X.X or
2022
   * Y.Y = Z.Z as the EC enforcement clause within the inner_path; it will
2023
   * not have produced both, and we can't readily tell from here which one
2024
   * it did pick.  If we add no clause to this join, we'll end up with
2025
   * insufficient enforcement of the EC; either Z.Z or X.X will fail to be
2026
   * constrained to be equal to the other members of the EC.  (When we come
2027
   * to join Z to this X/Y path, we will certainly drop whichever EC clause
2028
   * is generated at that join, so this omission won't get fixed later.)
2029
   *
2030
   * To handle this, for each EC we discarded such a clause from, try to
2031
   * generate a clause connecting the required_outer rels to the join's LHS
2032
   * ("Z.Z = X.X" in the terms of the above example).  If successful, and if
2033
   * the clause can't be moved to the LHS, add it to the current join's
2034
   * restriction clauses.  (If an EC cannot generate such a clause then it
2035
   * has nothing that needs to be enforced here, while if the clause can be
2036
   * moved into the LHS then it should have been enforced within that path.)
2037
   *
2038
   * In cases where an EC needs to constrain EC members that are newly
2039
   * computable at this join, it can emit clauses that it already returned
2040
   * above and we accepted into pclauses.  Hence, do a final list-membership
2041
   * check before accepting more clauses.  (Pointer comparison should be
2042
   * enough to detect duplicates, since ECs cache derived clauses.)
2043
   *
2044
   * Note that we don't need similar processing for ECs whose clause was
2045
   * considered to be movable into the LHS, because the LHS can't refer to
2046
   * the RHS so there is no comparable ambiguity about what it might
2047
   * actually be enforcing internally.
2048
   */
2049
0
  if (dropped_ecs)
2050
0
  {
2051
0
    Relids    real_outer_and_req;
2052
2053
0
    real_outer_and_req = bms_union(outer_path->parent->relids,
2054
0
                     required_outer);
2055
0
    eclauses =
2056
0
      generate_join_implied_equalities_for_ecs(root,
2057
0
                           dropped_ecs,
2058
0
                           real_outer_and_req,
2059
0
                           required_outer,
2060
0
                           outer_path->parent);
2061
0
    foreach(lc, eclauses)
2062
0
    {
2063
0
      RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2064
2065
0
      Assert(join_clause_is_movable_into(rinfo,
2066
0
                         outer_path->parent->relids,
2067
0
                         real_outer_and_req));
2068
0
      if (join_clause_is_movable_into(rinfo,
2069
0
                      outer_path->parent->relids,
2070
0
                      outer_and_req))
2071
0
        continue;   /* drop if movable into LHS */
2072
0
      if (list_member_ptr(pclauses, rinfo))
2073
0
        continue;   /* drop if already accepted */
2074
0
      pclauses = lappend(pclauses, rinfo);
2075
0
    }
2076
0
  }
2077
2078
  /*
2079
   * Now, attach the identified moved-down clauses to the caller's
2080
   * restrict_clauses list.  By using list_concat in this order, we leave
2081
   * the original list structure of restrict_clauses undamaged.
2082
   */
2083
0
  *restrict_clauses = list_concat(pclauses, *restrict_clauses);
2084
2085
  /* We should not have accepted multiple clones of the same clause */
2086
0
  Assert(no_duplicate_clause_serials(*restrict_clauses));
2087
2088
  /* If we already have a PPI for this parameterization, just return it */
2089
0
  if ((ppi = find_param_path_info(joinrel, required_outer)))
2090
0
    return ppi;
2091
2092
  /* Estimate the number of rows returned by the parameterized join */
2093
0
  rows = get_parameterized_joinrel_size(root, joinrel,
2094
0
                      outer_path,
2095
0
                      inner_path,
2096
0
                      sjinfo,
2097
0
                      *restrict_clauses);
2098
2099
  /*
2100
   * And now we can build the ParamPathInfo.  No point in saving the
2101
   * input-pair-dependent clause list, though.
2102
   *
2103
   * Note: in GEQO mode, we'll be called in a temporary memory context, but
2104
   * the joinrel structure is there too, so no problem.
2105
   */
2106
0
  ppi = makeNode(ParamPathInfo);
2107
0
  ppi->ppi_req_outer = required_outer;
2108
0
  ppi->ppi_rows = rows;
2109
0
  ppi->ppi_clauses = NIL;
2110
0
  ppi->ppi_serials = NULL;
2111
0
  joinrel->ppilist = lappend(joinrel->ppilist, ppi);
2112
2113
0
  return ppi;
2114
0
}
2115
2116
/*
2117
 * get_appendrel_parampathinfo
2118
 *    Get the ParamPathInfo for a parameterized path for an append relation.
2119
 *
2120
 * For an append relation, the rowcount estimate will just be the sum of
2121
 * the estimates for its children.  However, we still need a ParamPathInfo
2122
 * to flag the fact that the path requires parameters.  So this just creates
2123
 * a suitable struct with zero ppi_rows (and no ppi_clauses either, since
2124
 * the Append node isn't responsible for checking quals).
2125
 */
2126
ParamPathInfo *
2127
get_appendrel_parampathinfo(RelOptInfo *appendrel, Relids required_outer)
2128
0
{
2129
0
  ParamPathInfo *ppi;
2130
2131
  /* If rel has LATERAL refs, every path for it should account for them */
2132
0
  Assert(bms_is_subset(appendrel->lateral_relids, required_outer));
2133
2134
  /* Unparameterized paths have no ParamPathInfo */
2135
0
  if (bms_is_empty(required_outer))
2136
0
    return NULL;
2137
2138
0
  Assert(!bms_overlap(appendrel->relids, required_outer));
2139
2140
  /* If we already have a PPI for this parameterization, just return it */
2141
0
  if ((ppi = find_param_path_info(appendrel, required_outer)))
2142
0
    return ppi;
2143
2144
  /* Else build the ParamPathInfo */
2145
0
  ppi = makeNode(ParamPathInfo);
2146
0
  ppi->ppi_req_outer = required_outer;
2147
0
  ppi->ppi_rows = 0;
2148
0
  ppi->ppi_clauses = NIL;
2149
0
  ppi->ppi_serials = NULL;
2150
0
  appendrel->ppilist = lappend(appendrel->ppilist, ppi);
2151
2152
0
  return ppi;
2153
0
}
2154
2155
/*
2156
 * get_wrapper_parampathinfo
2157
 *    Get the ParamPathInfo for a parameterized wrapper path.
2158
 *
2159
 * If a wrapper-type path, such as a MaterialPath, might be parameterized,
2160
 * use this function to compute its param_info.  This is suitable only when
2161
 * the wrapper path cannot add or remove any parameterization from its
2162
 * subpath, which typically means that it evaluates no quals nor tlist
2163
 * expressions.
2164
 */
2165
ParamPathInfo *
2166
get_wrapper_parampathinfo(Path *subpath)
2167
0
{
2168
  /*
2169
   * Currently we just re-use the subpath's ParamPathInfo, if any.  The
2170
   * ppi_req_outer value is correct given the assumption stated above, and
2171
   * none of the other fields are required to be valid for a wrapper path.
2172
   */
2173
0
  return subpath->param_info;
2174
0
}
2175
2176
/*
2177
 * Returns a ParamPathInfo for the parameterization given by required_outer, if
2178
 * already available in the given rel. Returns NULL otherwise.
2179
 */
2180
ParamPathInfo *
2181
find_param_path_info(RelOptInfo *rel, Relids required_outer)
2182
0
{
2183
0
  ListCell   *lc;
2184
2185
0
  foreach(lc, rel->ppilist)
2186
0
  {
2187
0
    ParamPathInfo *ppi = (ParamPathInfo *) lfirst(lc);
2188
2189
0
    if (bms_equal(ppi->ppi_req_outer, required_outer))
2190
0
      return ppi;
2191
0
  }
2192
2193
0
  return NULL;
2194
0
}
2195
2196
/*
2197
 * get_param_path_clause_serials
2198
 *    Given a parameterized Path, return the set of pushed-down clauses
2199
 *    (identified by rinfo_serial numbers) enforced within the Path.
2200
 *
2201
 * Callers should use this in preference to fetching ppi_serials themselves.
2202
 */
2203
Bitmapset *
2204
get_param_path_clause_serials(Path *path)
2205
0
{
2206
0
  if (path->param_info == NULL)
2207
0
    return NULL;     /* not parameterized */
2208
2209
0
  switch (nodeTag(path))
2210
0
  {
2211
0
    case T_NestPath:
2212
0
    case T_MergePath:
2213
0
    case T_HashPath:
2214
0
      {
2215
        /*
2216
         * For a join path, combine clauses enforced within either
2217
         * input path with those enforced as joinrestrictinfo in this
2218
         * path.  Note that joinrestrictinfo may include some
2219
         * non-pushed-down clauses, but for current purposes it's okay
2220
         * if we include those in the result.  (To be more careful, we
2221
         * could check for clause_relids overlapping the path
2222
         * parameterization, but it's not worth the cycles for now.)
2223
         */
2224
0
        JoinPath   *jpath = (JoinPath *) path;
2225
0
        Bitmapset  *pserials;
2226
0
        ListCell   *lc;
2227
2228
0
        pserials = NULL;
2229
0
        pserials = bms_add_members(pserials,
2230
0
                       get_param_path_clause_serials(jpath->outerjoinpath));
2231
0
        pserials = bms_add_members(pserials,
2232
0
                       get_param_path_clause_serials(jpath->innerjoinpath));
2233
0
        foreach(lc, jpath->joinrestrictinfo)
2234
0
        {
2235
0
          RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2236
2237
0
          pserials = bms_add_member(pserials, rinfo->rinfo_serial);
2238
0
        }
2239
0
        return pserials;
2240
0
      }
2241
0
    case T_AppendPath:
2242
0
      {
2243
        /*
2244
         * For an appendrel, take the intersection of the sets of
2245
         * clauses enforced in each input path.
2246
         */
2247
0
        AppendPath *apath = (AppendPath *) path;
2248
0
        Bitmapset  *pserials;
2249
0
        ListCell   *lc;
2250
2251
0
        pserials = NULL;
2252
0
        foreach(lc, apath->subpaths)
2253
0
        {
2254
0
          Path     *subpath = (Path *) lfirst(lc);
2255
0
          Bitmapset  *subserials;
2256
2257
0
          subserials = get_param_path_clause_serials(subpath);
2258
0
          if (lc == list_head(apath->subpaths))
2259
0
            pserials = bms_copy(subserials);
2260
0
          else
2261
0
            pserials = bms_int_members(pserials, subserials);
2262
0
          if (bms_is_empty(pserials))
2263
0
            break; /* no point in continuing */
2264
0
        }
2265
0
        return pserials;
2266
0
      }
2267
0
    case T_MergeAppendPath:
2268
2269
      /*
2270
       * We don't currently support parameterized MergeAppend paths, as
2271
       * explained in the comments for generate_orderedappend_paths.
2272
       */
2273
0
      Assert(false);
2274
0
      return NULL;
2275
0
    case T_GatherPath:
2276
0
    case T_GatherMergePath:
2277
2278
      /*
2279
       * Gather and GatherMerge paths are never parameterized, since we
2280
       * don't generate parameterized partial paths (see
2281
       * add_partial_path).
2282
       */
2283
0
      Assert(false);
2284
0
      return NULL;
2285
2286
      /*
2287
       * A path that merely wraps another path enforces no clauses of
2288
       * its own, so recurse through such paths.  We can't just use its
2289
       * ppi_serials, as that is the same as the subpath's, and won't be
2290
       * valid for join or append subpaths.  The set of path types
2291
       * listed here should match the set for which pathnode.c uses
2292
       * get_wrapper_parampathinfo().
2293
       */
2294
0
    case T_MaterialPath:
2295
0
      return get_param_path_clause_serials(((MaterialPath *) path)->subpath);
2296
0
    case T_MemoizePath:
2297
0
      return get_param_path_clause_serials(((MemoizePath *) path)->subpath);
2298
0
    case T_ProjectionPath:
2299
0
      return get_param_path_clause_serials(((ProjectionPath *) path)->subpath);
2300
0
    case T_SortPath:
2301
0
      return get_param_path_clause_serials(((SortPath *) path)->subpath);
2302
0
    case T_IncrementalSortPath:
2303
0
      return get_param_path_clause_serials(((IncrementalSortPath *) path)->spath.subpath);
2304
0
    case T_UniquePath:
2305
0
      return get_param_path_clause_serials(((UniquePath *) path)->subpath);
2306
0
    case T_AggPath:
2307
0
      return get_param_path_clause_serials(((AggPath *) path)->subpath);
2308
0
    case T_GroupingSetsPath:
2309
0
      return get_param_path_clause_serials(((GroupingSetsPath *) path)->subpath);
2310
0
    default:
2311
2312
      /*
2313
       * Otherwise, it's a baserel path and we can use the
2314
       * previously-computed set of serial numbers.
2315
       */
2316
0
      return path->param_info->ppi_serials;
2317
0
  }
2318
0
}
2319
2320
/*
2321
 * build_joinrel_partition_info
2322
 *    Checks if the two relations being joined can use partitionwise join
2323
 *    and if yes, initialize partitioning information of the resulting
2324
 *    partitioned join relation.
2325
 */
2326
static void
2327
build_joinrel_partition_info(PlannerInfo *root,
2328
               RelOptInfo *joinrel, RelOptInfo *outer_rel,
2329
               RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo,
2330
               List *restrictlist)
2331
0
{
2332
0
  PartitionScheme part_scheme;
2333
2334
  /* Nothing to do if partitionwise join technique is disabled. */
2335
0
  if ((joinrel->pgs_mask & PGS_CONSIDER_PARTITIONWISE) == 0)
2336
0
  {
2337
0
    Assert(!IS_PARTITIONED_REL(joinrel));
2338
0
    return;
2339
0
  }
2340
2341
  /*
2342
   * We can only consider this join as an input to further partitionwise
2343
   * joins if (a) the input relations are partitioned and have
2344
   * consider_partitionwise_join=true, (b) the partition schemes match, and
2345
   * (c) we can identify an equi-join between the partition keys.  Note that
2346
   * if it were possible for have_partkey_equi_join to return different
2347
   * answers for the same joinrel depending on which join ordering we try
2348
   * first, this logic would break.  That shouldn't happen, though, because
2349
   * of the way the query planner deduces implied equalities and reorders
2350
   * the joins.  Please see optimizer/README for details.
2351
   */
2352
0
  if (outer_rel->part_scheme == NULL || inner_rel->part_scheme == NULL ||
2353
0
    !outer_rel->consider_partitionwise_join ||
2354
0
    !inner_rel->consider_partitionwise_join ||
2355
0
    outer_rel->part_scheme != inner_rel->part_scheme ||
2356
0
    !have_partkey_equi_join(root, joinrel, outer_rel, inner_rel,
2357
0
                sjinfo->jointype, restrictlist))
2358
0
  {
2359
0
    Assert(!IS_PARTITIONED_REL(joinrel));
2360
0
    return;
2361
0
  }
2362
2363
0
  part_scheme = outer_rel->part_scheme;
2364
2365
  /*
2366
   * This function will be called only once for each joinrel, hence it
2367
   * should not have partitioning fields filled yet.
2368
   */
2369
0
  Assert(!joinrel->part_scheme && !joinrel->partexprs &&
2370
0
       !joinrel->nullable_partexprs && !joinrel->part_rels &&
2371
0
       !joinrel->boundinfo);
2372
2373
  /*
2374
   * If the join relation is partitioned, it uses the same partitioning
2375
   * scheme as the joining relations.
2376
   *
2377
   * Note: we calculate the partition bounds, number of partitions, and
2378
   * child-join relations of the join relation in try_partitionwise_join().
2379
   */
2380
0
  joinrel->part_scheme = part_scheme;
2381
0
  set_joinrel_partition_key_exprs(joinrel, outer_rel, inner_rel,
2382
0
                  sjinfo->jointype);
2383
2384
  /*
2385
   * Set the consider_partitionwise_join flag.
2386
   */
2387
0
  Assert(outer_rel->consider_partitionwise_join);
2388
0
  Assert(inner_rel->consider_partitionwise_join);
2389
0
  joinrel->consider_partitionwise_join = true;
2390
0
}
2391
2392
/*
2393
 * have_partkey_equi_join
2394
 *
2395
 * Returns true if there exist equi-join conditions involving pairs
2396
 * of matching partition keys of the relations being joined for all
2397
 * partition keys.
2398
 */
2399
static bool
2400
have_partkey_equi_join(PlannerInfo *root, RelOptInfo *joinrel,
2401
             RelOptInfo *rel1, RelOptInfo *rel2,
2402
             JoinType jointype, List *restrictlist)
2403
0
{
2404
0
  PartitionScheme part_scheme = rel1->part_scheme;
2405
0
  bool    pk_known_equal[PARTITION_MAX_KEYS];
2406
0
  int     num_equal_pks;
2407
0
  ListCell   *lc;
2408
2409
  /*
2410
   * This function must only be called when the joined relations have same
2411
   * partitioning scheme.
2412
   */
2413
0
  Assert(rel1->part_scheme == rel2->part_scheme);
2414
0
  Assert(part_scheme);
2415
2416
  /* We use a bool array to track which partkey columns are known equal */
2417
0
  memset(pk_known_equal, 0, sizeof(pk_known_equal));
2418
  /* ... as well as a count of how many are known equal */
2419
0
  num_equal_pks = 0;
2420
2421
  /* First, look through the join's restriction clauses */
2422
0
  foreach(lc, restrictlist)
2423
0
  {
2424
0
    RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
2425
0
    OpExpr     *opexpr;
2426
0
    Expr     *expr1;
2427
0
    Expr     *expr2;
2428
0
    bool    strict_op;
2429
0
    int     ipk1;
2430
0
    int     ipk2;
2431
2432
    /* If processing an outer join, only use its own join clauses. */
2433
0
    if (IS_OUTER_JOIN(jointype) &&
2434
0
      RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
2435
0
      continue;
2436
2437
    /* Skip clauses which can not be used for a join. */
2438
0
    if (!rinfo->can_join)
2439
0
      continue;
2440
2441
    /* Skip clauses which are not equality conditions. */
2442
0
    if (!rinfo->mergeopfamilies && !OidIsValid(rinfo->hashjoinoperator))
2443
0
      continue;
2444
2445
    /* Should be OK to assume it's an OpExpr. */
2446
0
    opexpr = castNode(OpExpr, rinfo->clause);
2447
2448
    /* Match the operands to the relation. */
2449
0
    if (bms_is_subset(rinfo->left_relids, rel1->relids) &&
2450
0
      bms_is_subset(rinfo->right_relids, rel2->relids))
2451
0
    {
2452
0
      expr1 = linitial(opexpr->args);
2453
0
      expr2 = lsecond(opexpr->args);
2454
0
    }
2455
0
    else if (bms_is_subset(rinfo->left_relids, rel2->relids) &&
2456
0
         bms_is_subset(rinfo->right_relids, rel1->relids))
2457
0
    {
2458
0
      expr1 = lsecond(opexpr->args);
2459
0
      expr2 = linitial(opexpr->args);
2460
0
    }
2461
0
    else
2462
0
      continue;
2463
2464
    /*
2465
     * Now we need to know whether the join operator is strict; see
2466
     * comments in pathnodes.h.
2467
     */
2468
0
    strict_op = op_strict(opexpr->opno);
2469
2470
    /*
2471
     * Vars appearing in the relation's partition keys will not have any
2472
     * varnullingrels, but those in expr1 and expr2 will if we're above
2473
     * outer joins that could null the respective rels.  It's okay to
2474
     * match anyway, if the join operator is strict.
2475
     */
2476
0
    if (strict_op)
2477
0
    {
2478
0
      if (bms_overlap(rel1->relids, root->outer_join_rels))
2479
0
        expr1 = (Expr *) remove_nulling_relids((Node *) expr1,
2480
0
                             root->outer_join_rels,
2481
0
                             NULL);
2482
0
      if (bms_overlap(rel2->relids, root->outer_join_rels))
2483
0
        expr2 = (Expr *) remove_nulling_relids((Node *) expr2,
2484
0
                             root->outer_join_rels,
2485
0
                             NULL);
2486
0
    }
2487
2488
    /*
2489
     * Only clauses referencing the partition keys are useful for
2490
     * partitionwise join.
2491
     */
2492
0
    ipk1 = match_expr_to_partition_keys(expr1, rel1, strict_op);
2493
0
    if (ipk1 < 0)
2494
0
      continue;
2495
0
    ipk2 = match_expr_to_partition_keys(expr2, rel2, strict_op);
2496
0
    if (ipk2 < 0)
2497
0
      continue;
2498
2499
    /*
2500
     * If the clause refers to keys at different ordinal positions, it can
2501
     * not be used for partitionwise join.
2502
     */
2503
0
    if (ipk1 != ipk2)
2504
0
      continue;
2505
2506
    /* Ignore clause if we already proved these keys equal. */
2507
0
    if (pk_known_equal[ipk1])
2508
0
      continue;
2509
2510
    /* Reject if the partition key collation differs from the clause's. */
2511
0
    if (rel1->part_scheme->partcollation[ipk1] != opexpr->inputcollid)
2512
0
      return false;
2513
2514
    /*
2515
     * The clause allows partitionwise join only if it uses the same
2516
     * operator family as that specified by the partition key.
2517
     */
2518
0
    if (part_scheme->strategy == PARTITION_STRATEGY_HASH)
2519
0
    {
2520
0
      if (!OidIsValid(rinfo->hashjoinoperator) ||
2521
0
        !op_in_opfamily(rinfo->hashjoinoperator,
2522
0
                part_scheme->partopfamily[ipk1]))
2523
0
        continue;
2524
0
    }
2525
0
    else if (!list_member_oid(rinfo->mergeopfamilies,
2526
0
                  part_scheme->partopfamily[ipk1]))
2527
0
      continue;
2528
2529
    /* Mark the partition key as having an equi-join clause. */
2530
0
    pk_known_equal[ipk1] = true;
2531
2532
    /* We can stop examining clauses once we prove all keys equal. */
2533
0
    if (++num_equal_pks == part_scheme->partnatts)
2534
0
      return true;
2535
0
  }
2536
2537
  /*
2538
   * Also check to see if any keys are known equal by equivclass.c.  In most
2539
   * cases there would have been a join restriction clause generated from
2540
   * any EC that had such knowledge, but there might be no such clause, or
2541
   * it might happen to constrain other members of the ECs than the ones we
2542
   * are looking for.
2543
   */
2544
0
  for (int ipk = 0; ipk < part_scheme->partnatts; ipk++)
2545
0
  {
2546
0
    Oid     btree_opfamily;
2547
2548
    /* Ignore if we already proved these keys equal. */
2549
0
    if (pk_known_equal[ipk])
2550
0
      continue;
2551
2552
    /*
2553
     * We need a btree opfamily to ask equivclass.c about.  If the
2554
     * partopfamily is a hash opfamily, look up its equality operator, and
2555
     * select some btree opfamily that that operator is part of.  (Any
2556
     * such opfamily should be good enough, since equivclass.c will track
2557
     * multiple opfamilies as appropriate.)
2558
     */
2559
0
    if (part_scheme->strategy == PARTITION_STRATEGY_HASH)
2560
0
    {
2561
0
      Oid     eq_op;
2562
0
      List     *eq_opfamilies;
2563
2564
0
      eq_op = get_opfamily_member(part_scheme->partopfamily[ipk],
2565
0
                    part_scheme->partopcintype[ipk],
2566
0
                    part_scheme->partopcintype[ipk],
2567
0
                    HTEqualStrategyNumber);
2568
0
      if (!OidIsValid(eq_op))
2569
0
        break;     /* we're not going to succeed */
2570
0
      eq_opfamilies = get_mergejoin_opfamilies(eq_op);
2571
0
      if (eq_opfamilies == NIL)
2572
0
        break;     /* we're not going to succeed */
2573
0
      btree_opfamily = linitial_oid(eq_opfamilies);
2574
0
    }
2575
0
    else
2576
0
      btree_opfamily = part_scheme->partopfamily[ipk];
2577
2578
    /*
2579
     * We consider only non-nullable partition keys here; nullable ones
2580
     * would not be treated as part of the same equivalence classes as
2581
     * non-nullable ones.
2582
     */
2583
0
    foreach(lc, rel1->partexprs[ipk])
2584
0
    {
2585
0
      Node     *expr1 = (Node *) lfirst(lc);
2586
0
      ListCell   *lc2;
2587
0
      Oid     partcoll1 = rel1->part_scheme->partcollation[ipk];
2588
0
      Oid     exprcoll1 = exprCollation(expr1);
2589
2590
0
      foreach(lc2, rel2->partexprs[ipk])
2591
0
      {
2592
0
        Node     *expr2 = (Node *) lfirst(lc2);
2593
2594
0
        if (exprs_known_equal(root, expr1, expr2, btree_opfamily))
2595
0
        {
2596
          /*
2597
           * Ensure that the collation of the expression matches
2598
           * that of the partition key. Checking just one collation
2599
           * (partcoll1 and exprcoll1) suffices because partcoll1
2600
           * and partcoll2, as well as exprcoll1 and exprcoll2,
2601
           * should be identical. This holds because both rel1 and
2602
           * rel2 use the same PartitionScheme and expr1 and expr2
2603
           * are equal.
2604
           */
2605
0
          if (partcoll1 == exprcoll1)
2606
0
          {
2607
0
            Oid     partcoll2 PG_USED_FOR_ASSERTS_ONLY =
2608
0
              rel2->part_scheme->partcollation[ipk];
2609
0
            Oid     exprcoll2 PG_USED_FOR_ASSERTS_ONLY =
2610
0
              exprCollation(expr2);
2611
2612
0
            Assert(partcoll2 == exprcoll2);
2613
0
            pk_known_equal[ipk] = true;
2614
0
            break;
2615
0
          }
2616
0
        }
2617
0
      }
2618
0
      if (pk_known_equal[ipk])
2619
0
        break;
2620
0
    }
2621
2622
0
    if (pk_known_equal[ipk])
2623
0
    {
2624
      /* We can stop examining keys once we prove all keys equal. */
2625
0
      if (++num_equal_pks == part_scheme->partnatts)
2626
0
        return true;
2627
0
    }
2628
0
    else
2629
0
      break;       /* no chance to succeed, give up */
2630
0
  }
2631
2632
0
  return false;
2633
0
}
2634
2635
/*
2636
 * match_expr_to_partition_keys
2637
 *
2638
 * Tries to match an expression to one of the nullable or non-nullable
2639
 * partition keys of "rel".  Returns the matched key's ordinal position,
2640
 * or -1 if the expression could not be matched to any of the keys.
2641
 *
2642
 * strict_op must be true if the expression will be compared with the
2643
 * partition key using a strict operator.  This allows us to consider
2644
 * nullable as well as nonnullable partition keys.
2645
 */
2646
static int
2647
match_expr_to_partition_keys(Expr *expr, RelOptInfo *rel, bool strict_op)
2648
0
{
2649
0
  int     cnt;
2650
2651
  /* This function should be called only for partitioned relations. */
2652
0
  Assert(rel->part_scheme);
2653
0
  Assert(rel->partexprs);
2654
0
  Assert(rel->nullable_partexprs);
2655
2656
  /* Remove any relabel decorations. */
2657
0
  while (IsA(expr, RelabelType))
2658
0
    expr = (Expr *) (castNode(RelabelType, expr))->arg;
2659
2660
0
  for (cnt = 0; cnt < rel->part_scheme->partnatts; cnt++)
2661
0
  {
2662
0
    ListCell   *lc;
2663
2664
    /* We can always match to the non-nullable partition keys. */
2665
0
    foreach(lc, rel->partexprs[cnt])
2666
0
    {
2667
0
      if (equal(lfirst(lc), expr))
2668
0
        return cnt;
2669
0
    }
2670
2671
0
    if (!strict_op)
2672
0
      continue;
2673
2674
    /*
2675
     * If it's a strict join operator then a NULL partition key on one
2676
     * side will not join to any partition key on the other side, and in
2677
     * particular such a row can't join to a row from a different
2678
     * partition on the other side.  So, it's okay to search the nullable
2679
     * partition keys as well.
2680
     */
2681
0
    foreach(lc, rel->nullable_partexprs[cnt])
2682
0
    {
2683
0
      if (equal(lfirst(lc), expr))
2684
0
        return cnt;
2685
0
    }
2686
0
  }
2687
2688
0
  return -1;
2689
0
}
2690
2691
/*
2692
 * set_joinrel_partition_key_exprs
2693
 *    Initialize partition key expressions for a partitioned joinrel.
2694
 */
2695
static void
2696
set_joinrel_partition_key_exprs(RelOptInfo *joinrel,
2697
                RelOptInfo *outer_rel, RelOptInfo *inner_rel,
2698
                JoinType jointype)
2699
0
{
2700
0
  PartitionScheme part_scheme = joinrel->part_scheme;
2701
0
  int     partnatts = part_scheme->partnatts;
2702
2703
0
  joinrel->partexprs = palloc0_array(List *, partnatts);
2704
0
  joinrel->nullable_partexprs = palloc0_array(List *, partnatts);
2705
2706
  /*
2707
   * The joinrel's partition expressions are the same as those of the input
2708
   * rels, but we must properly classify them as nullable or not in the
2709
   * joinrel's output.  (Also, we add some more partition expressions if
2710
   * it's a FULL JOIN.)
2711
   */
2712
0
  for (int cnt = 0; cnt < partnatts; cnt++)
2713
0
  {
2714
    /* mark these const to enforce that we copy them properly */
2715
0
    const List *outer_expr = outer_rel->partexprs[cnt];
2716
0
    const List *outer_null_expr = outer_rel->nullable_partexprs[cnt];
2717
0
    const List *inner_expr = inner_rel->partexprs[cnt];
2718
0
    const List *inner_null_expr = inner_rel->nullable_partexprs[cnt];
2719
0
    List     *partexpr = NIL;
2720
0
    List     *nullable_partexpr = NIL;
2721
0
    ListCell   *lc;
2722
2723
0
    switch (jointype)
2724
0
    {
2725
        /*
2726
         * A join relation resulting from an INNER join may be
2727
         * regarded as partitioned by either of the inner and outer
2728
         * relation keys.  For example, A INNER JOIN B ON A.a = B.b
2729
         * can be regarded as partitioned on either A.a or B.b.  So we
2730
         * add both keys to the joinrel's partexpr lists.  However,
2731
         * anything that was already nullable still has to be treated
2732
         * as nullable.
2733
         */
2734
0
      case JOIN_INNER:
2735
0
        partexpr = list_concat_copy(outer_expr, inner_expr);
2736
0
        nullable_partexpr = list_concat_copy(outer_null_expr,
2737
0
                           inner_null_expr);
2738
0
        break;
2739
2740
        /*
2741
         * A join relation resulting from a SEMI or ANTI join may be
2742
         * regarded as partitioned by the outer relation keys.  The
2743
         * inner relation's keys are no longer interesting; since they
2744
         * aren't visible in the join output, nothing could join to
2745
         * them.
2746
         */
2747
0
      case JOIN_SEMI:
2748
0
      case JOIN_ANTI:
2749
0
        partexpr = list_copy(outer_expr);
2750
0
        nullable_partexpr = list_copy(outer_null_expr);
2751
0
        break;
2752
2753
        /*
2754
         * A join relation resulting from a LEFT OUTER JOIN likewise
2755
         * may be regarded as partitioned on the (non-nullable) outer
2756
         * relation keys.  The inner (nullable) relation keys are okay
2757
         * as partition keys for further joins as long as they involve
2758
         * strict join operators.
2759
         */
2760
0
      case JOIN_LEFT:
2761
0
        partexpr = list_copy(outer_expr);
2762
0
        nullable_partexpr = list_concat_copy(inner_expr,
2763
0
                           outer_null_expr);
2764
0
        nullable_partexpr = list_concat(nullable_partexpr,
2765
0
                        inner_null_expr);
2766
0
        break;
2767
2768
        /*
2769
         * For FULL OUTER JOINs, both relations are nullable, so the
2770
         * resulting join relation may be regarded as partitioned on
2771
         * either of inner and outer relation keys, but only for joins
2772
         * that involve strict join operators.
2773
         */
2774
0
      case JOIN_FULL:
2775
0
        nullable_partexpr = list_concat_copy(outer_expr,
2776
0
                           inner_expr);
2777
0
        nullable_partexpr = list_concat(nullable_partexpr,
2778
0
                        outer_null_expr);
2779
0
        nullable_partexpr = list_concat(nullable_partexpr,
2780
0
                        inner_null_expr);
2781
2782
        /*
2783
         * Also add CoalesceExprs corresponding to each possible
2784
         * full-join output variable (that is, left side coalesced to
2785
         * right side), so that we can match equijoin expressions
2786
         * using those variables.  We really only need these for
2787
         * columns merged by JOIN USING, and only with the pairs of
2788
         * input items that correspond to the data structures that
2789
         * parse analysis would build for such variables.  But it's
2790
         * hard to tell which those are, so just make all the pairs.
2791
         * Extra items in the nullable_partexprs list won't cause big
2792
         * problems.  (It's possible that such items will get matched
2793
         * to user-written COALESCEs, but it should still be valid to
2794
         * partition on those, since they're going to be either the
2795
         * partition column or NULL; it's the same argument as for
2796
         * partitionwise nesting of any outer join.)  We assume no
2797
         * type coercions are needed to make the coalesce expressions,
2798
         * since columns of different types won't have gotten
2799
         * classified as the same PartitionScheme.  Note that we
2800
         * intentionally leave out the varnullingrels decoration that
2801
         * would ordinarily appear on the Vars inside these
2802
         * CoalesceExprs, because have_partkey_equi_join will strip
2803
         * varnullingrels from the expressions it will compare to the
2804
         * partexprs.
2805
         */
2806
0
        foreach(lc, list_concat_copy(outer_expr, outer_null_expr))
2807
0
        {
2808
0
          Node     *larg = (Node *) lfirst(lc);
2809
0
          ListCell   *lc2;
2810
2811
0
          foreach(lc2, list_concat_copy(inner_expr, inner_null_expr))
2812
0
          {
2813
0
            Node     *rarg = (Node *) lfirst(lc2);
2814
0
            CoalesceExpr *c = makeNode(CoalesceExpr);
2815
2816
0
            c->coalescetype = exprType(larg);
2817
0
            c->coalescecollid = exprCollation(larg);
2818
0
            c->args = list_make2(larg, rarg);
2819
0
            c->location = -1;
2820
0
            nullable_partexpr = lappend(nullable_partexpr, c);
2821
0
          }
2822
0
        }
2823
0
        break;
2824
2825
0
      default:
2826
0
        elog(ERROR, "unrecognized join type: %d", (int) jointype);
2827
0
    }
2828
2829
0
    joinrel->partexprs[cnt] = partexpr;
2830
0
    joinrel->nullable_partexprs[cnt] = nullable_partexpr;
2831
0
  }
2832
0
}
2833
2834
/*
2835
 * build_child_join_reltarget
2836
 *    Set up a child-join relation's reltarget from a parent-join relation.
2837
 */
2838
static void
2839
build_child_join_reltarget(PlannerInfo *root,
2840
               RelOptInfo *parentrel,
2841
               RelOptInfo *childrel,
2842
               int nappinfos,
2843
               AppendRelInfo **appinfos)
2844
0
{
2845
  /* Build the targetlist */
2846
0
  childrel->reltarget->exprs = (List *)
2847
0
    adjust_appendrel_attrs(root,
2848
0
                 (Node *) parentrel->reltarget->exprs,
2849
0
                 nappinfos, appinfos);
2850
2851
  /* Set the cost and width fields */
2852
0
  childrel->reltarget->cost.startup = parentrel->reltarget->cost.startup;
2853
0
  childrel->reltarget->cost.per_tuple = parentrel->reltarget->cost.per_tuple;
2854
0
  childrel->reltarget->width = parentrel->reltarget->width;
2855
0
}
2856
2857
/*
2858
 * create_rel_agg_info
2859
 *    Create the RelAggInfo structure for the given relation if it can produce
2860
 *    grouped paths.  The given relation is the non-grouped one which has the
2861
 *    reltarget already constructed.
2862
 *
2863
 * calculate_grouped_rows: if true, calculate the estimated number of grouped
2864
 * rows for the relation.  If false, skip the estimation to avoid unnecessary
2865
 * planning overhead.
2866
 */
2867
RelAggInfo *
2868
create_rel_agg_info(PlannerInfo *root, RelOptInfo *rel,
2869
          bool calculate_grouped_rows)
2870
0
{
2871
0
  ListCell   *lc;
2872
0
  RelAggInfo *result;
2873
0
  PathTarget *agg_input;
2874
0
  PathTarget *target;
2875
0
  List     *group_clauses = NIL;
2876
0
  List     *group_exprs = NIL;
2877
2878
  /*
2879
   * The lists of aggregate expressions and grouping expressions should have
2880
   * been constructed.
2881
   */
2882
0
  Assert(root->agg_clause_list != NIL);
2883
0
  Assert(root->group_expr_list != NIL);
2884
2885
  /*
2886
   * If this is a child rel, the grouped rel for its parent rel must have
2887
   * been created if it can.  So we can just use parent's RelAggInfo if
2888
   * there is one, with appropriate variable substitutions.
2889
   */
2890
0
  if (IS_OTHER_REL(rel))
2891
0
  {
2892
0
    RelOptInfo *grouped_rel;
2893
0
    RelAggInfo *agg_info;
2894
2895
0
    grouped_rel = rel->top_parent->grouped_rel;
2896
0
    if (grouped_rel == NULL)
2897
0
      return NULL;
2898
2899
0
    Assert(IS_GROUPED_REL(grouped_rel));
2900
2901
    /* Must do multi-level transformation */
2902
0
    agg_info = (RelAggInfo *)
2903
0
      adjust_appendrel_attrs_multilevel(root,
2904
0
                        (Node *) grouped_rel->agg_info,
2905
0
                        rel,
2906
0
                        rel->top_parent);
2907
2908
0
    agg_info->apply_agg_at = NULL; /* caller will change this later */
2909
2910
0
    if (calculate_grouped_rows)
2911
0
    {
2912
0
      agg_info->grouped_rows =
2913
0
        estimate_num_groups(root, agg_info->group_exprs,
2914
0
                  rel->rows, NULL, NULL);
2915
2916
      /*
2917
       * The grouped paths for the given relation are considered useful
2918
       * iff the average group size is no less than
2919
       * min_eager_agg_group_size.
2920
       */
2921
0
      agg_info->agg_useful =
2922
0
        (rel->rows / agg_info->grouped_rows) >= min_eager_agg_group_size;
2923
0
    }
2924
2925
0
    return agg_info;
2926
0
  }
2927
2928
  /* Check if it's possible to produce grouped paths for this relation. */
2929
0
  if (!eager_aggregation_possible_for_relation(root, rel))
2930
0
    return NULL;
2931
2932
  /*
2933
   * Create targets for the grouped paths and for the input paths of the
2934
   * grouped paths.
2935
   */
2936
0
  target = create_empty_pathtarget();
2937
0
  agg_input = create_empty_pathtarget();
2938
2939
  /* ... and initialize these targets */
2940
0
  if (!init_grouping_targets(root, rel, target, agg_input,
2941
0
                 &group_clauses, &group_exprs))
2942
0
    return NULL;
2943
2944
  /*
2945
   * Eager aggregation is not applicable if there are no available grouping
2946
   * expressions.
2947
   */
2948
0
  if (group_clauses == NIL)
2949
0
    return NULL;
2950
2951
  /* Add aggregates to the grouping target */
2952
0
  foreach(lc, root->agg_clause_list)
2953
0
  {
2954
0
    AggClauseInfo *ac_info = lfirst_node(AggClauseInfo, lc);
2955
0
    Aggref     *aggref;
2956
2957
0
    Assert(IsA(ac_info->aggref, Aggref));
2958
2959
0
    aggref = (Aggref *) copyObject(ac_info->aggref);
2960
0
    mark_partial_aggref(aggref, AGGSPLIT_INITIAL_SERIAL);
2961
2962
0
    add_column_to_pathtarget(target, (Expr *) aggref, 0);
2963
0
  }
2964
2965
  /* Set the estimated eval cost and output width for both targets */
2966
0
  set_pathtarget_cost_width(root, target);
2967
0
  set_pathtarget_cost_width(root, agg_input);
2968
2969
  /* build the RelAggInfo result */
2970
0
  result = makeNode(RelAggInfo);
2971
0
  result->target = target;
2972
0
  result->agg_input = agg_input;
2973
0
  result->group_clauses = group_clauses;
2974
0
  result->group_exprs = group_exprs;
2975
0
  result->apply_agg_at = NULL; /* caller will change this later */
2976
2977
0
  if (calculate_grouped_rows)
2978
0
  {
2979
0
    result->grouped_rows = estimate_num_groups(root, result->group_exprs,
2980
0
                           rel->rows, NULL, NULL);
2981
2982
    /*
2983
     * The grouped paths for the given relation are considered useful iff
2984
     * the average group size is no less than min_eager_agg_group_size.
2985
     */
2986
0
    result->agg_useful =
2987
0
      (rel->rows / result->grouped_rows) >= min_eager_agg_group_size;
2988
0
  }
2989
2990
0
  return result;
2991
0
}
2992
2993
/*
2994
 * eager_aggregation_possible_for_relation
2995
 *    Check if it's possible to produce grouped paths for the given relation.
2996
 */
2997
static bool
2998
eager_aggregation_possible_for_relation(PlannerInfo *root, RelOptInfo *rel)
2999
0
{
3000
0
  ListCell   *lc;
3001
0
  int     cur_relid;
3002
3003
  /*
3004
   * Check to see if the given relation is in the nullable side of an outer
3005
   * join.  In this case, we cannot push a partial aggregation down to the
3006
   * relation, because the NULL-extended rows produced by the outer join
3007
   * would not be available when we perform the partial aggregation, while
3008
   * with a non-eager-aggregation plan these rows are available for the
3009
   * top-level aggregation.  Doing so may result in the rows being grouped
3010
   * differently than expected, or produce incorrect values from the
3011
   * aggregate functions.
3012
   */
3013
0
  cur_relid = -1;
3014
0
  while ((cur_relid = bms_next_member(rel->relids, cur_relid)) >= 0)
3015
0
  {
3016
0
    RelOptInfo *baserel = find_base_rel_ignore_join(root, cur_relid);
3017
3018
0
    if (baserel == NULL)
3019
0
      continue;     /* ignore outer joins in rel->relids */
3020
3021
0
    if (!bms_is_subset(baserel->nulling_relids, rel->relids))
3022
0
      return false;
3023
0
  }
3024
3025
  /*
3026
   * Similarly, we cannot push a partial aggregation down to a relation on
3027
   * the inner (RHS) side of a semi/anti join.  A semi/anti join does not
3028
   * preserve its inner rows in the join output, so a partial aggregate
3029
   * computed on the inner side would not survive the join and could not be
3030
   * combined by the final aggregation.
3031
   *
3032
   * Note that the inner side of an anti join already carries nulling_relids
3033
   * and so is handled by the outer-join check above.  The case this check
3034
   * adds is a semi join, which has no relid.
3035
   */
3036
0
  foreach(lc, root->join_info_list)
3037
0
  {
3038
0
    SpecialJoinInfo *sjinfo = lfirst_node(SpecialJoinInfo, lc);
3039
3040
0
    if (sjinfo->jointype != JOIN_SEMI && sjinfo->jointype != JOIN_ANTI)
3041
0
      continue;
3042
3043
    /* rel includes inner-side rels of this join but not its outer side */
3044
0
    if (bms_overlap(rel->relids, sjinfo->min_righthand) &&
3045
0
      !bms_is_subset(sjinfo->min_lefthand, rel->relids))
3046
0
      return false;
3047
0
  }
3048
3049
  /*
3050
   * We cannot push a partial aggregation down below a join clause that
3051
   * contains volatile functions, because the clause would then be evaluated
3052
   * once per group rather than once per input row.
3053
   */
3054
0
  foreach(lc, rel->joininfo)
3055
0
  {
3056
0
    RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3057
3058
0
    if (contain_volatile_functions((Node *) rinfo))
3059
0
      return false;
3060
0
  }
3061
3062
  /*
3063
   * For now we don't try to support PlaceHolderVars.
3064
   */
3065
0
  foreach(lc, rel->reltarget->exprs)
3066
0
  {
3067
0
    Expr     *expr = lfirst(lc);
3068
3069
0
    if (IsA(expr, PlaceHolderVar))
3070
0
      return false;
3071
0
  }
3072
3073
  /* Caller should only pass base relations or joins. */
3074
0
  Assert(rel->reloptkind == RELOPT_BASEREL ||
3075
0
       rel->reloptkind == RELOPT_JOINREL);
3076
3077
  /*
3078
   * Check if all aggregate expressions can be evaluated on this relation
3079
   * level.
3080
   */
3081
0
  foreach(lc, root->agg_clause_list)
3082
0
  {
3083
0
    AggClauseInfo *ac_info = lfirst_node(AggClauseInfo, lc);
3084
3085
0
    Assert(IsA(ac_info->aggref, Aggref));
3086
3087
    /*
3088
     * Give up if any aggregate requires relations other than the current
3089
     * one.  If the aggregate requires the current relation plus
3090
     * additional relations, grouping the current relation could make some
3091
     * input rows unavailable for the higher aggregate and may reduce the
3092
     * number of input rows it receives.  If the aggregate does not
3093
     * require the current relation at all, it should not be grouped, as
3094
     * we do not support joining two grouped relations.
3095
     */
3096
0
    if (!bms_is_subset(ac_info->agg_eval_at, rel->relids))
3097
0
      return false;
3098
0
  }
3099
3100
0
  return true;
3101
0
}
3102
3103
/*
3104
 * init_grouping_targets
3105
 *    Initialize the target for grouped paths (target) as well as the target
3106
 *    for paths that generate input for the grouped paths (agg_input).
3107
 *
3108
 * We also construct the list of SortGroupClauses and the list of grouping
3109
 * expressions for the partial aggregation, and return them in *group_clause
3110
 * and *group_exprs.
3111
 *
3112
 * Return true if the targets could be initialized, false otherwise.
3113
 */
3114
static bool
3115
init_grouping_targets(PlannerInfo *root, RelOptInfo *rel,
3116
            PathTarget *target, PathTarget *agg_input,
3117
            List **group_clauses, List **group_exprs)
3118
0
{
3119
0
  ListCell   *lc;
3120
0
  List     *possibly_dependent = NIL;
3121
0
  Index   maxSortGroupRef;
3122
3123
  /* Identify the max sortgroupref */
3124
0
  maxSortGroupRef = 0;
3125
0
  foreach(lc, root->processed_tlist)
3126
0
  {
3127
0
    Index   ref = ((TargetEntry *) lfirst(lc))->ressortgroupref;
3128
3129
0
    if (ref > maxSortGroupRef)
3130
0
      maxSortGroupRef = ref;
3131
0
  }
3132
3133
  /*
3134
   * At this point, all Vars from this relation that are needed by upper
3135
   * joins or are required in the final targetlist should already be present
3136
   * in its reltarget.  Therefore, we can safely iterate over this
3137
   * relation's reltarget->exprs to construct the PathTarget and grouping
3138
   * clauses for the grouped paths.
3139
   */
3140
0
  foreach(lc, rel->reltarget->exprs)
3141
0
  {
3142
0
    Expr     *expr = (Expr *) lfirst(lc);
3143
0
    Index   sortgroupref;
3144
3145
    /*
3146
     * Given that PlaceHolderVar currently prevents us from doing eager
3147
     * aggregation, the source target cannot contain anything more complex
3148
     * than a Var.
3149
     */
3150
0
    Assert(IsA(expr, Var));
3151
3152
    /*
3153
     * Get the sortgroupref of the expr if it is found among, or can be
3154
     * deduced from, the original grouping expressions.
3155
     */
3156
0
    sortgroupref = get_expression_sortgroupref(root, expr);
3157
0
    if (sortgroupref > 0)
3158
0
    {
3159
0
      SortGroupClause *sgc;
3160
3161
      /* Find the matching SortGroupClause */
3162
0
      sgc = get_sortgroupref_clause(sortgroupref, root->processed_groupClause);
3163
0
      Assert(sgc->tleSortGroupRef <= maxSortGroupRef);
3164
3165
      /*
3166
       * If the target expression is to be used as a grouping key, it
3167
       * should be emitted by the grouped paths that have been pushed
3168
       * down to this relation level.
3169
       */
3170
0
      add_column_to_pathtarget(target, expr, sortgroupref);
3171
3172
      /*
3173
       * ... and it also should be emitted by the input paths.
3174
       */
3175
0
      add_column_to_pathtarget(agg_input, expr, sortgroupref);
3176
3177
      /*
3178
       * Record this SortGroupClause and grouping expression.  Note that
3179
       * this SortGroupClause might have already been recorded.
3180
       */
3181
0
      if (!list_member(*group_clauses, sgc))
3182
0
      {
3183
0
        *group_clauses = lappend(*group_clauses, sgc);
3184
0
        *group_exprs = lappend(*group_exprs, expr);
3185
0
      }
3186
0
    }
3187
0
    else if (is_var_needed_by_join(root, (Var *) expr, rel))
3188
0
    {
3189
      /*
3190
       * The expression is needed for an upper join but is neither in
3191
       * the GROUP BY clause nor derivable from it using EC (otherwise,
3192
       * it would have already been included in the targets above).  We
3193
       * need to create a special SortGroupClause for this expression.
3194
       *
3195
       * It is important to include such expressions in the grouping
3196
       * keys.  This is essential to ensure that an aggregated row from
3197
       * the partial aggregation matches the other side of the join if
3198
       * and only if each row in the partial group does.  This ensures
3199
       * that all rows within the same partial group share the same
3200
       * 'destiny', which is crucial for maintaining correctness.
3201
       */
3202
0
      SortGroupClause *sgc;
3203
0
      TypeCacheEntry *tce;
3204
0
      Oid     equalimageproc;
3205
3206
      /*
3207
       * But first, check if equality implies image equality for this
3208
       * expression.  If not, we cannot use it as a grouping key.  See
3209
       * comments in create_grouping_expr_infos().
3210
       */
3211
0
      tce = lookup_type_cache(exprType((Node *) expr),
3212
0
                  TYPECACHE_BTREE_OPFAMILY);
3213
0
      if (!OidIsValid(tce->btree_opf) ||
3214
0
        !OidIsValid(tce->btree_opintype))
3215
0
        return false;
3216
3217
0
      equalimageproc = get_opfamily_proc(tce->btree_opf,
3218
0
                         tce->btree_opintype,
3219
0
                         tce->btree_opintype,
3220
0
                         BTEQUALIMAGE_PROC);
3221
3222
      /*
3223
       * If there is no BTEQUALIMAGE_PROC, eager aggregation is assumed
3224
       * to be unsafe.  Otherwise, we call the procedure to check.  We
3225
       * must be careful to pass the expression's actual collation,
3226
       * rather than the data type's default collation, to ensure that
3227
       * non-deterministic collations are correctly handled.
3228
       */
3229
0
      if (!OidIsValid(equalimageproc) ||
3230
0
        !DatumGetBool(OidFunctionCall1Coll(equalimageproc,
3231
0
                           exprCollation((Node *) expr),
3232
0
                           ObjectIdGetDatum(tce->btree_opintype))))
3233
0
        return false;
3234
3235
      /* Create the SortGroupClause. */
3236
0
      sgc = makeNode(SortGroupClause);
3237
3238
      /* Initialize the SortGroupClause. */
3239
0
      sgc->tleSortGroupRef = ++maxSortGroupRef;
3240
0
      get_sort_group_operators(exprType((Node *) expr),
3241
0
                   false, true, false,
3242
0
                   &sgc->sortop, &sgc->eqop, NULL,
3243
0
                   &sgc->hashable);
3244
3245
      /* This expression should be emitted by the grouped paths */
3246
0
      add_column_to_pathtarget(target, expr, sgc->tleSortGroupRef);
3247
3248
      /* ... and it also should be emitted by the input paths. */
3249
0
      add_column_to_pathtarget(agg_input, expr, sgc->tleSortGroupRef);
3250
3251
      /* Record this SortGroupClause and grouping expression */
3252
0
      *group_clauses = lappend(*group_clauses, sgc);
3253
0
      *group_exprs = lappend(*group_exprs, expr);
3254
0
    }
3255
0
    else if (is_var_in_aggref_only(root, (Var *) expr))
3256
0
    {
3257
      /*
3258
       * The expression is referenced by an aggregate function pushed
3259
       * down to this relation and does not appear elsewhere in the
3260
       * targetlist or havingQual.  Add it to 'agg_input' but not to
3261
       * 'target'.
3262
       */
3263
0
      add_new_column_to_pathtarget(agg_input, expr);
3264
0
    }
3265
0
    else
3266
0
    {
3267
      /*
3268
       * The expression may be functionally dependent on other
3269
       * expressions in the target, but we cannot verify this until all
3270
       * target expressions have been constructed.
3271
       */
3272
0
      possibly_dependent = lappend(possibly_dependent, expr);
3273
0
    }
3274
0
  }
3275
3276
  /*
3277
   * Now we can verify whether an expression is functionally dependent on
3278
   * others.
3279
   */
3280
0
  foreach(lc, possibly_dependent)
3281
0
  {
3282
0
    Var      *tvar;
3283
0
    List     *deps = NIL;
3284
0
    RangeTblEntry *rte;
3285
3286
0
    tvar = lfirst_node(Var, lc);
3287
0
    rte = root->simple_rte_array[tvar->varno];
3288
3289
0
    if (check_functional_grouping(rte->relid, tvar->varno,
3290
0
                    tvar->varlevelsup,
3291
0
                    target->exprs, &deps))
3292
0
    {
3293
      /*
3294
       * The expression is functionally dependent on other target
3295
       * expressions, so it can be included in the targets.  Since it
3296
       * will not be used as a grouping key, a sortgroupref is not
3297
       * needed for it.
3298
       */
3299
0
      add_new_column_to_pathtarget(target, (Expr *) tvar);
3300
0
      add_new_column_to_pathtarget(agg_input, (Expr *) tvar);
3301
0
    }
3302
0
    else
3303
0
    {
3304
      /*
3305
       * We may arrive here with a grouping expression that is proven
3306
       * redundant by EquivalenceClass processing, such as 't1.a' in the
3307
       * query below.
3308
       *
3309
       * select max(t1.c) from t t1, t t2 where t1.a = 1 group by t1.a,
3310
       * t1.b;
3311
       *
3312
       * For now we just give up in this case.
3313
       */
3314
0
      return false;
3315
0
    }
3316
0
  }
3317
3318
0
  return true;
3319
0
}
3320
3321
/*
3322
 * is_var_in_aggref_only
3323
 *    Check whether the given Var appears in aggregate expressions and not
3324
 *    elsewhere in the targetlist or havingQual.
3325
 */
3326
static bool
3327
is_var_in_aggref_only(PlannerInfo *root, Var *var)
3328
0
{
3329
0
  ListCell   *lc;
3330
3331
  /*
3332
   * Search the list of aggregate expressions for the Var.
3333
   */
3334
0
  foreach(lc, root->agg_clause_list)
3335
0
  {
3336
0
    AggClauseInfo *ac_info = lfirst_node(AggClauseInfo, lc);
3337
0
    List     *vars;
3338
3339
0
    Assert(IsA(ac_info->aggref, Aggref));
3340
3341
0
    if (!bms_is_member(var->varno, ac_info->agg_eval_at))
3342
0
      continue;
3343
3344
0
    vars = pull_var_clause((Node *) ac_info->aggref,
3345
0
                 PVC_RECURSE_AGGREGATES |
3346
0
                 PVC_RECURSE_WINDOWFUNCS |
3347
0
                 PVC_RECURSE_PLACEHOLDERS);
3348
3349
0
    if (list_member(vars, var))
3350
0
    {
3351
0
      list_free(vars);
3352
0
      break;
3353
0
    }
3354
3355
0
    list_free(vars);
3356
0
  }
3357
3358
0
  return (lc != NULL && !list_member(root->tlist_vars, var));
3359
0
}
3360
3361
/*
3362
 * is_var_needed_by_join
3363
 *    Check if the given Var is needed by joins above the current rel.
3364
 */
3365
static bool
3366
is_var_needed_by_join(PlannerInfo *root, Var *var, RelOptInfo *rel)
3367
0
{
3368
0
  Relids    relids;
3369
0
  int     attno;
3370
0
  RelOptInfo *baserel;
3371
3372
  /*
3373
   * Note that when checking if the Var is needed by joins above, we want to
3374
   * exclude cases where the Var is only needed in the final targetlist.  So
3375
   * include "relation 0" in the check.
3376
   */
3377
0
  relids = bms_copy(rel->relids);
3378
0
  relids = bms_add_member(relids, 0);
3379
3380
0
  baserel = find_base_rel(root, var->varno);
3381
0
  attno = var->varattno - baserel->min_attr;
3382
3383
0
  return bms_nonempty_difference(baserel->attr_needed[attno], relids);
3384
0
}
3385
3386
/*
3387
 * get_expression_sortgroupref
3388
 *    Return the sortgroupref of the given "expr" if it is found among the
3389
 *    original grouping expressions, or is known equal to any of the original
3390
 *    grouping expressions due to equivalence relationships.  Return 0 if no
3391
 *    match is found.
3392
 */
3393
static Index
3394
get_expression_sortgroupref(PlannerInfo *root, Expr *expr)
3395
0
{
3396
0
  ListCell   *lc;
3397
3398
0
  Assert(IsA(expr, Var));
3399
3400
0
  foreach(lc, root->group_expr_list)
3401
0
  {
3402
0
    GroupingExprInfo *ge_info = lfirst_node(GroupingExprInfo, lc);
3403
0
    ListCell   *lc1;
3404
3405
0
    Assert(IsA(ge_info->expr, Var));
3406
0
    Assert(ge_info->sortgroupref > 0);
3407
3408
0
    if (equal(expr, ge_info->expr))
3409
0
      return ge_info->sortgroupref;
3410
3411
0
    if (ge_info->ec == NULL ||
3412
0
      !bms_is_member(((Var *) expr)->varno, ge_info->ec->ec_relids))
3413
0
      continue;
3414
3415
    /* The grouping operators can't be applied to a cross-type member */
3416
0
    if (exprType((Node *) expr) != exprType((Node *) ge_info->expr))
3417
0
      continue;
3418
3419
    /*
3420
     * Scan the EquivalenceClass, looking for a match to the given
3421
     * expression.  We ignore child members here.
3422
     */
3423
0
    foreach(lc1, ge_info->ec->ec_members)
3424
0
    {
3425
0
      EquivalenceMember *em = (EquivalenceMember *) lfirst(lc1);
3426
3427
      /* Child members should not exist in ec_members */
3428
0
      Assert(!em->em_is_child);
3429
3430
0
      if (equal(expr, em->em_expr))
3431
0
        return ge_info->sortgroupref;
3432
0
    }
3433
0
  }
3434
3435
  /* no match is found */
3436
0
  return 0;
3437
0
}