PostgreSQL Source Code  git master
plancat.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * plancat.c
4  * routines for accessing the system catalogs
5  *
6  *
7  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  * src/backend/optimizer/util/plancat.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17 
18 #include <math.h>
19 
20 #include "access/genam.h"
21 #include "access/htup_details.h"
22 #include "access/nbtree.h"
23 #include "access/sysattr.h"
24 #include "access/table.h"
25 #include "access/tableam.h"
26 #include "access/transam.h"
27 #include "access/xlog.h"
28 #include "catalog/catalog.h"
29 #include "catalog/heap.h"
30 #include "catalog/index.h"
31 #include "catalog/pg_am.h"
32 #include "catalog/pg_proc.h"
34 #include "foreign/fdwapi.h"
35 #include "miscadmin.h"
36 #include "nodes/makefuncs.h"
37 #include "nodes/supportnodes.h"
38 #include "optimizer/clauses.h"
39 #include "optimizer/cost.h"
40 #include "optimizer/optimizer.h"
41 #include "optimizer/plancat.h"
42 #include "optimizer/prep.h"
43 #include "parser/parse_relation.h"
44 #include "parser/parsetree.h"
45 #include "partitioning/partdesc.h"
46 #include "rewrite/rewriteManip.h"
47 #include "statistics/statistics.h"
48 #include "storage/bufmgr.h"
49 #include "utils/builtins.h"
50 #include "utils/lsyscache.h"
51 #include "utils/partcache.h"
52 #include "utils/rel.h"
53 #include "utils/snapmgr.h"
54 #include "utils/syscache.h"
55 
56 /* GUC parameter */
58 
59 /* Hook for plugins to get control in get_relation_info() */
61 
62 
63 static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
64  Relation relation, bool inhparent);
65 static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
66  List *idxExprs);
68  Oid relationObjectId, RelOptInfo *rel,
69  bool include_noinherit,
70  bool include_notnull,
71  bool include_partition);
73  Relation heapRelation);
74 static List *get_relation_statistics(RelOptInfo *rel, Relation relation);
75 static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel,
76  Relation relation);
78 static void set_baserel_partition_key_exprs(Relation relation,
79  RelOptInfo *rel);
80 static void set_baserel_partition_constraint(Relation relation,
81  RelOptInfo *rel);
82 
83 
84 /*
85  * get_relation_info -
86  * Retrieves catalog information for a given relation.
87  *
88  * Given the Oid of the relation, return the following info into fields
89  * of the RelOptInfo struct:
90  *
91  * min_attr lowest valid AttrNumber
92  * max_attr highest valid AttrNumber
93  * indexlist list of IndexOptInfos for relation's indexes
94  * statlist list of StatisticExtInfo for relation's statistic objects
95  * serverid if it's a foreign table, the server OID
96  * fdwroutine if it's a foreign table, the FDW function pointers
97  * pages number of pages
98  * tuples number of tuples
99  * rel_parallel_workers user-defined number of parallel workers
100  *
101  * Also, add information about the relation's foreign keys to root->fkey_list.
102  *
103  * Also, initialize the attr_needed[] and attr_widths[] arrays. In most
104  * cases these are left as zeroes, but sometimes we need to compute attr
105  * widths here, and we may as well cache the results for costsize.c.
106  *
107  * If inhparent is true, all we need to do is set up the attr arrays:
108  * the RelOptInfo actually represents the appendrel formed by an inheritance
109  * tree, and so the parent rel's physical size and index information isn't
110  * important for it.
111  */
112 void
113 get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
114  RelOptInfo *rel)
115 {
116  Index varno = rel->relid;
117  Relation relation;
118  bool hasindex;
119  List *indexinfos = NIL;
120 
121  /*
122  * We need not lock the relation since it was already locked, either by
123  * the rewriter or when expand_inherited_rtentry() added it to the query's
124  * rangetable.
125  */
126  relation = table_open(relationObjectId, NoLock);
127 
128  /* Temporary and unlogged relations are inaccessible during recovery. */
129  if (relation->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT &&
131  ereport(ERROR,
132  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
133  errmsg("cannot access temporary or unlogged relations during recovery")));
134 
136  rel->max_attr = RelationGetNumberOfAttributes(relation);
137  rel->reltablespace = RelationGetForm(relation)->reltablespace;
138 
139  Assert(rel->max_attr >= rel->min_attr);
140  rel->attr_needed = (Relids *)
141  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
142  rel->attr_widths = (int32 *)
143  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
144 
145  /*
146  * Estimate relation size --- unless it's an inheritance parent, in which
147  * case the size we want is not the rel's own size but the size of its
148  * inheritance tree. That will be computed in set_append_rel_size().
149  */
150  if (!inhparent)
151  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
152  &rel->pages, &rel->tuples, &rel->allvisfrac);
153 
154  /* Retrieve the parallel_workers reloption, or -1 if not set. */
156 
157  /*
158  * Make list of indexes. Ignore indexes on system catalogs if told to.
159  * Don't bother with indexes for an inheritance parent, either.
160  */
161  if (inhparent ||
162  (IgnoreSystemIndexes && IsSystemRelation(relation)))
163  hasindex = false;
164  else
165  hasindex = relation->rd_rel->relhasindex;
166 
167  if (hasindex)
168  {
169  List *indexoidlist;
170  LOCKMODE lmode;
171  ListCell *l;
172 
173  indexoidlist = RelationGetIndexList(relation);
174 
175  /*
176  * For each index, we get the same type of lock that the executor will
177  * need, and do not release it. This saves a couple of trips to the
178  * shared lock manager while not creating any real loss of
179  * concurrency, because no schema changes could be happening on the
180  * index while we hold lock on the parent rel, and no lock type used
181  * for queries blocks any other kind of index operation.
182  */
183  lmode = root->simple_rte_array[varno]->rellockmode;
184 
185  foreach(l, indexoidlist)
186  {
187  Oid indexoid = lfirst_oid(l);
188  Relation indexRelation;
190  IndexAmRoutine *amroutine;
191  IndexOptInfo *info;
192  int ncolumns,
193  nkeycolumns;
194  int i;
195 
196  /*
197  * Extract info from the relation descriptor for the index.
198  */
199  indexRelation = index_open(indexoid, lmode);
200  index = indexRelation->rd_index;
201 
202  /* Warn if any dependent collations' versions have moved. */
203  if (!IsSystemRelation(relation) &&
204  !indexRelation->rd_version_checked)
205  {
207  indexRelation->rd_version_checked = true;
208  }
209 
210  /*
211  * Ignore invalid indexes, since they can't safely be used for
212  * queries. Note that this is OK because the data structure we
213  * are constructing is only used by the planner --- the executor
214  * still needs to insert into "invalid" indexes, if they're marked
215  * indisready.
216  */
217  if (!index->indisvalid)
218  {
219  index_close(indexRelation, NoLock);
220  continue;
221  }
222 
223  /*
224  * Ignore partitioned indexes, since they are not usable for
225  * queries.
226  */
227  if (indexRelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
228  {
229  index_close(indexRelation, NoLock);
230  continue;
231  }
232 
233  /*
234  * If the index is valid, but cannot yet be used, ignore it; but
235  * mark the plan we are generating as transient. See
236  * src/backend/access/heap/README.HOT for discussion.
237  */
238  if (index->indcheckxmin &&
241  {
242  root->glob->transientPlan = true;
243  index_close(indexRelation, NoLock);
244  continue;
245  }
246 
247  info = makeNode(IndexOptInfo);
248 
249  info->indexoid = index->indexrelid;
250  info->reltablespace =
251  RelationGetForm(indexRelation)->reltablespace;
252  info->rel = rel;
253  info->ncolumns = ncolumns = index->indnatts;
254  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
255 
256  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
257  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
258  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
259  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
260  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
261 
262  for (i = 0; i < ncolumns; i++)
263  {
264  info->indexkeys[i] = index->indkey.values[i];
265  info->canreturn[i] = index_can_return(indexRelation, i + 1);
266  }
267 
268  for (i = 0; i < nkeycolumns; i++)
269  {
270  info->opfamily[i] = indexRelation->rd_opfamily[i];
271  info->opcintype[i] = indexRelation->rd_opcintype[i];
272  info->indexcollations[i] = indexRelation->rd_indcollation[i];
273  }
274 
275  info->relam = indexRelation->rd_rel->relam;
276 
277  /* We copy just the fields we need, not all of rd_indam */
278  amroutine = indexRelation->rd_indam;
279  info->amcanorderbyop = amroutine->amcanorderbyop;
280  info->amoptionalkey = amroutine->amoptionalkey;
281  info->amsearcharray = amroutine->amsearcharray;
282  info->amsearchnulls = amroutine->amsearchnulls;
283  info->amcanparallel = amroutine->amcanparallel;
284  info->amhasgettuple = (amroutine->amgettuple != NULL);
285  info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
286  relation->rd_tableam->scan_bitmap_next_block != NULL;
287  info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
288  amroutine->amrestrpos != NULL);
289  info->amcostestimate = amroutine->amcostestimate;
290  Assert(info->amcostestimate != NULL);
291 
292  /* Fetch index opclass options */
293  info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
294 
295  /*
296  * Fetch the ordering information for the index, if any.
297  */
298  if (info->relam == BTREE_AM_OID)
299  {
300  /*
301  * If it's a btree index, we can use its opfamily OIDs
302  * directly as the sort ordering opfamily OIDs.
303  */
304  Assert(amroutine->amcanorder);
305 
306  info->sortopfamily = info->opfamily;
307  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
308  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
309 
310  for (i = 0; i < nkeycolumns; i++)
311  {
312  int16 opt = indexRelation->rd_indoption[i];
313 
314  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
315  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
316  }
317  }
318  else if (amroutine->amcanorder)
319  {
320  /*
321  * Otherwise, identify the corresponding btree opfamilies by
322  * trying to map this index's "<" operators into btree. Since
323  * "<" uniquely defines the behavior of a sort order, this is
324  * a sufficient test.
325  *
326  * XXX This method is rather slow and also requires the
327  * undesirable assumption that the other index AM numbers its
328  * strategies the same as btree. It'd be better to have a way
329  * to explicitly declare the corresponding btree opfamily for
330  * each opfamily of the other index type. But given the lack
331  * of current or foreseeable amcanorder index types, it's not
332  * worth expending more effort on now.
333  */
334  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
335  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
336  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
337 
338  for (i = 0; i < nkeycolumns; i++)
339  {
340  int16 opt = indexRelation->rd_indoption[i];
341  Oid ltopr;
342  Oid btopfamily;
343  Oid btopcintype;
344  int16 btstrategy;
345 
346  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
347  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
348 
349  ltopr = get_opfamily_member(info->opfamily[i],
350  info->opcintype[i],
351  info->opcintype[i],
353  if (OidIsValid(ltopr) &&
355  &btopfamily,
356  &btopcintype,
357  &btstrategy) &&
358  btopcintype == info->opcintype[i] &&
359  btstrategy == BTLessStrategyNumber)
360  {
361  /* Successful mapping */
362  info->sortopfamily[i] = btopfamily;
363  }
364  else
365  {
366  /* Fail ... quietly treat index as unordered */
367  info->sortopfamily = NULL;
368  info->reverse_sort = NULL;
369  info->nulls_first = NULL;
370  break;
371  }
372  }
373  }
374  else
375  {
376  info->sortopfamily = NULL;
377  info->reverse_sort = NULL;
378  info->nulls_first = NULL;
379  }
380 
381  /*
382  * Fetch the index expressions and predicate, if any. We must
383  * modify the copies we obtain from the relcache to have the
384  * correct varno for the parent relation, so that they match up
385  * correctly against qual clauses.
386  */
387  info->indexprs = RelationGetIndexExpressions(indexRelation);
388  info->indpred = RelationGetIndexPredicate(indexRelation);
389  if (info->indexprs && varno != 1)
390  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
391  if (info->indpred && varno != 1)
392  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
393 
394  /* Build targetlist using the completed indexprs data */
395  info->indextlist = build_index_tlist(root, info, relation);
396 
397  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
398  info->predOK = false; /* set later, in indxpath.c */
399  info->unique = index->indisunique;
400  info->immediate = index->indimmediate;
401  info->hypothetical = false;
402 
403  /*
404  * Estimate the index size. If it's not a partial index, we lock
405  * the number-of-tuples estimate to equal the parent table; if it
406  * is partial then we have to use the same methods as we would for
407  * a table, except we can be sure that the index is not larger
408  * than the table.
409  */
410  if (info->indpred == NIL)
411  {
412  info->pages = RelationGetNumberOfBlocks(indexRelation);
413  info->tuples = rel->tuples;
414  }
415  else
416  {
417  double allvisfrac; /* dummy */
418 
419  estimate_rel_size(indexRelation, NULL,
420  &info->pages, &info->tuples, &allvisfrac);
421  if (info->tuples > rel->tuples)
422  info->tuples = rel->tuples;
423  }
424 
425  if (info->relam == BTREE_AM_OID)
426  {
427  /* For btrees, get tree height while we have the index open */
428  info->tree_height = _bt_getrootheight(indexRelation);
429  }
430  else
431  {
432  /* For other index types, just set it to "unknown" for now */
433  info->tree_height = -1;
434  }
435 
436  index_close(indexRelation, NoLock);
437 
438  /*
439  * We've historically used lcons() here. It'd make more sense to
440  * use lappend(), but that causes the planner to change behavior
441  * in cases where two indexes seem equally attractive. For now,
442  * stick with lcons() --- few tables should have so many indexes
443  * that the O(N^2) behavior of lcons() is really a problem.
444  */
445  indexinfos = lcons(info, indexinfos);
446  }
447 
448  list_free(indexoidlist);
449  }
450 
451  rel->indexlist = indexinfos;
452 
453  rel->statlist = get_relation_statistics(rel, relation);
454 
455  /* Grab foreign-table info using the relcache, while we have it */
456  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
457  {
459  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
460  }
461  else
462  {
463  rel->serverid = InvalidOid;
464  rel->fdwroutine = NULL;
465  }
466 
467  /* Collect info about relation's foreign keys, if relevant */
468  get_relation_foreign_keys(root, rel, relation, inhparent);
469 
470  /* Collect info about functions implemented by the rel's table AM. */
471  if (relation->rd_tableam &&
472  relation->rd_tableam->scan_set_tidrange != NULL &&
473  relation->rd_tableam->scan_getnextslot_tidrange != NULL)
475 
476  /*
477  * Collect info about relation's partitioning scheme, if any. Only
478  * inheritance parents may be partitioned.
479  */
480  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
481  set_relation_partition_info(root, rel, relation);
482 
483  table_close(relation, NoLock);
484 
485  /*
486  * Allow a plugin to editorialize on the info we obtained from the
487  * catalogs. Actions might include altering the assumed relation size,
488  * removing an index, or adding a hypothetical index to the indexlist.
489  */
491  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
492 }
493 
494 /*
495  * get_relation_foreign_keys -
496  * Retrieves foreign key information for a given relation.
497  *
498  * ForeignKeyOptInfos for relevant foreign keys are created and added to
499  * root->fkey_list. We do this now while we have the relcache entry open.
500  * We could sometimes avoid making useless ForeignKeyOptInfos if we waited
501  * until all RelOptInfos have been built, but the cost of re-opening the
502  * relcache entries would probably exceed any savings.
503  */
504 static void
506  Relation relation, bool inhparent)
507 {
508  List *rtable = root->parse->rtable;
509  List *cachedfkeys;
510  ListCell *lc;
511 
512  /*
513  * If it's not a baserel, we don't care about its FKs. Also, if the query
514  * references only a single relation, we can skip the lookup since no FKs
515  * could satisfy the requirements below.
516  */
517  if (rel->reloptkind != RELOPT_BASEREL ||
518  list_length(rtable) < 2)
519  return;
520 
521  /*
522  * If it's the parent of an inheritance tree, ignore its FKs. We could
523  * make useful FK-based deductions if we found that all members of the
524  * inheritance tree have equivalent FK constraints, but detecting that
525  * would require code that hasn't been written.
526  */
527  if (inhparent)
528  return;
529 
530  /*
531  * Extract data about relation's FKs from the relcache. Note that this
532  * list belongs to the relcache and might disappear in a cache flush, so
533  * we must not do any further catalog access within this function.
534  */
535  cachedfkeys = RelationGetFKeyList(relation);
536 
537  /*
538  * Figure out which FKs are of interest for this query, and create
539  * ForeignKeyOptInfos for them. We want only FKs that reference some
540  * other RTE of the current query. In queries containing self-joins,
541  * there might be more than one other RTE for a referenced table, and we
542  * should make a ForeignKeyOptInfo for each occurrence.
543  *
544  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
545  * too hard to identify those here, so we might end up making some useless
546  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
547  * them again.
548  */
549  foreach(lc, cachedfkeys)
550  {
551  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
552  Index rti;
553  ListCell *lc2;
554 
555  /* conrelid should always be that of the table we're considering */
556  Assert(cachedfk->conrelid == RelationGetRelid(relation));
557 
558  /* Scan to find other RTEs matching confrelid */
559  rti = 0;
560  foreach(lc2, rtable)
561  {
562  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
563  ForeignKeyOptInfo *info;
564 
565  rti++;
566  /* Ignore if not the correct table */
567  if (rte->rtekind != RTE_RELATION ||
568  rte->relid != cachedfk->confrelid)
569  continue;
570  /* Ignore if it's an inheritance parent; doesn't really match */
571  if (rte->inh)
572  continue;
573  /* Ignore self-referential FKs; we only care about joins */
574  if (rti == rel->relid)
575  continue;
576 
577  /* OK, let's make an entry */
578  info = makeNode(ForeignKeyOptInfo);
579  info->con_relid = rel->relid;
580  info->ref_relid = rti;
581  info->nkeys = cachedfk->nkeys;
582  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
583  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
584  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
585  /* zero out fields to be filled by match_foreign_keys_to_quals */
586  info->nmatched_ec = 0;
587  info->nconst_ec = 0;
588  info->nmatched_rcols = 0;
589  info->nmatched_ri = 0;
590  memset(info->eclass, 0, sizeof(info->eclass));
591  memset(info->fk_eclass_member, 0, sizeof(info->fk_eclass_member));
592  memset(info->rinfos, 0, sizeof(info->rinfos));
593 
594  root->fkey_list = lappend(root->fkey_list, info);
595  }
596  }
597 }
598 
599 /*
600  * infer_arbiter_indexes -
601  * Determine the unique indexes used to arbitrate speculative insertion.
602  *
603  * Uses user-supplied inference clause expressions and predicate to match a
604  * unique index from those defined and ready on the heap relation (target).
605  * An exact match is required on columns/expressions (although they can appear
606  * in any order). However, the predicate given by the user need only restrict
607  * insertion to a subset of some part of the table covered by some particular
608  * unique index (in particular, a partial unique index) in order to be
609  * inferred.
610  *
611  * The implementation does not consider which B-Tree operator class any
612  * particular available unique index attribute uses, unless one was specified
613  * in the inference specification. The same is true of collations. In
614  * particular, there is no system dependency on the default operator class for
615  * the purposes of inference. If no opclass (or collation) is specified, then
616  * all matching indexes (that may or may not match the default in terms of
617  * each attribute opclass/collation) are used for inference.
618  */
619 List *
621 {
622  OnConflictExpr *onconflict = root->parse->onConflict;
623 
624  /* Iteration state */
625  RangeTblEntry *rte;
626  Relation relation;
627  Oid indexOidFromConstraint = InvalidOid;
628  List *indexList;
629  ListCell *l;
630 
631  /* Normalized inference attributes and inference expressions: */
632  Bitmapset *inferAttrs = NULL;
633  List *inferElems = NIL;
634 
635  /* Results */
636  List *results = NIL;
637 
638  /*
639  * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
640  * specification or named constraint. ON CONFLICT DO UPDATE statements
641  * must always provide one or the other (but parser ought to have caught
642  * that already).
643  */
644  if (onconflict->arbiterElems == NIL &&
645  onconflict->constraint == InvalidOid)
646  return NIL;
647 
648  /*
649  * We need not lock the relation since it was already locked, either by
650  * the rewriter or when expand_inherited_rtentry() added it to the query's
651  * rangetable.
652  */
653  rte = rt_fetch(root->parse->resultRelation, root->parse->rtable);
654 
655  relation = table_open(rte->relid, NoLock);
656 
657  /*
658  * Build normalized/BMS representation of plain indexed attributes, as
659  * well as a separate list of expression items. This simplifies matching
660  * the cataloged definition of indexes.
661  */
662  foreach(l, onconflict->arbiterElems)
663  {
664  InferenceElem *elem = (InferenceElem *) lfirst(l);
665  Var *var;
666  int attno;
667 
668  if (!IsA(elem->expr, Var))
669  {
670  /* If not a plain Var, just shove it in inferElems for now */
671  inferElems = lappend(inferElems, elem->expr);
672  continue;
673  }
674 
675  var = (Var *) elem->expr;
676  attno = var->varattno;
677 
678  if (attno == 0)
679  ereport(ERROR,
680  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
681  errmsg("whole row unique index inference specifications are not supported")));
682 
683  inferAttrs = bms_add_member(inferAttrs,
685  }
686 
687  /*
688  * Lookup named constraint's index. This is not immediately returned
689  * because some additional sanity checks are required.
690  */
691  if (onconflict->constraint != InvalidOid)
692  {
693  indexOidFromConstraint = get_constraint_index(onconflict->constraint);
694 
695  if (indexOidFromConstraint == InvalidOid)
696  ereport(ERROR,
697  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
698  errmsg("constraint in ON CONFLICT clause has no associated index")));
699  }
700 
701  /*
702  * Using that representation, iterate through the list of indexes on the
703  * target relation to try and find a match
704  */
705  indexList = RelationGetIndexList(relation);
706 
707  foreach(l, indexList)
708  {
709  Oid indexoid = lfirst_oid(l);
710  Relation idxRel;
711  Form_pg_index idxForm;
712  Bitmapset *indexedAttrs;
713  List *idxExprs;
714  List *predExprs;
715  AttrNumber natt;
716  ListCell *el;
717 
718  /*
719  * Extract info from the relation descriptor for the index. Obtain
720  * the same lock type that the executor will ultimately use.
721  *
722  * Let executor complain about !indimmediate case directly, because
723  * enforcement needs to occur there anyway when an inference clause is
724  * omitted.
725  */
726  idxRel = index_open(indexoid, rte->rellockmode);
727  idxForm = idxRel->rd_index;
728 
729  if (!idxForm->indisvalid)
730  goto next;
731 
732  /*
733  * Note that we do not perform a check against indcheckxmin (like e.g.
734  * get_relation_info()) here to eliminate candidates, because
735  * uniqueness checking only cares about the most recently committed
736  * tuple versions.
737  */
738 
739  /*
740  * Look for match on "ON constraint_name" variant, which may not be
741  * unique constraint. This can only be a constraint name.
742  */
743  if (indexOidFromConstraint == idxForm->indexrelid)
744  {
745  if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
746  ereport(ERROR,
747  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
748  errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
749 
750  results = lappend_oid(results, idxForm->indexrelid);
751  list_free(indexList);
752  index_close(idxRel, NoLock);
753  table_close(relation, NoLock);
754  return results;
755  }
756  else if (indexOidFromConstraint != InvalidOid)
757  {
758  /* No point in further work for index in named constraint case */
759  goto next;
760  }
761 
762  /*
763  * Only considering conventional inference at this point (not named
764  * constraints), so index under consideration can be immediately
765  * skipped if it's not unique
766  */
767  if (!idxForm->indisunique)
768  goto next;
769 
770  /* Build BMS representation of plain (non expression) index attrs */
771  indexedAttrs = NULL;
772  for (natt = 0; natt < idxForm->indnkeyatts; natt++)
773  {
774  int attno = idxRel->rd_index->indkey.values[natt];
775 
776  if (attno != 0)
777  indexedAttrs = bms_add_member(indexedAttrs,
779  }
780 
781  /* Non-expression attributes (if any) must match */
782  if (!bms_equal(indexedAttrs, inferAttrs))
783  goto next;
784 
785  /* Expression attributes (if any) must match */
786  idxExprs = RelationGetIndexExpressions(idxRel);
787  foreach(el, onconflict->arbiterElems)
788  {
789  InferenceElem *elem = (InferenceElem *) lfirst(el);
790 
791  /*
792  * Ensure that collation/opclass aspects of inference expression
793  * element match. Even though this loop is primarily concerned
794  * with matching expressions, it is a convenient point to check
795  * this for both expressions and ordinary (non-expression)
796  * attributes appearing as inference elements.
797  */
798  if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
799  goto next;
800 
801  /*
802  * Plain Vars don't factor into count of expression elements, and
803  * the question of whether or not they satisfy the index
804  * definition has already been considered (they must).
805  */
806  if (IsA(elem->expr, Var))
807  continue;
808 
809  /*
810  * Might as well avoid redundant check in the rare cases where
811  * infer_collation_opclass_match() is required to do real work.
812  * Otherwise, check that element expression appears in cataloged
813  * index definition.
814  */
815  if (elem->infercollid != InvalidOid ||
816  elem->inferopclass != InvalidOid ||
817  list_member(idxExprs, elem->expr))
818  continue;
819 
820  goto next;
821  }
822 
823  /*
824  * Now that all inference elements were matched, ensure that the
825  * expression elements from inference clause are not missing any
826  * cataloged expressions. This does the right thing when unique
827  * indexes redundantly repeat the same attribute, or if attributes
828  * redundantly appear multiple times within an inference clause.
829  */
830  if (list_difference(idxExprs, inferElems) != NIL)
831  goto next;
832 
833  /*
834  * If it's a partial index, its predicate must be implied by the ON
835  * CONFLICT's WHERE clause.
836  */
837  predExprs = RelationGetIndexPredicate(idxRel);
838 
839  if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, false))
840  goto next;
841 
842  results = lappend_oid(results, idxForm->indexrelid);
843 next:
844  index_close(idxRel, NoLock);
845  }
846 
847  list_free(indexList);
848  table_close(relation, NoLock);
849 
850  if (results == NIL)
851  ereport(ERROR,
852  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
853  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
854 
855  return results;
856 }
857 
858 /*
859  * infer_collation_opclass_match - ensure infer element opclass/collation match
860  *
861  * Given unique index inference element from inference specification, if
862  * collation was specified, or if opclass was specified, verify that there is
863  * at least one matching indexed attribute (occasionally, there may be more).
864  * Skip this in the common case where inference specification does not include
865  * collation or opclass (instead matching everything, regardless of cataloged
866  * collation/opclass of indexed attribute).
867  *
868  * At least historically, Postgres has not offered collations or opclasses
869  * with alternative-to-default notions of equality, so these additional
870  * criteria should only be required infrequently.
871  *
872  * Don't give up immediately when an inference element matches some attribute
873  * cataloged as indexed but not matching additional opclass/collation
874  * criteria. This is done so that the implementation is as forgiving as
875  * possible of redundancy within cataloged index attributes (or, less
876  * usefully, within inference specification elements). If collations actually
877  * differ between apparently redundantly indexed attributes (redundant within
878  * or across indexes), then there really is no redundancy as such.
879  *
880  * Note that if an inference element specifies an opclass and a collation at
881  * once, both must match in at least one particular attribute within index
882  * catalog definition in order for that inference element to be considered
883  * inferred/satisfied.
884  */
885 static bool
887  List *idxExprs)
888 {
889  AttrNumber natt;
890  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
891  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
892  int nplain = 0; /* # plain attrs observed */
893 
894  /*
895  * If inference specification element lacks collation/opclass, then no
896  * need to check for exact match.
897  */
898  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
899  return true;
900 
901  /*
902  * Lookup opfamily and input type, for matching indexes
903  */
904  if (elem->inferopclass)
905  {
906  inferopfamily = get_opclass_family(elem->inferopclass);
907  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
908  }
909 
910  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
911  {
912  Oid opfamily = idxRel->rd_opfamily[natt - 1];
913  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
914  Oid collation = idxRel->rd_indcollation[natt - 1];
915  int attno = idxRel->rd_index->indkey.values[natt - 1];
916 
917  if (attno != 0)
918  nplain++;
919 
920  if (elem->inferopclass != InvalidOid &&
921  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
922  {
923  /* Attribute needed to match opclass, but didn't */
924  continue;
925  }
926 
927  if (elem->infercollid != InvalidOid &&
928  elem->infercollid != collation)
929  {
930  /* Attribute needed to match collation, but didn't */
931  continue;
932  }
933 
934  /* If one matching index att found, good enough -- return true */
935  if (IsA(elem->expr, Var))
936  {
937  if (((Var *) elem->expr)->varattno == attno)
938  return true;
939  }
940  else if (attno == 0)
941  {
942  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
943 
944  /*
945  * Note that unlike routines like match_index_to_operand() we
946  * don't need to care about RelabelType. Neither the index
947  * definition nor the inference clause should contain them.
948  */
949  if (equal(elem->expr, nattExpr))
950  return true;
951  }
952  }
953 
954  return false;
955 }
956 
957 /*
958  * estimate_rel_size - estimate # pages and # tuples in a table or index
959  *
960  * We also estimate the fraction of the pages that are marked all-visible in
961  * the visibility map, for use in estimation of index-only scans.
962  *
963  * If attr_widths isn't NULL, it points to the zero-index entry of the
964  * relation's attr_widths[] cache; we fill this in if we have need to compute
965  * the attribute widths for estimation purposes.
966  */
967 void
968 estimate_rel_size(Relation rel, int32 *attr_widths,
969  BlockNumber *pages, double *tuples, double *allvisfrac)
970 {
971  BlockNumber curpages;
972  BlockNumber relpages;
973  double reltuples;
974  BlockNumber relallvisible;
975  double density;
976 
977  switch (rel->rd_rel->relkind)
978  {
979  case RELKIND_RELATION:
980  case RELKIND_MATVIEW:
981  case RELKIND_TOASTVALUE:
982  table_relation_estimate_size(rel, attr_widths, pages, tuples,
983  allvisfrac);
984  break;
985 
986  case RELKIND_INDEX:
987 
988  /*
989  * XXX: It'd probably be good to move this into a callback,
990  * individual index types e.g. know if they have a metapage.
991  */
992 
993  /* it has storage, ok to call the smgr */
994  curpages = RelationGetNumberOfBlocks(rel);
995 
996  /* report estimated # pages */
997  *pages = curpages;
998  /* quick exit if rel is clearly empty */
999  if (curpages == 0)
1000  {
1001  *tuples = 0;
1002  *allvisfrac = 0;
1003  break;
1004  }
1005 
1006  /* coerce values in pg_class to more desirable types */
1007  relpages = (BlockNumber) rel->rd_rel->relpages;
1008  reltuples = (double) rel->rd_rel->reltuples;
1009  relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
1010 
1011  /*
1012  * Discount the metapage while estimating the number of tuples.
1013  * This is a kluge because it assumes more than it ought to about
1014  * index structure. Currently it's OK for btree, hash, and GIN
1015  * indexes but suspect for GiST indexes.
1016  */
1017  if (relpages > 0)
1018  {
1019  curpages--;
1020  relpages--;
1021  }
1022 
1023  /* estimate number of tuples from previous tuple density */
1024  if (reltuples >= 0 && relpages > 0)
1025  density = reltuples / (double) relpages;
1026  else
1027  {
1028  /*
1029  * If we have no data because the relation was never vacuumed,
1030  * estimate tuple width from attribute datatypes. We assume
1031  * here that the pages are completely full, which is OK for
1032  * tables (since they've presumably not been VACUUMed yet) but
1033  * is probably an overestimate for indexes. Fortunately
1034  * get_relation_info() can clamp the overestimate to the
1035  * parent table's size.
1036  *
1037  * Note: this code intentionally disregards alignment
1038  * considerations, because (a) that would be gilding the lily
1039  * considering how crude the estimate is, and (b) it creates
1040  * platform dependencies in the default plans which are kind
1041  * of a headache for regression testing.
1042  *
1043  * XXX: Should this logic be more index specific?
1044  */
1045  int32 tuple_width;
1046 
1047  tuple_width = get_rel_data_width(rel, attr_widths);
1048  tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1049  tuple_width += sizeof(ItemIdData);
1050  /* note: integer division is intentional here */
1051  density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1052  }
1053  *tuples = rint(density * (double) curpages);
1054 
1055  /*
1056  * We use relallvisible as-is, rather than scaling it up like we
1057  * do for the pages and tuples counts, on the theory that any
1058  * pages added since the last VACUUM are most likely not marked
1059  * all-visible. But costsize.c wants it converted to a fraction.
1060  */
1061  if (relallvisible == 0 || curpages <= 0)
1062  *allvisfrac = 0;
1063  else if ((double) relallvisible >= curpages)
1064  *allvisfrac = 1;
1065  else
1066  *allvisfrac = (double) relallvisible / curpages;
1067  break;
1068 
1069  case RELKIND_SEQUENCE:
1070  /* Sequences always have a known size */
1071  *pages = 1;
1072  *tuples = 1;
1073  *allvisfrac = 0;
1074  break;
1075  case RELKIND_FOREIGN_TABLE:
1076  /* Just use whatever's in pg_class */
1077  /* Note that FDW must cope if reltuples is -1! */
1078  *pages = rel->rd_rel->relpages;
1079  *tuples = rel->rd_rel->reltuples;
1080  *allvisfrac = 0;
1081  break;
1082  default:
1083  /* else it has no disk storage; probably shouldn't get here? */
1084  *pages = 0;
1085  *tuples = 0;
1086  *allvisfrac = 0;
1087  break;
1088  }
1089 }
1090 
1091 
1092 /*
1093  * get_rel_data_width
1094  *
1095  * Estimate the average width of (the data part of) the relation's tuples.
1096  *
1097  * If attr_widths isn't NULL, it points to the zero-index entry of the
1098  * relation's attr_widths[] cache; use and update that cache as appropriate.
1099  *
1100  * Currently we ignore dropped columns. Ideally those should be included
1101  * in the result, but we haven't got any way to get info about them; and
1102  * since they might be mostly NULLs, treating them as zero-width is not
1103  * necessarily the wrong thing anyway.
1104  */
1105 int32
1107 {
1108  int32 tuple_width = 0;
1109  int i;
1110 
1111  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1112  {
1113  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1114  int32 item_width;
1115 
1116  if (att->attisdropped)
1117  continue;
1118 
1119  /* use previously cached data, if any */
1120  if (attr_widths != NULL && attr_widths[i] > 0)
1121  {
1122  tuple_width += attr_widths[i];
1123  continue;
1124  }
1125 
1126  /* This should match set_rel_width() in costsize.c */
1127  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1128  if (item_width <= 0)
1129  {
1130  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1131  Assert(item_width > 0);
1132  }
1133  if (attr_widths != NULL)
1134  attr_widths[i] = item_width;
1135  tuple_width += item_width;
1136  }
1137 
1138  return tuple_width;
1139 }
1140 
1141 /*
1142  * get_relation_data_width
1143  *
1144  * External API for get_rel_data_width: same behavior except we have to
1145  * open the relcache entry.
1146  */
1147 int32
1148 get_relation_data_width(Oid relid, int32 *attr_widths)
1149 {
1150  int32 result;
1151  Relation relation;
1152 
1153  /* As above, assume relation is already locked */
1154  relation = table_open(relid, NoLock);
1155 
1156  result = get_rel_data_width(relation, attr_widths);
1157 
1158  table_close(relation, NoLock);
1159 
1160  return result;
1161 }
1162 
1163 
1164 /*
1165  * get_relation_constraints
1166  *
1167  * Retrieve the applicable constraint expressions of the given relation.
1168  *
1169  * Returns a List (possibly empty) of constraint expressions. Each one
1170  * has been canonicalized, and its Vars are changed to have the varno
1171  * indicated by rel->relid. This allows the expressions to be easily
1172  * compared to expressions taken from WHERE.
1173  *
1174  * If include_noinherit is true, it's okay to include constraints that
1175  * are marked NO INHERIT.
1176  *
1177  * If include_notnull is true, "col IS NOT NULL" expressions are generated
1178  * and added to the result for each column that's marked attnotnull.
1179  *
1180  * If include_partition is true, and the relation is a partition,
1181  * also include the partitioning constraints.
1182  *
1183  * Note: at present this is invoked at most once per relation per planner
1184  * run, and in many cases it won't be invoked at all, so there seems no
1185  * point in caching the data in RelOptInfo.
1186  */
1187 static List *
1189  Oid relationObjectId, RelOptInfo *rel,
1190  bool include_noinherit,
1191  bool include_notnull,
1192  bool include_partition)
1193 {
1194  List *result = NIL;
1195  Index varno = rel->relid;
1196  Relation relation;
1197  TupleConstr *constr;
1198 
1199  /*
1200  * We assume the relation has already been safely locked.
1201  */
1202  relation = table_open(relationObjectId, NoLock);
1203 
1204  constr = relation->rd_att->constr;
1205  if (constr != NULL)
1206  {
1207  int num_check = constr->num_check;
1208  int i;
1209 
1210  for (i = 0; i < num_check; i++)
1211  {
1212  Node *cexpr;
1213 
1214  /*
1215  * If this constraint hasn't been fully validated yet, we must
1216  * ignore it here. Also ignore if NO INHERIT and we weren't told
1217  * that that's safe.
1218  */
1219  if (!constr->check[i].ccvalid)
1220  continue;
1221  if (constr->check[i].ccnoinherit && !include_noinherit)
1222  continue;
1223 
1224  cexpr = stringToNode(constr->check[i].ccbin);
1225 
1226  /*
1227  * Run each expression through const-simplification and
1228  * canonicalization. This is not just an optimization, but is
1229  * necessary, because we will be comparing it to
1230  * similarly-processed qual clauses, and may fail to detect valid
1231  * matches without this. This must match the processing done to
1232  * qual clauses in preprocess_expression()! (We can skip the
1233  * stuff involving subqueries, however, since we don't allow any
1234  * in check constraints.)
1235  */
1236  cexpr = eval_const_expressions(root, cexpr);
1237 
1238  cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1239 
1240  /* Fix Vars to have the desired varno */
1241  if (varno != 1)
1242  ChangeVarNodes(cexpr, 1, varno, 0);
1243 
1244  /*
1245  * Finally, convert to implicit-AND format (that is, a List) and
1246  * append the resulting item(s) to our output list.
1247  */
1248  result = list_concat(result,
1249  make_ands_implicit((Expr *) cexpr));
1250  }
1251 
1252  /* Add NOT NULL constraints in expression form, if requested */
1253  if (include_notnull && constr->has_not_null)
1254  {
1255  int natts = relation->rd_att->natts;
1256 
1257  for (i = 1; i <= natts; i++)
1258  {
1259  Form_pg_attribute att = TupleDescAttr(relation->rd_att, i - 1);
1260 
1261  if (att->attnotnull && !att->attisdropped)
1262  {
1263  NullTest *ntest = makeNode(NullTest);
1264 
1265  ntest->arg = (Expr *) makeVar(varno,
1266  i,
1267  att->atttypid,
1268  att->atttypmod,
1269  att->attcollation,
1270  0);
1271  ntest->nulltesttype = IS_NOT_NULL;
1272 
1273  /*
1274  * argisrow=false is correct even for a composite column,
1275  * because attnotnull does not represent a SQL-spec IS NOT
1276  * NULL test in such a case, just IS DISTINCT FROM NULL.
1277  */
1278  ntest->argisrow = false;
1279  ntest->location = -1;
1280  result = lappend(result, ntest);
1281  }
1282  }
1283  }
1284  }
1285 
1286  /*
1287  * Add partitioning constraints, if requested.
1288  */
1289  if (include_partition && relation->rd_rel->relispartition)
1290  {
1291  /* make sure rel->partition_qual is set */
1292  set_baserel_partition_constraint(relation, rel);
1293  result = list_concat(result, rel->partition_qual);
1294  }
1295 
1296  table_close(relation, NoLock);
1297 
1298  return result;
1299 }
1300 
1301 /*
1302  * get_relation_statistics
1303  * Retrieve extended statistics defined on the table.
1304  *
1305  * Returns a List (possibly empty) of StatisticExtInfo objects describing
1306  * the statistics. Note that this doesn't load the actual statistics data,
1307  * just the identifying metadata. Only stats actually built are considered.
1308  */
1309 static List *
1311 {
1312  List *statoidlist;
1313  List *stainfos = NIL;
1314  ListCell *l;
1315 
1316  statoidlist = RelationGetStatExtList(relation);
1317 
1318  foreach(l, statoidlist)
1319  {
1320  Oid statOid = lfirst_oid(l);
1321  Form_pg_statistic_ext staForm;
1322  HeapTuple htup;
1323  HeapTuple dtup;
1324  Bitmapset *keys = NULL;
1325  int i;
1326 
1327  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1328  if (!HeapTupleIsValid(htup))
1329  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1330  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1331 
1333  if (!HeapTupleIsValid(dtup))
1334  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1335 
1336  /*
1337  * First, build the array of columns covered. This is ultimately
1338  * wasted if no stats within the object have actually been built, but
1339  * it doesn't seem worth troubling over that case.
1340  */
1341  for (i = 0; i < staForm->stxkeys.dim1; i++)
1342  keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1343 
1344  /* add one StatisticExtInfo for each kind built */
1345  if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1346  {
1348 
1349  info->statOid = statOid;
1350  info->rel = rel;
1351  info->kind = STATS_EXT_NDISTINCT;
1352  info->keys = bms_copy(keys);
1353 
1354  stainfos = lappend(stainfos, info);
1355  }
1356 
1357  if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1358  {
1360 
1361  info->statOid = statOid;
1362  info->rel = rel;
1363  info->kind = STATS_EXT_DEPENDENCIES;
1364  info->keys = bms_copy(keys);
1365 
1366  stainfos = lappend(stainfos, info);
1367  }
1368 
1369  if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1370  {
1372 
1373  info->statOid = statOid;
1374  info->rel = rel;
1375  info->kind = STATS_EXT_MCV;
1376  info->keys = bms_copy(keys);
1377 
1378  stainfos = lappend(stainfos, info);
1379  }
1380 
1381  ReleaseSysCache(htup);
1382  ReleaseSysCache(dtup);
1383  bms_free(keys);
1384  }
1385 
1386  list_free(statoidlist);
1387 
1388  return stainfos;
1389 }
1390 
1391 /*
1392  * relation_excluded_by_constraints
1393  *
1394  * Detect whether the relation need not be scanned because it has either
1395  * self-inconsistent restrictions, or restrictions inconsistent with the
1396  * relation's applicable constraints.
1397  *
1398  * Note: this examines only rel->relid, rel->reloptkind, and
1399  * rel->baserestrictinfo; therefore it can be called before filling in
1400  * other fields of the RelOptInfo.
1401  */
1402 bool
1404  RelOptInfo *rel, RangeTblEntry *rte)
1405 {
1406  bool include_noinherit;
1407  bool include_notnull;
1408  bool include_partition = false;
1409  List *safe_restrictions;
1410  List *constraint_pred;
1411  List *safe_constraints;
1412  ListCell *lc;
1413 
1414  /* As of now, constraint exclusion works only with simple relations. */
1415  Assert(IS_SIMPLE_REL(rel));
1416 
1417  /*
1418  * If there are no base restriction clauses, we have no hope of proving
1419  * anything below, so fall out quickly.
1420  */
1421  if (rel->baserestrictinfo == NIL)
1422  return false;
1423 
1424  /*
1425  * Regardless of the setting of constraint_exclusion, detect
1426  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1427  * reduce "anything AND FALSE" to just "FALSE", any such case should
1428  * result in exactly one baserestrictinfo entry. This doesn't fire very
1429  * often, but it seems cheap enough to be worth doing anyway. (Without
1430  * this, we'd miss some optimizations that 9.5 and earlier found via much
1431  * more roundabout methods.)
1432  */
1433  if (list_length(rel->baserestrictinfo) == 1)
1434  {
1436  Expr *clause = rinfo->clause;
1437 
1438  if (clause && IsA(clause, Const) &&
1439  (((Const *) clause)->constisnull ||
1440  !DatumGetBool(((Const *) clause)->constvalue)))
1441  return true;
1442  }
1443 
1444  /*
1445  * Skip further tests, depending on constraint_exclusion.
1446  */
1447  switch (constraint_exclusion)
1448  {
1450  /* In 'off' mode, never make any further tests */
1451  return false;
1452 
1454 
1455  /*
1456  * When constraint_exclusion is set to 'partition' we only handle
1457  * appendrel members. Normally, they are RELOPT_OTHER_MEMBER_REL
1458  * relations, but we also consider inherited target relations as
1459  * appendrel members for the purposes of constraint exclusion
1460  * (since, indeed, they were appendrel members earlier in
1461  * inheritance_planner).
1462  *
1463  * In both cases, partition pruning was already applied, so there
1464  * is no need to consider the rel's partition constraints here.
1465  */
1466  if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL ||
1467  (rel->relid == root->parse->resultRelation &&
1468  root->inhTargetKind != INHKIND_NONE))
1469  break; /* appendrel member, so process it */
1470  return false;
1471 
1473 
1474  /*
1475  * In 'on' mode, always apply constraint exclusion. If we are
1476  * considering a baserel that is a partition (i.e., it was
1477  * directly named rather than expanded from a parent table), then
1478  * its partition constraints haven't been considered yet, so
1479  * include them in the processing here.
1480  */
1481  if (rel->reloptkind == RELOPT_BASEREL &&
1482  !(rel->relid == root->parse->resultRelation &&
1483  root->inhTargetKind != INHKIND_NONE))
1484  include_partition = true;
1485  break; /* always try to exclude */
1486  }
1487 
1488  /*
1489  * Check for self-contradictory restriction clauses. We dare not make
1490  * deductions with non-immutable functions, but any immutable clauses that
1491  * are self-contradictory allow us to conclude the scan is unnecessary.
1492  *
1493  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1494  * expecting to see any in its predicate argument.
1495  */
1496  safe_restrictions = NIL;
1497  foreach(lc, rel->baserestrictinfo)
1498  {
1499  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1500 
1501  if (!contain_mutable_functions((Node *) rinfo->clause))
1502  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1503  }
1504 
1505  /*
1506  * We can use weak refutation here, since we're comparing restriction
1507  * clauses with restriction clauses.
1508  */
1509  if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1510  return true;
1511 
1512  /*
1513  * Only plain relations have constraints, so stop here for other rtekinds.
1514  */
1515  if (rte->rtekind != RTE_RELATION)
1516  return false;
1517 
1518  /*
1519  * If we are scanning just this table, we can use NO INHERIT constraints,
1520  * but not if we're scanning its children too. (Note that partitioned
1521  * tables should never have NO INHERIT constraints; but it's not necessary
1522  * for us to assume that here.)
1523  */
1524  include_noinherit = !rte->inh;
1525 
1526  /*
1527  * Currently, attnotnull constraints must be treated as NO INHERIT unless
1528  * this is a partitioned table. In future we might track their
1529  * inheritance status more accurately, allowing this to be refined.
1530  */
1531  include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
1532 
1533  /*
1534  * Fetch the appropriate set of constraint expressions.
1535  */
1536  constraint_pred = get_relation_constraints(root, rte->relid, rel,
1537  include_noinherit,
1538  include_notnull,
1539  include_partition);
1540 
1541  /*
1542  * We do not currently enforce that CHECK constraints contain only
1543  * immutable functions, so it's necessary to check here. We daren't draw
1544  * conclusions from plan-time evaluation of non-immutable functions. Since
1545  * they're ANDed, we can just ignore any mutable constraints in the list,
1546  * and reason about the rest.
1547  */
1548  safe_constraints = NIL;
1549  foreach(lc, constraint_pred)
1550  {
1551  Node *pred = (Node *) lfirst(lc);
1552 
1553  if (!contain_mutable_functions(pred))
1554  safe_constraints = lappend(safe_constraints, pred);
1555  }
1556 
1557  /*
1558  * The constraints are effectively ANDed together, so we can just try to
1559  * refute the entire collection at once. This may allow us to make proofs
1560  * that would fail if we took them individually.
1561  *
1562  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1563  * an obvious optimization. Some of the clauses might be OR clauses that
1564  * have volatile and nonvolatile subclauses, and it's OK to make
1565  * deductions with the nonvolatile parts.
1566  *
1567  * We need strong refutation because we have to prove that the constraints
1568  * would yield false, not just NULL.
1569  */
1570  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1571  return true;
1572 
1573  return false;
1574 }
1575 
1576 
1577 /*
1578  * build_physical_tlist
1579  *
1580  * Build a targetlist consisting of exactly the relation's user attributes,
1581  * in order. The executor can special-case such tlists to avoid a projection
1582  * step at runtime, so we use such tlists preferentially for scan nodes.
1583  *
1584  * Exception: if there are any dropped or missing columns, we punt and return
1585  * NIL. Ideally we would like to handle these cases too. However this
1586  * creates problems for ExecTypeFromTL, which may be asked to build a tupdesc
1587  * for a tlist that includes vars of no-longer-existent types. In theory we
1588  * could dig out the required info from the pg_attribute entries of the
1589  * relation, but that data is not readily available to ExecTypeFromTL.
1590  * For now, we don't apply the physical-tlist optimization when there are
1591  * dropped cols.
1592  *
1593  * We also support building a "physical" tlist for subqueries, functions,
1594  * values lists, table expressions, and CTEs, since the same optimization can
1595  * occur in SubqueryScan, FunctionScan, ValuesScan, CteScan, TableFunc,
1596  * NamedTuplestoreScan, and WorkTableScan nodes.
1597  */
1598 List *
1600 {
1601  List *tlist = NIL;
1602  Index varno = rel->relid;
1603  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1604  Relation relation;
1605  Query *subquery;
1606  Var *var;
1607  ListCell *l;
1608  int attrno,
1609  numattrs;
1610  List *colvars;
1611 
1612  switch (rte->rtekind)
1613  {
1614  case RTE_RELATION:
1615  /* Assume we already have adequate lock */
1616  relation = table_open(rte->relid, NoLock);
1617 
1618  numattrs = RelationGetNumberOfAttributes(relation);
1619  for (attrno = 1; attrno <= numattrs; attrno++)
1620  {
1621  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1622  attrno - 1);
1623 
1624  if (att_tup->attisdropped || att_tup->atthasmissing)
1625  {
1626  /* found a dropped or missing col, so punt */
1627  tlist = NIL;
1628  break;
1629  }
1630 
1631  var = makeVar(varno,
1632  attrno,
1633  att_tup->atttypid,
1634  att_tup->atttypmod,
1635  att_tup->attcollation,
1636  0);
1637 
1638  tlist = lappend(tlist,
1639  makeTargetEntry((Expr *) var,
1640  attrno,
1641  NULL,
1642  false));
1643  }
1644 
1645  table_close(relation, NoLock);
1646  break;
1647 
1648  case RTE_SUBQUERY:
1649  subquery = rte->subquery;
1650  foreach(l, subquery->targetList)
1651  {
1652  TargetEntry *tle = (TargetEntry *) lfirst(l);
1653 
1654  /*
1655  * A resjunk column of the subquery can be reflected as
1656  * resjunk in the physical tlist; we need not punt.
1657  */
1658  var = makeVarFromTargetEntry(varno, tle);
1659 
1660  tlist = lappend(tlist,
1661  makeTargetEntry((Expr *) var,
1662  tle->resno,
1663  NULL,
1664  tle->resjunk));
1665  }
1666  break;
1667 
1668  case RTE_FUNCTION:
1669  case RTE_TABLEFUNC:
1670  case RTE_VALUES:
1671  case RTE_CTE:
1672  case RTE_NAMEDTUPLESTORE:
1673  case RTE_RESULT:
1674  /* Not all of these can have dropped cols, but share code anyway */
1675  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1676  NULL, &colvars);
1677  foreach(l, colvars)
1678  {
1679  var = (Var *) lfirst(l);
1680 
1681  /*
1682  * A non-Var in expandRTE's output means a dropped column;
1683  * must punt.
1684  */
1685  if (!IsA(var, Var))
1686  {
1687  tlist = NIL;
1688  break;
1689  }
1690 
1691  tlist = lappend(tlist,
1692  makeTargetEntry((Expr *) var,
1693  var->varattno,
1694  NULL,
1695  false));
1696  }
1697  break;
1698 
1699  default:
1700  /* caller error */
1701  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1702  (int) rte->rtekind);
1703  break;
1704  }
1705 
1706  return tlist;
1707 }
1708 
1709 /*
1710  * build_index_tlist
1711  *
1712  * Build a targetlist representing the columns of the specified index.
1713  * Each column is represented by a Var for the corresponding base-relation
1714  * column, or an expression in base-relation Vars, as appropriate.
1715  *
1716  * There are never any dropped columns in indexes, so unlike
1717  * build_physical_tlist, we need no failure case.
1718  */
1719 static List *
1721  Relation heapRelation)
1722 {
1723  List *tlist = NIL;
1724  Index varno = index->rel->relid;
1725  ListCell *indexpr_item;
1726  int i;
1727 
1728  indexpr_item = list_head(index->indexprs);
1729  for (i = 0; i < index->ncolumns; i++)
1730  {
1731  int indexkey = index->indexkeys[i];
1732  Expr *indexvar;
1733 
1734  if (indexkey != 0)
1735  {
1736  /* simple column */
1737  const FormData_pg_attribute *att_tup;
1738 
1739  if (indexkey < 0)
1740  att_tup = SystemAttributeDefinition(indexkey);
1741  else
1742  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1743 
1744  indexvar = (Expr *) makeVar(varno,
1745  indexkey,
1746  att_tup->atttypid,
1747  att_tup->atttypmod,
1748  att_tup->attcollation,
1749  0);
1750  }
1751  else
1752  {
1753  /* expression column */
1754  if (indexpr_item == NULL)
1755  elog(ERROR, "wrong number of index expressions");
1756  indexvar = (Expr *) lfirst(indexpr_item);
1757  indexpr_item = lnext(index->indexprs, indexpr_item);
1758  }
1759 
1760  tlist = lappend(tlist,
1761  makeTargetEntry(indexvar,
1762  i + 1,
1763  NULL,
1764  false));
1765  }
1766  if (indexpr_item != NULL)
1767  elog(ERROR, "wrong number of index expressions");
1768 
1769  return tlist;
1770 }
1771 
1772 /*
1773  * restriction_selectivity
1774  *
1775  * Returns the selectivity of a specified restriction operator clause.
1776  * This code executes registered procedures stored in the
1777  * operator relation, by calling the function manager.
1778  *
1779  * See clause_selectivity() for the meaning of the additional parameters.
1780  */
1783  Oid operatorid,
1784  List *args,
1785  Oid inputcollid,
1786  int varRelid)
1787 {
1788  RegProcedure oprrest = get_oprrest(operatorid);
1789  float8 result;
1790 
1791  /*
1792  * if the oprrest procedure is missing for whatever reason, use a
1793  * selectivity of 0.5
1794  */
1795  if (!oprrest)
1796  return (Selectivity) 0.5;
1797 
1798  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1799  inputcollid,
1800  PointerGetDatum(root),
1801  ObjectIdGetDatum(operatorid),
1802  PointerGetDatum(args),
1803  Int32GetDatum(varRelid)));
1804 
1805  if (result < 0.0 || result > 1.0)
1806  elog(ERROR, "invalid restriction selectivity: %f", result);
1807 
1808  return (Selectivity) result;
1809 }
1810 
1811 /*
1812  * join_selectivity
1813  *
1814  * Returns the selectivity of a specified join operator clause.
1815  * This code executes registered procedures stored in the
1816  * operator relation, by calling the function manager.
1817  *
1818  * See clause_selectivity() for the meaning of the additional parameters.
1819  */
1822  Oid operatorid,
1823  List *args,
1824  Oid inputcollid,
1825  JoinType jointype,
1826  SpecialJoinInfo *sjinfo)
1827 {
1828  RegProcedure oprjoin = get_oprjoin(operatorid);
1829  float8 result;
1830 
1831  /*
1832  * if the oprjoin procedure is missing for whatever reason, use a
1833  * selectivity of 0.5
1834  */
1835  if (!oprjoin)
1836  return (Selectivity) 0.5;
1837 
1838  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1839  inputcollid,
1840  PointerGetDatum(root),
1841  ObjectIdGetDatum(operatorid),
1842  PointerGetDatum(args),
1843  Int16GetDatum(jointype),
1844  PointerGetDatum(sjinfo)));
1845 
1846  if (result < 0.0 || result > 1.0)
1847  elog(ERROR, "invalid join selectivity: %f", result);
1848 
1849  return (Selectivity) result;
1850 }
1851 
1852 /*
1853  * function_selectivity
1854  *
1855  * Returns the selectivity of a specified boolean function clause.
1856  * This code executes registered procedures stored in the
1857  * pg_proc relation, by calling the function manager.
1858  *
1859  * See clause_selectivity() for the meaning of the additional parameters.
1860  */
1863  Oid funcid,
1864  List *args,
1865  Oid inputcollid,
1866  bool is_join,
1867  int varRelid,
1868  JoinType jointype,
1869  SpecialJoinInfo *sjinfo)
1870 {
1871  RegProcedure prosupport = get_func_support(funcid);
1873  SupportRequestSelectivity *sresult;
1874 
1875  /*
1876  * If no support function is provided, use our historical default
1877  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
1878  * Postgres has been using that estimate for function calls since 1992.
1879  * The hoariness of this behavior suggests that we should not be in too
1880  * much hurry to use another value.
1881  */
1882  if (!prosupport)
1883  return (Selectivity) 0.3333333;
1884 
1886  req.root = root;
1887  req.funcid = funcid;
1888  req.args = args;
1889  req.inputcollid = inputcollid;
1890  req.is_join = is_join;
1891  req.varRelid = varRelid;
1892  req.jointype = jointype;
1893  req.sjinfo = sjinfo;
1894  req.selectivity = -1; /* to catch failure to set the value */
1895 
1896  sresult = (SupportRequestSelectivity *)
1897  DatumGetPointer(OidFunctionCall1(prosupport,
1898  PointerGetDatum(&req)));
1899 
1900  /* If support function fails, use default */
1901  if (sresult != &req)
1902  return (Selectivity) 0.3333333;
1903 
1904  if (req.selectivity < 0.0 || req.selectivity > 1.0)
1905  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
1906 
1907  return (Selectivity) req.selectivity;
1908 }
1909 
1910 /*
1911  * add_function_cost
1912  *
1913  * Get an estimate of the execution cost of a function, and *add* it to
1914  * the contents of *cost. The estimate may include both one-time and
1915  * per-tuple components, since QualCost does.
1916  *
1917  * The funcid must always be supplied. If it is being called as the
1918  * implementation of a specific parsetree node (FuncExpr, OpExpr,
1919  * WindowFunc, etc), pass that as "node", else pass NULL.
1920  *
1921  * In some usages root might be NULL, too.
1922  */
1923 void
1924 add_function_cost(PlannerInfo *root, Oid funcid, Node *node,
1925  QualCost *cost)
1926 {
1927  HeapTuple proctup;
1928  Form_pg_proc procform;
1929 
1930  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1931  if (!HeapTupleIsValid(proctup))
1932  elog(ERROR, "cache lookup failed for function %u", funcid);
1933  procform = (Form_pg_proc) GETSTRUCT(proctup);
1934 
1935  if (OidIsValid(procform->prosupport))
1936  {
1937  SupportRequestCost req;
1938  SupportRequestCost *sresult;
1939 
1940  req.type = T_SupportRequestCost;
1941  req.root = root;
1942  req.funcid = funcid;
1943  req.node = node;
1944 
1945  /* Initialize cost fields so that support function doesn't have to */
1946  req.startup = 0;
1947  req.per_tuple = 0;
1948 
1949  sresult = (SupportRequestCost *)
1950  DatumGetPointer(OidFunctionCall1(procform->prosupport,
1951  PointerGetDatum(&req)));
1952 
1953  if (sresult == &req)
1954  {
1955  /* Success, so accumulate support function's estimate into *cost */
1956  cost->startup += req.startup;
1957  cost->per_tuple += req.per_tuple;
1958  ReleaseSysCache(proctup);
1959  return;
1960  }
1961  }
1962 
1963  /* No support function, or it failed, so rely on procost */
1964  cost->per_tuple += procform->procost * cpu_operator_cost;
1965 
1966  ReleaseSysCache(proctup);
1967 }
1968 
1969 /*
1970  * get_function_rows
1971  *
1972  * Get an estimate of the number of rows returned by a set-returning function.
1973  *
1974  * The funcid must always be supplied. In current usage, the calling node
1975  * will always be supplied, and will be either a FuncExpr or OpExpr.
1976  * But it's a good idea to not fail if it's NULL.
1977  *
1978  * In some usages root might be NULL, too.
1979  *
1980  * Note: this returns the unfiltered result of the support function, if any.
1981  * It's usually a good idea to apply clamp_row_est() to the result, but we
1982  * leave it to the caller to do so.
1983  */
1984 double
1985 get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
1986 {
1987  HeapTuple proctup;
1988  Form_pg_proc procform;
1989  double result;
1990 
1991  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1992  if (!HeapTupleIsValid(proctup))
1993  elog(ERROR, "cache lookup failed for function %u", funcid);
1994  procform = (Form_pg_proc) GETSTRUCT(proctup);
1995 
1996  Assert(procform->proretset); /* else caller error */
1997 
1998  if (OidIsValid(procform->prosupport))
1999  {
2000  SupportRequestRows req;
2001  SupportRequestRows *sresult;
2002 
2003  req.type = T_SupportRequestRows;
2004  req.root = root;
2005  req.funcid = funcid;
2006  req.node = node;
2007 
2008  req.rows = 0; /* just for sanity */
2009 
2010  sresult = (SupportRequestRows *)
2011  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2012  PointerGetDatum(&req)));
2013 
2014  if (sresult == &req)
2015  {
2016  /* Success */
2017  ReleaseSysCache(proctup);
2018  return req.rows;
2019  }
2020  }
2021 
2022  /* No support function, or it failed, so rely on prorows */
2023  result = procform->prorows;
2024 
2025  ReleaseSysCache(proctup);
2026 
2027  return result;
2028 }
2029 
2030 /*
2031  * has_unique_index
2032  *
2033  * Detect whether there is a unique index on the specified attribute
2034  * of the specified relation, thus allowing us to conclude that all
2035  * the (non-null) values of the attribute are distinct.
2036  *
2037  * This function does not check the index's indimmediate property, which
2038  * means that uniqueness may transiently fail to hold intra-transaction.
2039  * That's appropriate when we are making statistical estimates, but beware
2040  * of using this for any correctness proofs.
2041  */
2042 bool
2044 {
2045  ListCell *ilist;
2046 
2047  foreach(ilist, rel->indexlist)
2048  {
2049  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2050 
2051  /*
2052  * Note: ignore partial indexes, since they don't allow us to conclude
2053  * that all attr values are distinct, *unless* they are marked predOK
2054  * which means we know the index's predicate is satisfied by the
2055  * query. We don't take any interest in expressional indexes either.
2056  * Also, a multicolumn unique index doesn't allow us to conclude that
2057  * just the specified attr is unique.
2058  */
2059  if (index->unique &&
2060  index->nkeycolumns == 1 &&
2061  index->indexkeys[0] == attno &&
2062  (index->indpred == NIL || index->predOK))
2063  return true;
2064  }
2065  return false;
2066 }
2067 
2068 
2069 /*
2070  * has_row_triggers
2071  *
2072  * Detect whether the specified relation has any row-level triggers for event.
2073  */
2074 bool
2076 {
2077  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2078  Relation relation;
2079  TriggerDesc *trigDesc;
2080  bool result = false;
2081 
2082  /* Assume we already have adequate lock */
2083  relation = table_open(rte->relid, NoLock);
2084 
2085  trigDesc = relation->trigdesc;
2086  switch (event)
2087  {
2088  case CMD_INSERT:
2089  if (trigDesc &&
2090  (trigDesc->trig_insert_after_row ||
2091  trigDesc->trig_insert_before_row))
2092  result = true;
2093  break;
2094  case CMD_UPDATE:
2095  if (trigDesc &&
2096  (trigDesc->trig_update_after_row ||
2097  trigDesc->trig_update_before_row))
2098  result = true;
2099  break;
2100  case CMD_DELETE:
2101  if (trigDesc &&
2102  (trigDesc->trig_delete_after_row ||
2103  trigDesc->trig_delete_before_row))
2104  result = true;
2105  break;
2106  default:
2107  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2108  break;
2109  }
2110 
2111  table_close(relation, NoLock);
2112  return result;
2113 }
2114 
2115 bool
2117 {
2118  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2119  Relation relation;
2120  TupleDesc tupdesc;
2121  bool result = false;
2122 
2123  /* Assume we already have adequate lock */
2124  relation = table_open(rte->relid, NoLock);
2125 
2126  tupdesc = RelationGetDescr(relation);
2127  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2128 
2129  table_close(relation, NoLock);
2130 
2131  return result;
2132 }
2133 
2134 /*
2135  * set_relation_partition_info
2136  *
2137  * Set partitioning scheme and related information for a partitioned table.
2138  */
2139 static void
2141  Relation relation)
2142 {
2143  PartitionDesc partdesc;
2144 
2145  /* Create the PartitionDirectory infrastructure if we didn't already */
2146  if (root->glob->partition_directory == NULL)
2147  root->glob->partition_directory =
2149 
2151  relation);
2152  rel->part_scheme = find_partition_scheme(root, relation);
2153  Assert(partdesc != NULL && rel->part_scheme != NULL);
2154  rel->boundinfo = partdesc->boundinfo;
2155  rel->nparts = partdesc->nparts;
2156  set_baserel_partition_key_exprs(relation, rel);
2157  set_baserel_partition_constraint(relation, rel);
2158 }
2159 
2160 /*
2161  * find_partition_scheme
2162  *
2163  * Find or create a PartitionScheme for this Relation.
2164  */
2165 static PartitionScheme
2167 {
2168  PartitionKey partkey = RelationGetPartitionKey(relation);
2169  ListCell *lc;
2170  int partnatts,
2171  i;
2172  PartitionScheme part_scheme;
2173 
2174  /* A partitioned table should have a partition key. */
2175  Assert(partkey != NULL);
2176 
2177  partnatts = partkey->partnatts;
2178 
2179  /* Search for a matching partition scheme and return if found one. */
2180  foreach(lc, root->part_schemes)
2181  {
2182  part_scheme = lfirst(lc);
2183 
2184  /* Match partitioning strategy and number of keys. */
2185  if (partkey->strategy != part_scheme->strategy ||
2186  partnatts != part_scheme->partnatts)
2187  continue;
2188 
2189  /* Match partition key type properties. */
2190  if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2191  sizeof(Oid) * partnatts) != 0 ||
2192  memcmp(partkey->partopcintype, part_scheme->partopcintype,
2193  sizeof(Oid) * partnatts) != 0 ||
2194  memcmp(partkey->partcollation, part_scheme->partcollation,
2195  sizeof(Oid) * partnatts) != 0)
2196  continue;
2197 
2198  /*
2199  * Length and byval information should match when partopcintype
2200  * matches.
2201  */
2202  Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2203  sizeof(int16) * partnatts) == 0);
2204  Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2205  sizeof(bool) * partnatts) == 0);
2206 
2207  /*
2208  * If partopfamily and partopcintype matched, must have the same
2209  * partition comparison functions. Note that we cannot reliably
2210  * Assert the equality of function structs themselves for they might
2211  * be different across PartitionKey's, so just Assert for the function
2212  * OIDs.
2213  */
2214 #ifdef USE_ASSERT_CHECKING
2215  for (i = 0; i < partkey->partnatts; i++)
2216  Assert(partkey->partsupfunc[i].fn_oid ==
2217  part_scheme->partsupfunc[i].fn_oid);
2218 #endif
2219 
2220  /* Found matching partition scheme. */
2221  return part_scheme;
2222  }
2223 
2224  /*
2225  * Did not find matching partition scheme. Create one copying relevant
2226  * information from the relcache. We need to copy the contents of the
2227  * array since the relcache entry may not survive after we have closed the
2228  * relation.
2229  */
2230  part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
2231  part_scheme->strategy = partkey->strategy;
2232  part_scheme->partnatts = partkey->partnatts;
2233 
2234  part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
2235  memcpy(part_scheme->partopfamily, partkey->partopfamily,
2236  sizeof(Oid) * partnatts);
2237 
2238  part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
2239  memcpy(part_scheme->partopcintype, partkey->partopcintype,
2240  sizeof(Oid) * partnatts);
2241 
2242  part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
2243  memcpy(part_scheme->partcollation, partkey->partcollation,
2244  sizeof(Oid) * partnatts);
2245 
2246  part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
2247  memcpy(part_scheme->parttyplen, partkey->parttyplen,
2248  sizeof(int16) * partnatts);
2249 
2250  part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
2251  memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2252  sizeof(bool) * partnatts);
2253 
2254  part_scheme->partsupfunc = (FmgrInfo *)
2255  palloc(sizeof(FmgrInfo) * partnatts);
2256  for (i = 0; i < partnatts; i++)
2257  fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2259 
2260  /* Add the partitioning scheme to PlannerInfo. */
2261  root->part_schemes = lappend(root->part_schemes, part_scheme);
2262 
2263  return part_scheme;
2264 }
2265 
2266 /*
2267  * set_baserel_partition_key_exprs
2268  *
2269  * Builds partition key expressions for the given base relation and fills
2270  * rel->partexprs.
2271  */
2272 static void
2274  RelOptInfo *rel)
2275 {
2276  PartitionKey partkey = RelationGetPartitionKey(relation);
2277  int partnatts;
2278  int cnt;
2279  List **partexprs;
2280  ListCell *lc;
2281  Index varno = rel->relid;
2282 
2283  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2284 
2285  /* A partitioned table should have a partition key. */
2286  Assert(partkey != NULL);
2287 
2288  partnatts = partkey->partnatts;
2289  partexprs = (List **) palloc(sizeof(List *) * partnatts);
2290  lc = list_head(partkey->partexprs);
2291 
2292  for (cnt = 0; cnt < partnatts; cnt++)
2293  {
2294  Expr *partexpr;
2295  AttrNumber attno = partkey->partattrs[cnt];
2296 
2297  if (attno != InvalidAttrNumber)
2298  {
2299  /* Single column partition key is stored as a Var node. */
2300  Assert(attno > 0);
2301 
2302  partexpr = (Expr *) makeVar(varno, attno,
2303  partkey->parttypid[cnt],
2304  partkey->parttypmod[cnt],
2305  partkey->parttypcoll[cnt], 0);
2306  }
2307  else
2308  {
2309  if (lc == NULL)
2310  elog(ERROR, "wrong number of partition key expressions");
2311 
2312  /* Re-stamp the expression with given varno. */
2313  partexpr = (Expr *) copyObject(lfirst(lc));
2314  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2315  lc = lnext(partkey->partexprs, lc);
2316  }
2317 
2318  /* Base relations have a single expression per key. */
2319  partexprs[cnt] = list_make1(partexpr);
2320  }
2321 
2322  rel->partexprs = partexprs;
2323 
2324  /*
2325  * A base relation does not have nullable partition key expressions, since
2326  * no outer join is involved. We still allocate an array of empty
2327  * expression lists to keep partition key expression handling code simple.
2328  * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2329  */
2330  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2331 }
2332 
2333 /*
2334  * set_baserel_partition_constraint
2335  *
2336  * Builds the partition constraint for the given base relation and sets it
2337  * in the given RelOptInfo. All Var nodes are restamped with the relid of the
2338  * given relation.
2339  */
2340 static void
2342 {
2343  List *partconstr;
2344 
2345  if (rel->partition_qual) /* already done */
2346  return;
2347 
2348  /*
2349  * Run the partition quals through const-simplification similar to check
2350  * constraints. We skip canonicalize_qual, though, because partition
2351  * quals should be in canonical form already; also, since the qual is in
2352  * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2353  * format and back again.
2354  */
2355  partconstr = RelationGetPartitionQual(relation);
2356  if (partconstr)
2357  {
2358  partconstr = (List *) expression_planner((Expr *) partconstr);
2359  if (rel->relid != 1)
2360  ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2361  rel->partition_qual = partconstr;
2362  }
2363 }
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
static void table_relation_estimate_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: tableam.h:1907
Definition: fmgr.h:56
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1552
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Query * parse
Definition: pathnodes.h:173
List * statlist
Definition: pathnodes.h:708
int16 * rd_indoption
Definition: rel.h:194
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1310
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
Oid * indexcollations
Definition: pathnodes.h:838
RelOptKind reloptkind
Definition: pathnodes.h:667
static int32 next
Definition: blutils.c:219
Relids * attr_needed
Definition: pathnodes.h:703
bool IsSystemRelation(Relation relation)
Definition: catalog.c:66
amgettuple_function amgettuple
Definition: amapi.h:273
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:633
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3073
#define RelationGetDescr(relation)
Definition: rel.h:483
int LOCKMODE
Definition: lockdefs.h:26
OnConflictExpr * onConflict
Definition: parsenodes.h:144
Oid * partopfamily
Definition: partcache.h:33
bool amcanorderbyop
Definition: amapi.h:222
FmgrInfo * partsupfunc
Definition: partcache.h:35
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:463
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1782
List * indextlist
Definition: pathnodes.h:852
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define RelationGetForm(relation)
Definition: rel.h:451
double tuples
Definition: pathnodes.h:710
Oid reltablespace
Definition: pathnodes.h:699
List * baserestrictinfo
Definition: pathnodes.h:734
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: rel.h:263
int constraint_exclusion
Definition: plancat.c:57
regproc RegProcedure
Definition: c.h:585
Expr * expression_planner(Expr *expr)
Definition: planner.c:6165
int resultRelation
Definition: parsenodes.h:122
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1403
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:103
PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt)
Definition: partdesc.c:283
#define Int16GetDatum(X)
Definition: postgres.h:451
static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel, List *idxExprs)
Definition: plancat.c:886
Definition: nodes.h:533
List * part_schemes
Definition: pathnodes.h:299
Oid * sortopfamily
Definition: pathnodes.h:841
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
int errcode(int sqlerrcode)
Definition: elog.c:694
void * stringToNode(const char *str)
Definition: read.c:89
Oid reltablespace
Definition: pathnodes.h:825
AttrNumber varattno
Definition: primnodes.h:186
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2022
bool IgnoreSystemIndexes
Definition: miscinit.c:79
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
uint32 BlockNumber
Definition: block.h:31
bool statext_is_kind_built(HeapTuple htup, char type)
bool hypothetical
Definition: pathnodes.h:863
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1924
double Selectivity
Definition: nodes.h:666
List * partexprs
Definition: partcache.h:30
bool immediate
Definition: pathnodes.h:862
bool has_stored_generated_columns(PlannerInfo *root, Index rti)
Definition: plancat.c:2116
#define SizeOfPageHeaderData
Definition: bufpage.h:216
double tuples
Definition: pathnodes.h:830
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
Form_pg_class rd_rel
Definition: rel.h:110
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8132
List ** nullable_partexprs
Definition: pathnodes.h:761
Definition: primnodes.h:181
List * fkey_list
Definition: pathnodes.h:290
int tree_height
Definition: pathnodes.h:831
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
bool amoptionalkey
Definition: amapi.h:230
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:643
Cost startup
Definition: pathnodes.h:45
double allvisfrac
Definition: pathnodes.h:711
signed int int32
Definition: c.h:429
PartitionBoundInfo boundinfo
Definition: partdesc.h:29
JoinType
Definition: nodes.h:700
List * targetList
Definition: parsenodes.h:140
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4873
List * arbiterElems
Definition: primnodes.h:1553
struct HeapTupleData * rd_indextuple
Definition: rel.h:177
TransactionId TransactionXmin
Definition: snapmgr.c:112
struct PlannerInfo * root
Definition: supportnodes.h:163
HeapTupleHeader t_data
Definition: htup.h:68
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:829
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:249
#define list_make1(x1)
Definition: pg_list.h:206
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:731
bool has_generated_stored
Definition: tupdesc.h:45
Cost per_tuple
Definition: pathnodes.h:46
Form_pg_index rd_index
Definition: rel.h:175
uint32 amflags
Definition: pathnodes.h:717
RelOptInfo * rel
Definition: pathnodes.h:826
bool amoptionalkey
Definition: pathnodes.h:867
Oid * parttypcoll
Definition: partcache.h:46
List ** partexprs
Definition: pathnodes.h:760
amgetbitmap_function amgetbitmap
Definition: amapi.h:274
bool resjunk
Definition: primnodes.h:1438
#define linitial(l)
Definition: pg_list.h:174
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:2043
List * rtable
Definition: parsenodes.h:137
Oid * rd_indcollation
Definition: rel.h:200
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:221
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
double float8
Definition: c.h:565
struct PlannerInfo * root
Definition: supportnodes.h:96
bool list_member(const List *list, const void *datum)
Definition: list.c:628
struct SpecialJoinInfo * sjinfo
Definition: supportnodes.h:103
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
bool rd_version_checked
Definition: rel.h:66
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: pathnodes.h:896
Expr * arg
Definition: primnodes.h:1243
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
bool(* scan_bitmap_next_block)(TableScanDesc scan, struct TBMIterateResult *tbmres)
Definition: tableam.h:788
TriggerDesc * trigdesc
Definition: rel.h:116
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:664
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:611
amcostestimate_function amcostestimate
Definition: amapi.h:265
bool trig_delete_after_row
Definition: reltrigger.h:67
#define NoLock
Definition: lockdefs.h:34
Selectivity function_selectivity(PlannerInfo *root, Oid funcid, List *args, Oid inputcollid, bool is_join, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1862
bool amcanorderbyop
Definition: pathnodes.h:866
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4760
PlannerGlobal * glob
Definition: pathnodes.h:175
TupleConstr * constr
Definition: tupdesc.h:85
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:725
int nparts
Definition: pathnodes.h:750
AttrNumber resno
Definition: primnodes.h:1432
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
#define DatumGetBool(X)
Definition: postgres.h:393
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:2140
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:292
bool trig_update_before_row
Definition: reltrigger.h:61
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:60
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
struct ItemIdData ItemIdData
double cpu_operator_cost
Definition: costsize.c:122
Oid * rd_opfamily
Definition: rel.h:190
bool trig_insert_after_row
Definition: reltrigger.h:57
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:968
RelOptInfo * rel
Definition: pathnodes.h:923
void(* amcostestimate)()
Definition: pathnodes.h:875
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
bool amhasgetbitmap
Definition: pathnodes.h:871
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
bool amcanparallel
Definition: amapi.h:242
struct PartitionSchemeData * PartitionScheme
Definition: pathnodes.h:411
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
Index relid
Definition: pathnodes.h:698
bool trig_update_after_row
Definition: reltrigger.h:62
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1148
bool(* scan_getnextslot_tidrange)(TableScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:354
List * lappend(List *list, void *datum)
Definition: list.c:336
OnConflictAction action
Definition: primnodes.h:1550
List * build_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
Definition: plancat.c:1599
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:205
Expr * clause
Definition: pathnodes.h:2006
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:904
Oid serverid
Definition: pathnodes.h:721
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
bool amsearchnulls
Definition: amapi.h:234
List * indrestrictinfo
Definition: pathnodes.h:854
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1528
Oid * partcollation
Definition: partcache.h:38
bool trig_insert_before_row
Definition: reltrigger.h:56
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:906
void * palloc0(Size size)
Definition: mcxt.c:981
AttrNumber * partattrs
Definition: partcache.h:28
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: pathnodes.h:894
#define DatumGetFloat8(X)
Definition: postgres.h:714
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
int rel_parallel_workers
Definition: pathnodes.h:716
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
const struct TableAmRoutine * rd_tableam
Definition: rel.h:172
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:753
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
unsigned int Index
Definition: c.h:549
TupleDesc rd_att
Definition: rel.h:111
NullTestType nulltesttype
Definition: primnodes.h:1244
uint16 num_check
Definition: tupdesc.h:43
List * indexlist
Definition: pathnodes.h:707
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
int32 * parttypmod
Definition: partcache.h:42
bool amsearcharray
Definition: amapi.h:232
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2525
bool amhasgettuple
Definition: pathnodes.h:870
#define InvalidOid
Definition: postgres_ext.h:36
FormData_pg_attribute
Definition: pg_attribute.h:181
Oid fn_oid
Definition: fmgr.h:59
#define ereport(elevel,...)
Definition: elog.h:155
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2341
List * lcons(void *datum, List *list)
Definition: list.c:468
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation rel)
Definition: plancat.c:2166
void(* scan_set_tidrange)(TableScanDesc scan, ItemPointer mintid, ItemPointer maxtid)
Definition: tableam.h:346
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1829
#define makeNode(_type_)
Definition: nodes.h:581
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: rel.h:265
bool * parttypbyval
Definition: partcache.h:44
void index_check_collation_versions(Oid relid)
Definition: index.c:1333
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
BlockNumber pages
Definition: pathnodes.h:709
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
int16 * parttyplen
Definition: partcache.h:43
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:505
void(* get_relation_info_hook_type)(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
Definition: plancat.h:21
InheritanceKind inhTargetKind
Definition: pathnodes.h:336
struct FmgrInfo * partsupfunc
Definition: pathnodes.h:408
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:340
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:205
int location
Definition: primnodes.h:1246
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1455
List * infer_arbiter_indexes(PlannerInfo *root)
Definition: plancat.c:620
static int list_length(const List *l)
Definition: pg_list.h:149
bool amsearcharray
Definition: pathnodes.h:868
#define MAXALIGN(LEN)
Definition: c.h:757
ammarkpos_function ammarkpos
Definition: amapi.h:276
bool amcanorder
Definition: amapi.h:220
List * list_difference(const List *list1, const List *list2)
Definition: list.c:1091
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
int nkeycolumns
Definition: pathnodes.h:835
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1183
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4526
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1444
Oid * opcintype
Definition: pathnodes.h:840
Bitmapset * Relids
Definition: pathnodes.h:28
#define InvalidAttrNumber
Definition: attnum.h:23
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4645
struct PlannerInfo * root
Definition: supportnodes.h:136
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define DatumGetPointer(X)
Definition: postgres.h:549
bool amcanmarkpos
Definition: pathnodes.h:873
Oid * opfamily
Definition: pathnodes.h:839
RTEKind rtekind
Definition: parsenodes.h:981
Node * arbiterWhere
Definition: primnodes.h:1555
#define Int32GetDatum(X)
Definition: postgres.h:479
Query * subquery
Definition: parsenodes.h:1016
Bitmapset * keys
Definition: pathnodes.h:925
AttrNumber max_attr
Definition: pathnodes.h:702
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4417
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:905
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1106
Oid * partopcintype
Definition: partcache.h:34
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:227
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: rel.h:264
int i
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:276
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:360
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
Definition: plancat.c:1188
PartitionScheme part_scheme
Definition: pathnodes.h:749
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:358
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1720
bool argisrow
Definition: primnodes.h:1245
int * indexkeys
Definition: pathnodes.h:836
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1821
PartitionDesc PartitionDirectoryLookup(PartitionDirectory pdir, Relation rel)
Definition: partdesc.c:315
ConstrCheck * check
Definition: tupdesc.h:40
bool ccvalid
Definition: tupdesc.h:32
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2273
Oid get_constraint_index(Oid conoid)
Definition: lsyscache.c:1133
bool * canreturn
Definition: pathnodes.h:845
#define AMFLAG_HAS_TID_RANGE
Definition: pathnodes.h:626
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5448
bool amsearchnulls
Definition: pathnodes.h:869
Oid * rd_opcintype
Definition: rel.h:191
#define copyObject(obj)
Definition: nodes.h:649
List * partition_qual
Definition: pathnodes.h:756
bool has_not_null
Definition: tupdesc.h:44
bool * nulls_first
Definition: pathnodes.h:843
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3105
bool has_row_triggers(PlannerInfo *root, Index rti, CmdType event)
Definition: plancat.c:2075
PartitionDirectory partition_directory
Definition: pathnodes.h:143
bool * reverse_sort
Definition: pathnodes.h:842
bytea ** opclassoptions
Definition: pathnodes.h:844
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: pathnodes.h:850
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int32 * attr_widths
Definition: pathnodes.h:704
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: pathnodes.h:895
char * ccbin
Definition: tupdesc.h:31
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:457
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:908
CmdType
Definition: nodes.h:676
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
bool amcanparallel
Definition: pathnodes.h:872
void get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
Definition: plancat.c:113
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define lfirst_oid(lc)
Definition: pg_list.h:171
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94
List * indexprs
Definition: pathnodes.h:849
bool transientPlan
Definition: pathnodes.h:133
bool trig_delete_before_row
Definition: reltrigger.h:66
bool ccnoinherit
Definition: tupdesc.h:33
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition: plancat.c:1985
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1205
amrestrpos_function amrestrpos
Definition: amapi.h:277
AttrNumber min_attr
Definition: pathnodes.h:701