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 1470 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_NAMEDTUPLESTORE, RTE_RELATION, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::subquery, Query::targetList, and Var::varattno.

Referenced by create_scan_plan().

1471 {
1472  List *tlist = NIL;
1473  Index varno = rel->relid;
1474  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1475  Relation relation;
1476  Query *subquery;
1477  Var *var;
1478  ListCell *l;
1479  int attrno,
1480  numattrs;
1481  List *colvars;
1482 
1483  switch (rte->rtekind)
1484  {
1485  case RTE_RELATION:
1486  /* Assume we already have adequate lock */
1487  relation = heap_open(rte->relid, NoLock);
1488 
1489  numattrs = RelationGetNumberOfAttributes(relation);
1490  for (attrno = 1; attrno <= numattrs; attrno++)
1491  {
1492  Form_pg_attribute att_tup = relation->rd_att->attrs[attrno - 1];
1493 
1494  if (att_tup->attisdropped)
1495  {
1496  /* found a dropped col, so punt */
1497  tlist = NIL;
1498  break;
1499  }
1500 
1501  var = makeVar(varno,
1502  attrno,
1503  att_tup->atttypid,
1504  att_tup->atttypmod,
1505  att_tup->attcollation,
1506  0);
1507 
1508  tlist = lappend(tlist,
1509  makeTargetEntry((Expr *) var,
1510  attrno,
1511  NULL,
1512  false));
1513  }
1514 
1515  heap_close(relation, NoLock);
1516  break;
1517 
1518  case RTE_SUBQUERY:
1519  subquery = rte->subquery;
1520  foreach(l, subquery->targetList)
1521  {
1522  TargetEntry *tle = (TargetEntry *) lfirst(l);
1523 
1524  /*
1525  * A resjunk column of the subquery can be reflected as
1526  * resjunk in the physical tlist; we need not punt.
1527  */
1528  var = makeVarFromTargetEntry(varno, tle);
1529 
1530  tlist = lappend(tlist,
1531  makeTargetEntry((Expr *) var,
1532  tle->resno,
1533  NULL,
1534  tle->resjunk));
1535  }
1536  break;
1537 
1538  case RTE_FUNCTION:
1539  case RTE_TABLEFUNC:
1540  case RTE_VALUES:
1541  case RTE_CTE:
1542  case RTE_NAMEDTUPLESTORE:
1543  /* Not all of these can have dropped cols, but share code anyway */
1544  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1545  NULL, &colvars);
1546  foreach(l, colvars)
1547  {
1548  var = (Var *) lfirst(l);
1549 
1550  /*
1551  * A non-Var in expandRTE's output means a dropped column;
1552  * must punt.
1553  */
1554  if (!IsA(var, Var))
1555  {
1556  tlist = NIL;
1557  break;
1558  }
1559 
1560  tlist = lappend(tlist,
1561  makeTargetEntry((Expr *) var,
1562  var->varattno,
1563  NULL,
1564  false));
1565  }
1566  break;
1567 
1568  default:
1569  /* caller error */
1570  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1571  (int) rte->rtekind);
1572  break;
1573  }
1574 
1575  return tlist;
1576 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#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:138
bool resjunk
Definition: primnodes.h:1374
#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:1368
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
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:552
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:1284
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:928
Query * subquery
Definition: parsenodes.h:946
#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 908 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().

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

1111 {
1112  int32 result;
1113  Relation relation;
1114 
1115  /* As above, assume relation is already locked */
1116  relation = heap_open(relid, NoLock);
1117 
1118  result = get_rel_data_width(relation, attr_widths);
1119 
1120  heap_close(relation, NoLock);
1121 
1122  return result;
1123 }
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:1068
#define NoLock
Definition: lockdefs.h:34
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
void get_relation_info ( PlannerInfo root,
Oid  relationObjectId,
bool  inhparent,
RelOptInfo rel 
)

Definition at line 101 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().

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

Definition at line 1765 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().

1766 {
1767  RangeTblEntry *rte = planner_rt_fetch(rti, root);
1768  Relation relation;
1769  TriggerDesc *trigDesc;
1770  bool result = false;
1771 
1772  /* Assume we already have adequate lock */
1773  relation = heap_open(rte->relid, NoLock);
1774 
1775  trigDesc = relation->trigdesc;
1776  switch (event)
1777  {
1778  case CMD_INSERT:
1779  if (trigDesc &&
1780  (trigDesc->trig_insert_after_row ||
1781  trigDesc->trig_insert_before_row))
1782  result = true;
1783  break;
1784  case CMD_UPDATE:
1785  if (trigDesc &&
1786  (trigDesc->trig_update_after_row ||
1787  trigDesc->trig_update_before_row))
1788  result = true;
1789  break;
1790  case CMD_DELETE:
1791  if (trigDesc &&
1792  (trigDesc->trig_delete_after_row ||
1793  trigDesc->trig_delete_before_row))
1794  result = true;
1795  break;
1796  default:
1797  elog(ERROR, "unrecognized CmdType: %d", (int) event);
1798  break;
1799  }
1800 
1801  heap_close(relation, NoLock);
1802  return result;
1803 }
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:1284
#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 1733 of file plancat.c.

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

Referenced by examine_variable().

1734 {
1735  ListCell *ilist;
1736 
1737  foreach(ilist, rel->indexlist)
1738  {
1739  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1740 
1741  /*
1742  * Note: ignore partial indexes, since they don't allow us to conclude
1743  * that all attr values are distinct, *unless* they are marked predOK
1744  * which means we know the index's predicate is satisfied by the
1745  * query. We don't take any interest in expressional indexes either.
1746  * Also, a multicolumn unique index doesn't allow us to conclude that
1747  * just the specified attr is unique.
1748  */
1749  if (index->unique &&
1750  index->ncolumns == 1 &&
1751  index->indexkeys[0] == attno &&
1752  (index->indpred == NIL || index->predOK))
1753  return true;
1754  }
1755  return false;
1756 }
#define NIL
Definition: pg_list.h:69
bool predOK
Definition: relation.h:662
bool unique
Definition: relation.h:663
Definition: type.h:90
int ncolumns
Definition: relation.h:640
List * indexlist
Definition: relation.h:561
#define lfirst(lc)
Definition: pg_list.h:106
int * indexkeys
Definition: relation.h:641
List * indpred
Definition: relation.h:653
List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 558 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().

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

Definition at line 1689 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1695 {
1696  RegProcedure oprjoin = get_oprjoin(operatorid);
1697  float8 result;
1698 
1699  /*
1700  * if the oprjoin procedure is missing for whatever reason, use a
1701  * selectivity of 0.5
1702  */
1703  if (!oprjoin)
1704  return (Selectivity) 0.5;
1705 
1706  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1707  inputcollid,
1708  PointerGetDatum(root),
1709  ObjectIdGetDatum(operatorid),
1710  PointerGetDatum(args),
1711  Int16GetDatum(jointype),
1712  PointerGetDatum(sjinfo)));
1713 
1714  if (result < 0.0 || result > 1.0)
1715  elog(ERROR, "invalid join selectivity: %f", result);
1716 
1717  return (Selectivity) result;
1718 }
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1385
#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:638
#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:1425
#define elog
Definition: elog.h:219
bool relation_excluded_by_constraints ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)

Definition at line 1345 of file plancat.c.

References Assert, RelOptInfo::baserestrictinfo, RestrictInfo::clause, constraint_exclusion, CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_PARTITION, contain_mutable_functions(), DatumGetBool, get_relation_constraints(), PlannerInfo::hasInheritedTarget, RangeTblEntry::inh, IS_SIMPLE_REL, 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().

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

Definition at line 1652 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1657 {
1658  RegProcedure oprrest = get_oprrest(operatorid);
1659  float8 result;
1660 
1661  /*
1662  * if the oprrest procedure is missing for whatever reason, use a
1663  * selectivity of 0.5
1664  */
1665  if (!oprrest)
1666  return (Selectivity) 0.5;
1667 
1668  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1669  inputcollid,
1670  PointerGetDatum(root),
1671  ObjectIdGetDatum(operatorid),
1672  PointerGetDatum(args),
1673  Int32GetDatum(varRelid)));
1674 
1675  if (result < 0.0 || result > 1.0)
1676  elog(ERROR, "invalid restriction selectivity: %f", result);
1677 
1678  return (Selectivity) result;
1679 }
#define PointerGetDatum(X)
Definition: postgres.h:562
regproc RegProcedure
Definition: c.h:395
return result
Definition: formatting.c:1618
double Selectivity
Definition: nodes.h:638
#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:1361
#define DatumGetFloat8(X)
Definition: postgres.h:734
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1395
#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().