PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
plancat.h File Reference
#include "nodes/relation.h"
#include "utils/relcache.h"
Include dependency graph for plancat.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef void(* get_relation_info_hook_type )(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
 

Functions

void get_relation_info (PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
 
Listinfer_arbiter_indexes (PlannerInfo *root)
 
void estimate_rel_size (Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
 
int32 get_relation_data_width (Oid relid, int32 *attr_widths)
 
bool relation_excluded_by_constraints (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
Listbuild_physical_tlist (PlannerInfo *root, RelOptInfo *rel)
 
bool has_unique_index (RelOptInfo *rel, AttrNumber attno)
 
Selectivity restriction_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
 
Selectivity join_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
bool has_row_triggers (PlannerInfo *root, Index rti, CmdType event)
 

Variables

PGDLLIMPORT
get_relation_info_hook_type 
get_relation_info_hook
 

Typedef Documentation

typedef void(* get_relation_info_hook_type)(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)

Definition at line 21 of file plancat.h.

Function Documentation

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1454 of file plancat.c.

References tupleDesc::attrs, elog, ERROR, expandRTE(), heap_close, heap_open(), IsA, lappend(), lfirst, makeTargetEntry(), makeVar(), makeVarFromTargetEntry(), NIL, NoLock, NULL, planner_rt_fetch, RelationData::rd_att, RelationGetNumberOfAttributes, RelOptInfo::relid, RangeTblEntry::relid, TargetEntry::resjunk, TargetEntry::resno, RTE_CTE, RTE_FUNCTION, RTE_RELATION, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::subquery, Query::targetList, and Var::varattno.

Referenced by create_scan_plan().

1455 {
1456  List *tlist = NIL;
1457  Index varno = rel->relid;
1458  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1459  Relation relation;
1460  Query *subquery;
1461  Var *var;
1462  ListCell *l;
1463  int attrno,
1464  numattrs;
1465  List *colvars;
1466 
1467  switch (rte->rtekind)
1468  {
1469  case RTE_RELATION:
1470  /* Assume we already have adequate lock */
1471  relation = heap_open(rte->relid, NoLock);
1472 
1473  numattrs = RelationGetNumberOfAttributes(relation);
1474  for (attrno = 1; attrno <= numattrs; attrno++)
1475  {
1476  Form_pg_attribute att_tup = relation->rd_att->attrs[attrno - 1];
1477 
1478  if (att_tup->attisdropped)
1479  {
1480  /* found a dropped col, so punt */
1481  tlist = NIL;
1482  break;
1483  }
1484 
1485  var = makeVar(varno,
1486  attrno,
1487  att_tup->atttypid,
1488  att_tup->atttypmod,
1489  att_tup->attcollation,
1490  0);
1491 
1492  tlist = lappend(tlist,
1493  makeTargetEntry((Expr *) var,
1494  attrno,
1495  NULL,
1496  false));
1497  }
1498 
1499  heap_close(relation, NoLock);
1500  break;
1501 
1502  case RTE_SUBQUERY:
1503  subquery = rte->subquery;
1504  foreach(l, subquery->targetList)
1505  {
1506  TargetEntry *tle = (TargetEntry *) lfirst(l);
1507 
1508  /*
1509  * A resjunk column of the subquery can be reflected as
1510  * resjunk in the physical tlist; we need not punt.
1511  */
1512  var = makeVarFromTargetEntry(varno, tle);
1513 
1514  tlist = lappend(tlist,
1515  makeTargetEntry((Expr *) var,
1516  tle->resno,
1517  NULL,
1518  tle->resjunk));
1519  }
1520  break;
1521 
1522  case RTE_FUNCTION:
1523  case RTE_TABLEFUNC:
1524  case RTE_VALUES:
1525  case RTE_CTE:
1526  /* Not all of these can have dropped cols, but share code anyway */
1527  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1528  NULL, &colvars);
1529  foreach(l, colvars)
1530  {
1531  var = (Var *) lfirst(l);
1532 
1533  /*
1534  * A non-Var in expandRTE's output means a dropped column;
1535  * must punt.
1536  */
1537  if (!IsA(var, Var))
1538  {
1539  tlist = NIL;
1540  break;
1541  }
1542 
1543  tlist = lappend(tlist,
1544  makeTargetEntry((Expr *) var,
1545  var->varattno,
1546  NULL,
1547  false));
1548  }
1549  break;
1550 
1551  default:
1552  /* caller error */
1553  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1554  (int) rte->rtekind);
1555  break;
1556  }
1557 
1558  return tlist;
1559 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:423
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:104
AttrNumber varattno
Definition: primnodes.h:168
#define heap_close(r, l)
Definition: heapam.h:97
Definition: primnodes.h:163
List * targetList
Definition: parsenodes.h:131
bool resjunk
Definition: primnodes.h:1359
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
AttrNumber resno
Definition: primnodes.h:1353
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:522
List * lappend(List *list, void *datum)
Definition: list.c:128
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
unsigned int Index
Definition: c.h:365
TupleDesc rd_att
Definition: rel.h:115
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:916
Query * subquery
Definition: parsenodes.h:934
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
void estimate_rel_size ( Relation  rel,
int32 attr_widths,
BlockNumber pages,
double *  tuples,
double *  allvisfrac 
)

Definition at line 907 of file plancat.c.

References get_rel_data_width(), MAXALIGN, RelationData::rd_rel, RelationGetNumberOfBlocks, RELKIND_FOREIGN_TABLE, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, rint(), SizeofHeapTupleHeader, and SizeOfPageHeaderData.

Referenced by get_relation_info(), and hashbuild().

909 {
910  BlockNumber curpages;
911  BlockNumber relpages;
912  double reltuples;
913  BlockNumber relallvisible;
914  double density;
915 
916  switch (rel->rd_rel->relkind)
917  {
918  case RELKIND_RELATION:
919  case RELKIND_INDEX:
920  case RELKIND_MATVIEW:
921  case RELKIND_TOASTVALUE:
922  /* it has storage, ok to call the smgr */
923  curpages = RelationGetNumberOfBlocks(rel);
924 
925  /*
926  * HACK: if the relation has never yet been vacuumed, use a
927  * minimum size estimate of 10 pages. The idea here is to avoid
928  * assuming a newly-created table is really small, even if it
929  * currently is, because that may not be true once some data gets
930  * loaded into it. Once a vacuum or analyze cycle has been done
931  * on it, it's more reasonable to believe the size is somewhat
932  * stable.
933  *
934  * (Note that this is only an issue if the plan gets cached and
935  * used again after the table has been filled. What we're trying
936  * to avoid is using a nestloop-type plan on a table that has
937  * grown substantially since the plan was made. Normally,
938  * autovacuum/autoanalyze will occur once enough inserts have
939  * happened and cause cached-plan invalidation; but that doesn't
940  * happen instantaneously, and it won't happen at all for cases
941  * such as temporary tables.)
942  *
943  * We approximate "never vacuumed" by "has relpages = 0", which
944  * means this will also fire on genuinely empty relations. Not
945  * great, but fortunately that's a seldom-seen case in the real
946  * world, and it shouldn't degrade the quality of the plan too
947  * much anyway to err in this direction.
948  *
949  * There are two exceptions wherein we don't apply this heuristic.
950  * One is if the table has inheritance children. Totally empty
951  * parent tables are quite common, so we should be willing to
952  * believe that they are empty. Also, we don't apply the 10-page
953  * minimum to indexes.
954  */
955  if (curpages < 10 &&
956  rel->rd_rel->relpages == 0 &&
957  !rel->rd_rel->relhassubclass &&
958  rel->rd_rel->relkind != RELKIND_INDEX)
959  curpages = 10;
960 
961  /* report estimated # pages */
962  *pages = curpages;
963  /* quick exit if rel is clearly empty */
964  if (curpages == 0)
965  {
966  *tuples = 0;
967  *allvisfrac = 0;
968  break;
969  }
970  /* coerce values in pg_class to more desirable types */
971  relpages = (BlockNumber) rel->rd_rel->relpages;
972  reltuples = (double) rel->rd_rel->reltuples;
973  relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
974 
975  /*
976  * If it's an index, discount the metapage while estimating the
977  * number of tuples. This is a kluge because it assumes more than
978  * it ought to about index structure. Currently it's OK for
979  * btree, hash, and GIN indexes but suspect for GiST indexes.
980  */
981  if (rel->rd_rel->relkind == RELKIND_INDEX &&
982  relpages > 0)
983  {
984  curpages--;
985  relpages--;
986  }
987 
988  /* estimate number of tuples from previous tuple density */
989  if (relpages > 0)
990  density = reltuples / (double) relpages;
991  else
992  {
993  /*
994  * When we have no data because the relation was truncated,
995  * estimate tuple width from attribute datatypes. We assume
996  * here that the pages are completely full, which is OK for
997  * tables (since they've presumably not been VACUUMed yet) but
998  * is probably an overestimate for indexes. Fortunately
999  * get_relation_info() can clamp the overestimate to the
1000  * parent table's size.
1001  *
1002  * Note: this code intentionally disregards alignment
1003  * considerations, because (a) that would be gilding the lily
1004  * considering how crude the estimate is, and (b) it creates
1005  * platform dependencies in the default plans which are kind
1006  * of a headache for regression testing.
1007  */
1008  int32 tuple_width;
1009 
1010  tuple_width = get_rel_data_width(rel, attr_widths);
1011  tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1012  tuple_width += sizeof(ItemIdData);
1013  /* note: integer division is intentional here */
1014  density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1015  }
1016  *tuples = rint(density * (double) curpages);
1017 
1018  /*
1019  * We use relallvisible as-is, rather than scaling it up like we
1020  * do for the pages and tuples counts, on the theory that any
1021  * pages added since the last VACUUM are most likely not marked
1022  * all-visible. But costsize.c wants it converted to a fraction.
1023  */
1024  if (relallvisible == 0 || curpages <= 0)
1025  *allvisfrac = 0;
1026  else if ((double) relallvisible >= curpages)
1027  *allvisfrac = 1;
1028  else
1029  *allvisfrac = (double) relallvisible / curpages;
1030  break;
1031  case RELKIND_SEQUENCE:
1032  /* Sequences always have a known size */
1033  *pages = 1;
1034  *tuples = 1;
1035  *allvisfrac = 0;
1036  break;
1037  case RELKIND_FOREIGN_TABLE:
1038  /* Just use whatever's in pg_class */
1039  *pages = rel->rd_rel->relpages;
1040  *tuples = rel->rd_rel->reltuples;
1041  *allvisfrac = 0;
1042  break;
1043  default:
1044  /* else it has no disk storage; probably shouldn't get here? */
1045  *pages = 0;
1046  *tuples = 0;
1047  *allvisfrac = 0;
1048  break;
1049  }
1050 }
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
#define RELKIND_MATVIEW
Definition: pg_class.h:165
uint32 BlockNumber
Definition: block.h:31
#define SizeOfPageHeaderData
Definition: bufpage.h:213
Form_pg_class rd_rel
Definition: rel.h:114
signed int int32
Definition: c.h:256
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1067
struct ItemIdData ItemIdData
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
double rint(double x)
Definition: rint.c:22
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define MAXALIGN(LEN)
Definition: c.h:588
#define RELKIND_INDEX
Definition: pg_class.h:161
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1109 of file plancat.c.

References get_rel_data_width(), heap_close, heap_open(), NoLock, and result.

Referenced by plan_cluster_use_sort(), and set_rel_width().

1110 {
1111  int32 result;
1112  Relation relation;
1113 
1114  /* As above, assume relation is already locked */
1115  relation = heap_open(relid, NoLock);
1116 
1117  result = get_rel_data_width(relation, attr_widths);
1118 
1119  heap_close(relation, NoLock);
1120 
1121  return result;
1122 }
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
signed int int32
Definition: c.h:256
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1067
#define NoLock
Definition: lockdefs.h:34
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
void get_relation_info ( PlannerInfo root,
Oid  relationObjectId,
bool  inhparent,
RelOptInfo rel 
)

Definition at line 100 of file plancat.c.

References _bt_getrootheight(), AccessShareLock, RelOptInfo::allvisfrac, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanorderbyop, IndexOptInfo::amcanorderbyop, IndexAmRoutine::amcanparallel, IndexOptInfo::amcanparallel, IndexAmRoutine::amcostestimate, IndexOptInfo::amcostestimate, IndexAmRoutine::amgetbitmap, IndexAmRoutine::amgettuple, IndexOptInfo::amhasgetbitmap, IndexOptInfo::amhasgettuple, IndexAmRoutine::amoptionalkey, IndexOptInfo::amoptionalkey, IndexAmRoutine::amsearcharray, IndexOptInfo::amsearcharray, IndexAmRoutine::amsearchnulls, IndexOptInfo::amsearchnulls, Assert, RelOptInfo::attr_needed, RelOptInfo::attr_widths, BTLessStrategyNumber, BTREE_AM_OID, build_index_tlist(), IndexOptInfo::canreturn, ChangeVarNodes(), ereport, errcode(), errmsg(), ERROR, estimate_rel_size(), RelOptInfo::fdwroutine, FirstLowInvalidHeapAttributeNumber, get_opfamily_member(), get_ordering_op_properties(), get_relation_foreign_keys(), get_relation_info_hook, get_relation_statistics(), GetFdwRoutineForRelation(), GetForeignServerIdByRelId(), PlannerInfo::glob, heap_close, heap_open(), HeapTupleHeaderGetXmin, IndexOptInfo::hypothetical, i, IgnoreSystemIndexes, IndexOptInfo::immediate, index_can_return(), index_close(), index_open(), IndexOptInfo::indexcollations, IndexIsValid, IndexOptInfo::indexkeys, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, IndexOptInfo::indextlist, INDOPTION_DESC, INDOPTION_NULLS_FIRST, IndexOptInfo::indpred, IndexOptInfo::indrestrictinfo, InvalidOid, IsSystemRelation(), lcons(), lfirst_oid, list_free(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, IndexOptInfo::ncolumns, NIL, NoLock, NULL, IndexOptInfo::nulls_first, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, RelOptInfo::pages, IndexOptInfo::pages, palloc(), palloc0(), PlannerInfo::parse, IndexOptInfo::predOK, RelationData::rd_amroutine, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_opcintype, RelationData::rd_opfamily, RelationData::rd_rel, RecoveryInProgress(), IndexOptInfo::rel, RelOptInfo::rel_parallel_workers, IndexOptInfo::relam, RelationGetForm, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNumberOfAttributes, RelationGetNumberOfBlocks, RelationGetParallelWorkers, RelationGetRelid, RelationNeedsWAL, RelOptInfo::relid, RELKIND_FOREIGN_TABLE, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, Query::resultRelation, IndexOptInfo::reverse_sort, RowExclusiveLock, RelOptInfo::serverid, IndexOptInfo::sortopfamily, RelOptInfo::statlist, HeapTupleData::t_data, TransactionIdPrecedes(), TransactionXmin, PlannerGlobal::transientPlan, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by build_simple_rel().

102 {
103  Index varno = rel->relid;
104  Relation relation;
105  bool hasindex;
106  List *indexinfos = NIL;
107 
108  /*
109  * We need not lock the relation since it was already locked, either by
110  * the rewriter or when expand_inherited_rtentry() added it to the query's
111  * rangetable.
112  */
113  relation = heap_open(relationObjectId, NoLock);
114 
115  /* Temporary and unlogged relations are inaccessible during recovery. */
116  if (!RelationNeedsWAL(relation) && RecoveryInProgress())
117  ereport(ERROR,
118  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
119  errmsg("cannot access temporary or unlogged relations during recovery")));
120 
122  rel->max_attr = RelationGetNumberOfAttributes(relation);
123  rel->reltablespace = RelationGetForm(relation)->reltablespace;
124 
125  Assert(rel->max_attr >= rel->min_attr);
126  rel->attr_needed = (Relids *)
127  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
128  rel->attr_widths = (int32 *)
129  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
130 
131  /*
132  * Estimate relation size --- unless it's an inheritance parent, in which
133  * case the size will be computed later in set_append_rel_pathlist, and we
134  * must leave it zero for now to avoid bollixing the total_table_pages
135  * calculation.
136  */
137  if (!inhparent)
138  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
139  &rel->pages, &rel->tuples, &rel->allvisfrac);
140 
141  /* Retrieve the parallel_workers reloption, or -1 if not set. */
143 
144  /*
145  * Make list of indexes. Ignore indexes on system catalogs if told to.
146  * Don't bother with indexes for an inheritance parent, either.
147  */
148  if (inhparent ||
149  (IgnoreSystemIndexes && IsSystemRelation(relation)))
150  hasindex = false;
151  else
152  hasindex = relation->rd_rel->relhasindex;
153 
154  if (hasindex)
155  {
156  List *indexoidlist;
157  ListCell *l;
158  LOCKMODE lmode;
159 
160  indexoidlist = RelationGetIndexList(relation);
161 
162  /*
163  * For each index, we get the same type of lock that the executor will
164  * need, and do not release it. This saves a couple of trips to the
165  * shared lock manager while not creating any real loss of
166  * concurrency, because no schema changes could be happening on the
167  * index while we hold lock on the parent rel, and neither lock type
168  * blocks any other kind of index operation.
169  */
170  if (rel->relid == root->parse->resultRelation)
171  lmode = RowExclusiveLock;
172  else
173  lmode = AccessShareLock;
174 
175  foreach(l, indexoidlist)
176  {
177  Oid indexoid = lfirst_oid(l);
178  Relation indexRelation;
180  IndexAmRoutine *amroutine;
181  IndexOptInfo *info;
182  int ncolumns;
183  int i;
184 
185  /*
186  * Extract info from the relation descriptor for the index.
187  */
188  indexRelation = index_open(indexoid, lmode);
189  index = indexRelation->rd_index;
190 
191  /*
192  * Ignore invalid indexes, since they can't safely be used for
193  * queries. Note that this is OK because the data structure we
194  * are constructing is only used by the planner --- the executor
195  * still needs to insert into "invalid" indexes, if they're marked
196  * IndexIsReady.
197  */
198  if (!IndexIsValid(index))
199  {
200  index_close(indexRelation, NoLock);
201  continue;
202  }
203 
204  /*
205  * If the index is valid, but cannot yet be used, ignore it; but
206  * mark the plan we are generating as transient. See
207  * src/backend/access/heap/README.HOT for discussion.
208  */
209  if (index->indcheckxmin &&
212  {
213  root->glob->transientPlan = true;
214  index_close(indexRelation, NoLock);
215  continue;
216  }
217 
218  info = makeNode(IndexOptInfo);
219 
220  info->indexoid = index->indexrelid;
221  info->reltablespace =
222  RelationGetForm(indexRelation)->reltablespace;
223  info->rel = rel;
224  info->ncolumns = ncolumns = index->indnatts;
225  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
226  info->indexcollations = (Oid *) palloc(sizeof(Oid) * ncolumns);
227  info->opfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
228  info->opcintype = (Oid *) palloc(sizeof(Oid) * ncolumns);
229  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
230 
231  for (i = 0; i < ncolumns; i++)
232  {
233  info->indexkeys[i] = index->indkey.values[i];
234  info->indexcollations[i] = indexRelation->rd_indcollation[i];
235  info->opfamily[i] = indexRelation->rd_opfamily[i];
236  info->opcintype[i] = indexRelation->rd_opcintype[i];
237  info->canreturn[i] = index_can_return(indexRelation, i + 1);
238  }
239 
240  info->relam = indexRelation->rd_rel->relam;
241 
242  /* We copy just the fields we need, not all of rd_amroutine */
243  amroutine = indexRelation->rd_amroutine;
244  info->amcanorderbyop = amroutine->amcanorderbyop;
245  info->amoptionalkey = amroutine->amoptionalkey;
246  info->amsearcharray = amroutine->amsearcharray;
247  info->amsearchnulls = amroutine->amsearchnulls;
248  info->amcanparallel = amroutine->amcanparallel;
249  info->amhasgettuple = (amroutine->amgettuple != NULL);
250  info->amhasgetbitmap = (amroutine->amgetbitmap != NULL);
251  info->amcostestimate = amroutine->amcostestimate;
252  Assert(info->amcostestimate != NULL);
253 
254  /*
255  * Fetch the ordering information for the index, if any.
256  */
257  if (info->relam == BTREE_AM_OID)
258  {
259  /*
260  * If it's a btree index, we can use its opfamily OIDs
261  * directly as the sort ordering opfamily OIDs.
262  */
263  Assert(amroutine->amcanorder);
264 
265  info->sortopfamily = info->opfamily;
266  info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
267  info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);
268 
269  for (i = 0; i < ncolumns; i++)
270  {
271  int16 opt = indexRelation->rd_indoption[i];
272 
273  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
274  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
275  }
276  }
277  else if (amroutine->amcanorder)
278  {
279  /*
280  * Otherwise, identify the corresponding btree opfamilies by
281  * trying to map this index's "<" operators into btree. Since
282  * "<" uniquely defines the behavior of a sort order, this is
283  * a sufficient test.
284  *
285  * XXX This method is rather slow and also requires the
286  * undesirable assumption that the other index AM numbers its
287  * strategies the same as btree. It'd be better to have a way
288  * to explicitly declare the corresponding btree opfamily for
289  * each opfamily of the other index type. But given the lack
290  * of current or foreseeable amcanorder index types, it's not
291  * worth expending more effort on now.
292  */
293  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
294  info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
295  info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);
296 
297  for (i = 0; i < ncolumns; i++)
298  {
299  int16 opt = indexRelation->rd_indoption[i];
300  Oid ltopr;
301  Oid btopfamily;
302  Oid btopcintype;
303  int16 btstrategy;
304 
305  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
306  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
307 
308  ltopr = get_opfamily_member(info->opfamily[i],
309  info->opcintype[i],
310  info->opcintype[i],
312  if (OidIsValid(ltopr) &&
314  &btopfamily,
315  &btopcintype,
316  &btstrategy) &&
317  btopcintype == info->opcintype[i] &&
318  btstrategy == BTLessStrategyNumber)
319  {
320  /* Successful mapping */
321  info->sortopfamily[i] = btopfamily;
322  }
323  else
324  {
325  /* Fail ... quietly treat index as unordered */
326  info->sortopfamily = NULL;
327  info->reverse_sort = NULL;
328  info->nulls_first = NULL;
329  break;
330  }
331  }
332  }
333  else
334  {
335  info->sortopfamily = NULL;
336  info->reverse_sort = NULL;
337  info->nulls_first = NULL;
338  }
339 
340  /*
341  * Fetch the index expressions and predicate, if any. We must
342  * modify the copies we obtain from the relcache to have the
343  * correct varno for the parent relation, so that they match up
344  * correctly against qual clauses.
345  */
346  info->indexprs = RelationGetIndexExpressions(indexRelation);
347  info->indpred = RelationGetIndexPredicate(indexRelation);
348  if (info->indexprs && varno != 1)
349  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
350  if (info->indpred && varno != 1)
351  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
352 
353  /* Build targetlist using the completed indexprs data */
354  info->indextlist = build_index_tlist(root, info, relation);
355 
356  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
357  info->predOK = false; /* set later, in indxpath.c */
358  info->unique = index->indisunique;
359  info->immediate = index->indimmediate;
360  info->hypothetical = false;
361 
362  /*
363  * Estimate the index size. If it's not a partial index, we lock
364  * the number-of-tuples estimate to equal the parent table; if it
365  * is partial then we have to use the same methods as we would for
366  * a table, except we can be sure that the index is not larger
367  * than the table.
368  */
369  if (info->indpred == NIL)
370  {
371  info->pages = RelationGetNumberOfBlocks(indexRelation);
372  info->tuples = rel->tuples;
373  }
374  else
375  {
376  double allvisfrac; /* dummy */
377 
378  estimate_rel_size(indexRelation, NULL,
379  &info->pages, &info->tuples, &allvisfrac);
380  if (info->tuples > rel->tuples)
381  info->tuples = rel->tuples;
382  }
383 
384  if (info->relam == BTREE_AM_OID)
385  {
386  /* For btrees, get tree height while we have the index open */
387  info->tree_height = _bt_getrootheight(indexRelation);
388  }
389  else
390  {
391  /* For other index types, just set it to "unknown" for now */
392  info->tree_height = -1;
393  }
394 
395  index_close(indexRelation, NoLock);
396 
397  indexinfos = lcons(info, indexinfos);
398  }
399 
400  list_free(indexoidlist);
401  }
402 
403  rel->indexlist = indexinfos;
404 
405  rel->statlist = get_relation_statistics(rel, relation);
406 
407  /* Grab foreign-table info using the relcache, while we have it */
408  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
409  {
411  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
412  }
413  else
414  {
415  rel->serverid = InvalidOid;
416  rel->fdwroutine = NULL;
417  }
418 
419  /* Collect info about relation's foreign keys, if relevant */
420  get_relation_foreign_keys(root, rel, relation, inhparent);
421 
422  heap_close(relation, NoLock);
423 
424  /*
425  * Allow a plugin to editorialize on the info we obtained from the
426  * catalogs. Actions might include altering the assumed relation size,
427  * removing an index, or adding a hypothetical index to the indexlist.
428  */
430  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
431 }
signed short int16
Definition: c.h:255
#define NIL
Definition: pg_list.h:69
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
Query * parse
Definition: relation.h:154
List * statlist
Definition: relation.h:532
int16 * rd_indoption
Definition: rel.h:186
bool predOK
Definition: relation.h:625
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1269
Oid * indexcollations
Definition: relation.h:605
Relids * attr_needed
Definition: relation.h:527
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
amgettuple_function amgettuple
Definition: amapi.h:210
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:435
int LOCKMODE
Definition: lockdefs.h:26
bool amcanorderbyop
Definition: amapi.h:173
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:423
List * indextlist
Definition: relation.h:618
#define RelationGetForm(relation)
Definition: rel.h:411
double tuples
Definition: relation.h:534
Oid reltablespace
Definition: relation.h:523
#define BTREE_AM_OID
Definition: pg_am.h:70
int resultRelation
Definition: parsenodes.h:113
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:504
Oid * sortopfamily
Definition: relation.h:608
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid reltablespace
Definition: relation.h:594
bool IgnoreSystemIndexes
Definition: miscinit.c:73
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
bool hypothetical
Definition: relation.h:628
#define heap_close(r, l)
Definition: heapam.h:97
bool immediate
Definition: relation.h:627
double tuples
Definition: relation.h:599
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:7863
int tree_height
Definition: relation.h:600
#define OidIsValid(objectId)
Definition: c.h:538
bool amoptionalkey
Definition: amapi.h:181
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:181
double allvisfrac
Definition: relation.h:535
signed int int32
Definition: c.h:256
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4753
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
TransactionId TransactionXmin
Definition: snapmgr.c:164
bool unique
Definition: relation.h:626
HeapTupleHeader t_data
Definition: htup.h:67
Definition: type.h:90
BlockNumber pages
Definition: relation.h:598
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:783
Form_pg_index rd_index
Definition: rel.h:159
RelOptInfo * rel
Definition: relation.h:595
bool amoptionalkey
Definition: relation.h:632
amgetbitmap_function amgetbitmap
Definition: amapi.h:211
Oid * rd_indcollation
Definition: rel.h:193
#define ERROR
Definition: elog.h:43
amcostestimate_function amcostestimate
Definition: amapi.h:204
#define NoLock
Definition: lockdefs.h:34
bool amcanorderbyop
Definition: relation.h:631
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4690
PlannerGlobal * glob
Definition: relation.h:156
#define RowExclusiveLock
Definition: lockdefs.h:38
struct FdwRoutine * fdwroutine
Definition: relation.h:545
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:57
Oid * rd_opfamily
Definition: rel.h:182
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:907
int ncolumns
Definition: relation.h:603
#define ereport(elevel, rest)
Definition: elog.h:122
bool amhasgetbitmap
Definition: relation.h:636
bool amcanparallel
Definition: amapi.h:193
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
Index relid
Definition: relation.h:522
Bitmapset * Relids
Definition: relation.h:28
Oid serverid
Definition: relation.h:541
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
bool amsearchnulls
Definition: amapi.h:185
List * indrestrictinfo
Definition: relation.h:620
void * palloc0(Size size)
Definition: mcxt.c:878
int rel_parallel_workers
Definition: relation.h:538
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
unsigned int Index
Definition: c.h:365
List * indexlist
Definition: relation.h:531
bool amsearcharray
Definition: amapi.h:183
bool amhasgettuple
Definition: relation.h:635
#define InvalidOid
Definition: postgres_ext.h:36
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:552
BlockNumber pages
Definition: relation.h:533
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:444
#define INDOPTION_DESC
Definition: pg_index.h:99
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:308
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:204
bool amsearcharray
Definition: relation.h:633
bool amcanorder
Definition: amapi.h:171
#define RelationNeedsWAL(relation)
Definition: rel.h:506
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4337
Oid * opcintype
Definition: relation.h:607
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
Oid * opfamily
Definition: relation.h:606
AttrNumber max_attr
Definition: relation.h:526
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
void list_free(List *list)
Definition: list.c:1133
int i
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:327
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1572
int * indexkeys
Definition: relation.h:604
Oid indexoid
Definition: relation.h:593
bool * canreturn
Definition: relation.h:611
bool amsearchnulls
Definition: relation.h:634
Oid * rd_opcintype
Definition: rel.h:183
void(* amcostestimate)()
Definition: relation.h:639
bool * nulls_first
Definition: relation.h:610
bool * reverse_sort
Definition: relation.h:609
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:616
int32 * attr_widths
Definition: relation.h:528
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:417
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
bool amcanparallel
Definition: relation.h:637
#define lfirst_oid(lc)
Definition: pg_list.h:108
List * indexprs
Definition: relation.h:615
bool transientPlan
Definition: relation.h:124
AttrNumber min_attr
Definition: relation.h:525
bool has_row_triggers ( PlannerInfo root,
Index  rti,
CmdType  event 
)

Definition at line 1748 of file plancat.c.

References CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ERROR, heap_close, heap_open(), NoLock, planner_rt_fetch, RangeTblEntry::relid, result, TriggerDesc::trig_delete_after_row, TriggerDesc::trig_delete_before_row, TriggerDesc::trig_insert_after_row, TriggerDesc::trig_insert_before_row, TriggerDesc::trig_update_after_row, TriggerDesc::trig_update_before_row, and RelationData::trigdesc.

Referenced by make_modifytable().

1749 {
1750  RangeTblEntry *rte = planner_rt_fetch(rti, root);
1751  Relation relation;
1752  TriggerDesc *trigDesc;
1753  bool result = false;
1754 
1755  /* Assume we already have adequate lock */
1756  relation = heap_open(rte->relid, NoLock);
1757 
1758  trigDesc = relation->trigdesc;
1759  switch (event)
1760  {
1761  case CMD_INSERT:
1762  if (trigDesc &&
1763  (trigDesc->trig_insert_after_row ||
1764  trigDesc->trig_insert_before_row))
1765  result = true;
1766  break;
1767  case CMD_UPDATE:
1768  if (trigDesc &&
1769  (trigDesc->trig_update_after_row ||
1770  trigDesc->trig_update_before_row))
1771  result = true;
1772  break;
1773  case CMD_DELETE:
1774  if (trigDesc &&
1775  (trigDesc->trig_delete_after_row ||
1776  trigDesc->trig_delete_before_row))
1777  result = true;
1778  break;
1779  default:
1780  elog(ERROR, "unrecognized CmdType: %d", (int) event);
1781  break;
1782  }
1783 
1784  heap_close(relation, NoLock);
1785  return result;
1786 }
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:120
bool trig_delete_after_row
Definition: reltrigger.h:66
#define NoLock
Definition: lockdefs.h:34
bool trig_update_before_row
Definition: reltrigger.h:60
bool trig_insert_after_row
Definition: reltrigger.h:56
bool trig_update_after_row
Definition: reltrigger.h:61
bool trig_insert_before_row
Definition: reltrigger.h:55
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define elog
Definition: elog.h:219
bool trig_delete_before_row
Definition: reltrigger.h:65
bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 1716 of file plancat.c.

References IndexOptInfo::indexkeys, RelOptInfo::indexlist, IndexOptInfo::indpred, lfirst, IndexOptInfo::ncolumns, NIL, IndexOptInfo::predOK, and IndexOptInfo::unique.

Referenced by examine_variable().

1717 {
1718  ListCell *ilist;
1719 
1720  foreach(ilist, rel->indexlist)
1721  {
1722  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1723 
1724  /*
1725  * Note: ignore partial indexes, since they don't allow us to conclude
1726  * that all attr values are distinct, *unless* they are marked predOK
1727  * which means we know the index's predicate is satisfied by the
1728  * query. We don't take any interest in expressional indexes either.
1729  * Also, a multicolumn unique index doesn't allow us to conclude that
1730  * just the specified attr is unique.
1731  */
1732  if (index->unique &&
1733  index->ncolumns == 1 &&
1734  index->indexkeys[0] == attno &&
1735  (index->indpred == NIL || index->predOK))
1736  return true;
1737  }
1738  return false;
1739 }
#define NIL
Definition: pg_list.h:69
bool predOK
Definition: relation.h:625
bool unique
Definition: relation.h:626
Definition: type.h:90
int ncolumns
Definition: relation.h:603
List * indexlist
Definition: relation.h:531
#define lfirst(lc)
Definition: pg_list.h:106
int * indexkeys
Definition: relation.h:604
List * indpred
Definition: relation.h:616
List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 557 of file plancat.c.

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, bms_add_member(), bms_equal(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, InferenceElem::expr, FirstLowInvalidHeapAttributeNumber, get_constraint_index(), heap_close, heap_open(), index_close(), index_open(), IndexIsValid, infer_collation_opclass_match(), InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, IsA, lappend(), lappend_oid(), lfirst, lfirst_oid, list_difference(), list_free(), list_member(), next, NIL, NoLock, NULL, Query::onConflict, ONCONFLICT_UPDATE, PlannerInfo::parse, predicate_implied_by(), RelationData::rd_index, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), Query::resultRelation, RowExclusiveLock, rt_fetch, Query::rtable, and Var::varattno.

Referenced by make_modifytable().

558 {
559  OnConflictExpr *onconflict = root->parse->onConflict;
560 
561  /* Iteration state */
562  Relation relation;
563  Oid relationObjectId;
564  Oid indexOidFromConstraint = InvalidOid;
565  List *indexList;
566  ListCell *l;
567 
568  /* Normalized inference attributes and inference expressions: */
569  Bitmapset *inferAttrs = NULL;
570  List *inferElems = NIL;
571 
572  /* Results */
573  List *results = NIL;
574 
575  /*
576  * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
577  * specification or named constraint. ON CONFLICT DO UPDATE statements
578  * must always provide one or the other (but parser ought to have caught
579  * that already).
580  */
581  if (onconflict->arbiterElems == NIL &&
582  onconflict->constraint == InvalidOid)
583  return NIL;
584 
585  /*
586  * We need not lock the relation since it was already locked, either by
587  * the rewriter or when expand_inherited_rtentry() added it to the query's
588  * rangetable.
589  */
590  relationObjectId = rt_fetch(root->parse->resultRelation,
591  root->parse->rtable)->relid;
592 
593  relation = heap_open(relationObjectId, NoLock);
594 
595  /*
596  * Build normalized/BMS representation of plain indexed attributes, as
597  * well as a separate list of expression items. This simplifies matching
598  * the cataloged definition of indexes.
599  */
600  foreach(l, onconflict->arbiterElems)
601  {
602  InferenceElem *elem = (InferenceElem *) lfirst(l);
603  Var *var;
604  int attno;
605 
606  if (!IsA(elem->expr, Var))
607  {
608  /* If not a plain Var, just shove it in inferElems for now */
609  inferElems = lappend(inferElems, elem->expr);
610  continue;
611  }
612 
613  var = (Var *) elem->expr;
614  attno = var->varattno;
615 
616  if (attno == 0)
617  ereport(ERROR,
618  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
619  errmsg("whole row unique index inference specifications are not supported")));
620 
621  inferAttrs = bms_add_member(inferAttrs,
623  }
624 
625  /*
626  * Lookup named constraint's index. This is not immediately returned
627  * because some additional sanity checks are required.
628  */
629  if (onconflict->constraint != InvalidOid)
630  {
631  indexOidFromConstraint = get_constraint_index(onconflict->constraint);
632 
633  if (indexOidFromConstraint == InvalidOid)
634  ereport(ERROR,
635  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
636  errmsg("constraint in ON CONFLICT clause has no associated index")));
637  }
638 
639  /*
640  * Using that representation, iterate through the list of indexes on the
641  * target relation to try and find a match
642  */
643  indexList = RelationGetIndexList(relation);
644 
645  foreach(l, indexList)
646  {
647  Oid indexoid = lfirst_oid(l);
648  Relation idxRel;
649  Form_pg_index idxForm;
650  Bitmapset *indexedAttrs;
651  List *idxExprs;
652  List *predExprs;
653  AttrNumber natt;
654  ListCell *el;
655 
656  /*
657  * Extract info from the relation descriptor for the index. We know
658  * that this is a target, so get lock type it is known will ultimately
659  * be required by the executor.
660  *
661  * Let executor complain about !indimmediate case directly, because
662  * enforcement needs to occur there anyway when an inference clause is
663  * omitted.
664  */
665  idxRel = index_open(indexoid, RowExclusiveLock);
666  idxForm = idxRel->rd_index;
667 
668  if (!IndexIsValid(idxForm))
669  goto next;
670 
671  /*
672  * Note that we do not perform a check against indcheckxmin (like e.g.
673  * get_relation_info()) here to eliminate candidates, because
674  * uniqueness checking only cares about the most recently committed
675  * tuple versions.
676  */
677 
678  /*
679  * Look for match on "ON constraint_name" variant, which may not be
680  * unique constraint. This can only be a constraint name.
681  */
682  if (indexOidFromConstraint == idxForm->indexrelid)
683  {
684  if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
685  ereport(ERROR,
686  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
687  errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
688 
689  results = lappend_oid(results, idxForm->indexrelid);
690  list_free(indexList);
691  index_close(idxRel, NoLock);
692  heap_close(relation, NoLock);
693  return results;
694  }
695  else if (indexOidFromConstraint != InvalidOid)
696  {
697  /* No point in further work for index in named constraint case */
698  goto next;
699  }
700 
701  /*
702  * Only considering conventional inference at this point (not named
703  * constraints), so index under consideration can be immediately
704  * skipped if it's not unique
705  */
706  if (!idxForm->indisunique)
707  goto next;
708 
709  /* Build BMS representation of plain (non expression) index attrs */
710  indexedAttrs = NULL;
711  for (natt = 0; natt < idxForm->indnatts; natt++)
712  {
713  int attno = idxRel->rd_index->indkey.values[natt];
714 
715  if (attno != 0)
716  indexedAttrs = bms_add_member(indexedAttrs,
718  }
719 
720  /* Non-expression attributes (if any) must match */
721  if (!bms_equal(indexedAttrs, inferAttrs))
722  goto next;
723 
724  /* Expression attributes (if any) must match */
725  idxExprs = RelationGetIndexExpressions(idxRel);
726  foreach(el, onconflict->arbiterElems)
727  {
728  InferenceElem *elem = (InferenceElem *) lfirst(el);
729 
730  /*
731  * Ensure that collation/opclass aspects of inference expression
732  * element match. Even though this loop is primarily concerned
733  * with matching expressions, it is a convenient point to check
734  * this for both expressions and ordinary (non-expression)
735  * attributes appearing as inference elements.
736  */
737  if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
738  goto next;
739 
740  /*
741  * Plain Vars don't factor into count of expression elements, and
742  * the question of whether or not they satisfy the index
743  * definition has already been considered (they must).
744  */
745  if (IsA(elem->expr, Var))
746  continue;
747 
748  /*
749  * Might as well avoid redundant check in the rare cases where
750  * infer_collation_opclass_match() is required to do real work.
751  * Otherwise, check that element expression appears in cataloged
752  * index definition.
753  */
754  if (elem->infercollid != InvalidOid ||
755  elem->inferopclass != InvalidOid ||
756  list_member(idxExprs, elem->expr))
757  continue;
758 
759  goto next;
760  }
761 
762  /*
763  * Now that all inference elements were matched, ensure that the
764  * expression elements from inference clause are not missing any
765  * cataloged expressions. This does the right thing when unique
766  * indexes redundantly repeat the same attribute, or if attributes
767  * redundantly appear multiple times within an inference clause.
768  */
769  if (list_difference(idxExprs, inferElems) != NIL)
770  goto next;
771 
772  /*
773  * If it's a partial index, its predicate must be implied by the ON
774  * CONFLICT's WHERE clause.
775  */
776  predExprs = RelationGetIndexPredicate(idxRel);
777 
778  if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere))
779  goto next;
780 
781  results = lappend_oid(results, idxForm->indexrelid);
782 next:
783  index_close(idxRel, NoLock);
784  }
785 
786  list_free(indexList);
787  heap_close(relation, NoLock);
788 
789  if (results == NIL)
790  ereport(ERROR,
791  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
792  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
793 
794  return results;
795 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
Query * parse
Definition: relation.h:154
static int32 next
Definition: blutils.c:210
bool predicate_implied_by(List *predicate_list, List *restrictinfo_list)
Definition: predtest.c:128
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
OnConflictExpr * onConflict
Definition: parsenodes.h:133
int resultRelation
Definition: parsenodes.h:113
static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel, List *idxExprs)
Definition: plancat.c:825
int errcode(int sqlerrcode)
Definition: elog.c:575
AttrNumber varattno
Definition: primnodes.h:168
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4753
List * arbiterElems
Definition: primnodes.h:1474
Form_pg_index rd_index
Definition: rel.h:159
List * rtable
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:43
bool list_member(const List *list, const void *datum)
Definition: list.c:444
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4690
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend(List *list, void *datum)
Definition: list.c:128
OnConflictAction action
Definition: primnodes.h:1471
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
List * list_difference(const List *list1, const List *list2)
Definition: list.c:858
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4337
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
Node * arbiterWhere
Definition: primnodes.h:1476
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
Oid get_constraint_index(Oid constraintId)
Definition: pg_depend.c:618
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define lfirst_oid(lc)
Definition: pg_list.h:108
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:130
Selectivity join_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1672 of file plancat.c.

References DatumGetFloat8, elog, ERROR, get_oprjoin(), Int16GetDatum, ObjectIdGetDatum, OidFunctionCall5Coll(), PointerGetDatum, and result.

Referenced by clause_selectivity(), and rowcomparesel().

1678 {
1679  RegProcedure oprjoin = get_oprjoin(operatorid);
1680  float8 result;
1681 
1682  /*
1683  * if the oprjoin procedure is missing for whatever reason, use a
1684  * selectivity of 0.5
1685  */
1686  if (!oprjoin)
1687  return (Selectivity) 0.5;
1688 
1689  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1690  inputcollid,
1691  PointerGetDatum(root),
1692  ObjectIdGetDatum(operatorid),
1693  PointerGetDatum(args),
1694  Int16GetDatum(jointype),
1695  PointerGetDatum(sjinfo)));
1696 
1697  if (result < 0.0 || result > 1.0)
1698  elog(ERROR, "invalid join selectivity: %f", result);
1699 
1700  return (Selectivity) result;
1701 }
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1353
#define PointerGetDatum(X)
Definition: postgres.h:562
regproc RegProcedure
Definition: c.h:395
#define Int16GetDatum(X)
Definition: postgres.h:457
return result
Definition: formatting.c:1618
double Selectivity
Definition: nodes.h:627
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:381
#define DatumGetFloat8(X)
Definition: postgres.h:734
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1734
#define elog
Definition: elog.h:219
bool relation_excluded_by_constraints ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)

Definition at line 1332 of file plancat.c.

References RelOptInfo::baserestrictinfo, RestrictInfo::clause, constraint_exclusion, CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_PARTITION, contain_mutable_functions(), DatumGetBool, get_relation_constraints(), PlannerInfo::hasInheritedTarget, RangeTblEntry::inh, IsA, lappend(), lfirst, linitial, list_length(), NIL, PlannerInfo::parse, predicate_refuted_by(), RelOptInfo::relid, RangeTblEntry::relid, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, Query::resultRelation, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by set_append_rel_size(), and set_rel_size().

1334 {
1335  List *safe_restrictions;
1336  List *constraint_pred;
1337  List *safe_constraints;
1338  ListCell *lc;
1339 
1340  /*
1341  * Regardless of the setting of constraint_exclusion, detect
1342  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1343  * reduce "anything AND FALSE" to just "FALSE", any such case should
1344  * result in exactly one baserestrictinfo entry. This doesn't fire very
1345  * often, but it seems cheap enough to be worth doing anyway. (Without
1346  * this, we'd miss some optimizations that 9.5 and earlier found via much
1347  * more roundabout methods.)
1348  */
1349  if (list_length(rel->baserestrictinfo) == 1)
1350  {
1352  Expr *clause = rinfo->clause;
1353 
1354  if (clause && IsA(clause, Const) &&
1355  (((Const *) clause)->constisnull ||
1356  !DatumGetBool(((Const *) clause)->constvalue)))
1357  return true;
1358  }
1359 
1360  /* Skip further tests if constraint exclusion is disabled for the rel */
1363  !(rel->reloptkind == RELOPT_OTHER_MEMBER_REL ||
1364  (root->hasInheritedTarget &&
1365  rel->reloptkind == RELOPT_BASEREL &&
1366  rel->relid == root->parse->resultRelation))))
1367  return false;
1368 
1369  /*
1370  * Check for self-contradictory restriction clauses. We dare not make
1371  * deductions with non-immutable functions, but any immutable clauses that
1372  * are self-contradictory allow us to conclude the scan is unnecessary.
1373  *
1374  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1375  * expecting to see any in its predicate argument.
1376  */
1377  safe_restrictions = NIL;
1378  foreach(lc, rel->baserestrictinfo)
1379  {
1380  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1381 
1382  if (!contain_mutable_functions((Node *) rinfo->clause))
1383  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1384  }
1385 
1386  if (predicate_refuted_by(safe_restrictions, safe_restrictions))
1387  return true;
1388 
1389  /* Only plain relations have constraints */
1390  if (rte->rtekind != RTE_RELATION || rte->inh)
1391  return false;
1392 
1393  /*
1394  * OK to fetch the constraint expressions. Include "col IS NOT NULL"
1395  * expressions for attnotnull columns, in case we can refute those.
1396  */
1397  constraint_pred = get_relation_constraints(root, rte->relid, rel, true);
1398 
1399  /*
1400  * We do not currently enforce that CHECK constraints contain only
1401  * immutable functions, so it's necessary to check here. We daren't draw
1402  * conclusions from plan-time evaluation of non-immutable functions. Since
1403  * they're ANDed, we can just ignore any mutable constraints in the list,
1404  * and reason about the rest.
1405  */
1406  safe_constraints = NIL;
1407  foreach(lc, constraint_pred)
1408  {
1409  Node *pred = (Node *) lfirst(lc);
1410 
1411  if (!contain_mutable_functions(pred))
1412  safe_constraints = lappend(safe_constraints, pred);
1413  }
1414 
1415  /*
1416  * The constraints are effectively ANDed together, so we can just try to
1417  * refute the entire collection at once. This may allow us to make proofs
1418  * that would fail if we took them individually.
1419  *
1420  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1421  * an obvious optimization. Some of the clauses might be OR clauses that
1422  * have volatile and nonvolatile subclauses, and it's OK to make
1423  * deductions with the nonvolatile parts.
1424  */
1425  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo))
1426  return true;
1427 
1428  return false;
1429 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
Query * parse
Definition: relation.h:154
RelOptKind reloptkind
Definition: relation.h:491
List * baserestrictinfo
Definition: relation.h:549
int constraint_exclusion
Definition: plancat.c:54
int resultRelation
Definition: parsenodes.h:113
Definition: nodes.h:504
#define linitial(l)
Definition: pg_list.h:110
#define DatumGetBool(X)
Definition: postgres.h:399
Index relid
Definition: relation.h:522
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1679
#define lfirst(lc)
Definition: pg_list.h:106
bool hasInheritedTarget
Definition: relation.h:296
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:916
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:877
bool predicate_refuted_by(List *predicate_list, List *restrictinfo_list)
Definition: predtest.c:186
Definition: pg_list.h:45
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
Definition: plancat.c:1143
Selectivity restriction_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
int  varRelid 
)

Definition at line 1635 of file plancat.c.

References DatumGetFloat8, elog, ERROR, get_oprrest(), Int32GetDatum, ObjectIdGetDatum, OidFunctionCall4Coll(), PointerGetDatum, and result.

Referenced by clause_selectivity(), and rowcomparesel().

1640 {
1641  RegProcedure oprrest = get_oprrest(operatorid);
1642  float8 result;
1643 
1644  /*
1645  * if the oprrest procedure is missing for whatever reason, use a
1646  * selectivity of 0.5
1647  */
1648  if (!oprrest)
1649  return (Selectivity) 0.5;
1650 
1651  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1652  inputcollid,
1653  PointerGetDatum(root),
1654  ObjectIdGetDatum(operatorid),
1655  PointerGetDatum(args),
1656  Int32GetDatum(varRelid)));
1657 
1658  if (result < 0.0 || result > 1.0)
1659  elog(ERROR, "invalid restriction selectivity: %f", result);
1660 
1661  return (Selectivity) result;
1662 }
#define PointerGetDatum(X)
Definition: postgres.h:562
regproc RegProcedure
Definition: c.h:395
return result
Definition: formatting.c:1618
double Selectivity
Definition: nodes.h:627
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:381
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1329
#define DatumGetFloat8(X)
Definition: postgres.h:734
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1704
#define Int32GetDatum(X)
Definition: postgres.h:485
#define elog
Definition: elog.h:219

Variable Documentation

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook

Definition at line 57 of file plancat.c.

Referenced by get_relation_info().