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