PostgreSQL Source Code  git master
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

◆ get_relation_info_hook_type

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

◆ build_physical_tlist()

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1558 of file plancat.c.

References elog, ERROR, expandRTE(), heap_close, heap_open(), IsA, lappend(), lfirst, makeTargetEntry(), makeVar(), makeVarFromTargetEntry(), NIL, NoLock, 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 TupleDescAttr.

Referenced by create_scan_plan().

1559 {
1560  List *tlist = NIL;
1561  Index varno = rel->relid;
1562  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1563  Relation relation;
1564  Query *subquery;
1565  Var *var;
1566  ListCell *l;
1567  int attrno,
1568  numattrs;
1569  List *colvars;
1570 
1571  switch (rte->rtekind)
1572  {
1573  case RTE_RELATION:
1574  /* Assume we already have adequate lock */
1575  relation = heap_open(rte->relid, NoLock);
1576 
1577  numattrs = RelationGetNumberOfAttributes(relation);
1578  for (attrno = 1; attrno <= numattrs; attrno++)
1579  {
1580  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1581  attrno - 1);
1582 
1583  if (att_tup->attisdropped || att_tup->atthasmissing)
1584  {
1585  /* found a dropped or missing col, so punt */
1586  tlist = NIL;
1587  break;
1588  }
1589 
1590  var = makeVar(varno,
1591  attrno,
1592  att_tup->atttypid,
1593  att_tup->atttypmod,
1594  att_tup->attcollation,
1595  0);
1596 
1597  tlist = lappend(tlist,
1598  makeTargetEntry((Expr *) var,
1599  attrno,
1600  NULL,
1601  false));
1602  }
1603 
1604  heap_close(relation, NoLock);
1605  break;
1606 
1607  case RTE_SUBQUERY:
1608  subquery = rte->subquery;
1609  foreach(l, subquery->targetList)
1610  {
1611  TargetEntry *tle = (TargetEntry *) lfirst(l);
1612 
1613  /*
1614  * A resjunk column of the subquery can be reflected as
1615  * resjunk in the physical tlist; we need not punt.
1616  */
1617  var = makeVarFromTargetEntry(varno, tle);
1618 
1619  tlist = lappend(tlist,
1620  makeTargetEntry((Expr *) var,
1621  tle->resno,
1622  NULL,
1623  tle->resjunk));
1624  }
1625  break;
1626 
1627  case RTE_FUNCTION:
1628  case RTE_TABLEFUNC:
1629  case RTE_VALUES:
1630  case RTE_CTE:
1631  case RTE_NAMEDTUPLESTORE:
1632  /* Not all of these can have dropped cols, but share code anyway */
1633  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1634  NULL, &colvars);
1635  foreach(l, colvars)
1636  {
1637  var = (Var *) lfirst(l);
1638 
1639  /*
1640  * A non-Var in expandRTE's output means a dropped column;
1641  * must punt.
1642  */
1643  if (!IsA(var, Var))
1644  {
1645  tlist = NIL;
1646  break;
1647  }
1648 
1649  tlist = lappend(tlist,
1650  makeTargetEntry((Expr *) var,
1651  var->varattno,
1652  NULL,
1653  false));
1654  }
1655  break;
1656 
1657  default:
1658  /* caller error */
1659  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1660  (int) rte->rtekind);
1661  break;
1662  }
1663 
1664  return tlist;
1665 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:413
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:104
#define heap_close(r, l)
Definition: heapam.h:97
Definition: primnodes.h:164
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1383
#define planner_rt_fetch(rti, root)
Definition: relation.h:344
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
AttrNumber resno
Definition: primnodes.h:1377
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:237
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:640
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:1294
unsigned int Index
Definition: c.h:442
TupleDesc rd_att
Definition: rel.h:85
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:962
Query * subquery
Definition: parsenodes.h:985
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ estimate_rel_size()

void estimate_rel_size ( Relation  rel,
int32 attr_widths,
BlockNumber pages,
double *  tuples,
double *  allvisfrac 
)

Definition at line 939 of file plancat.c.

References get_rel_data_width(), MAXALIGN, RelationData::rd_rel, relallvisible, RelationGetNumberOfBlocks, relpages, reltuples, rint(), SizeofHeapTupleHeader, and SizeOfPageHeaderData.

Referenced by get_relation_info(), hashbuild(), and plan_create_index_workers().

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

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1141 of file plancat.c.

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

1142 {
1143  int32 result;
1144  Relation relation;
1145 
1146  /* As above, assume relation is already locked */
1147  relation = heap_open(relid, NoLock);
1148 
1149  result = get_rel_data_width(relation, attr_widths);
1150 
1151  heap_close(relation, NoLock);
1152 
1153  return result;
1154 }
#define heap_close(r, l)
Definition: heapam.h:97
signed int int32
Definition: c.h:313
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1099
#define NoLock
Definition: lockdefs.h:34
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294

◆ get_relation_info()

void get_relation_info ( PlannerInfo root,
Oid  relationObjectId,
bool  inhparent,
RelOptInfo rel 
)

Definition at line 108 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, 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, IndexOptInfo::indpred, IndexOptInfo::indrestrictinfo, InvalidOid, IsSystemRelation(), lcons(), lfirst_oid, list_free(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, NoLock, 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, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, Query::resultRelation, IndexOptInfo::reverse_sort, RowExclusiveLock, RelOptInfo::serverid, set_relation_partition_info(), 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().

110 {
111  Index varno = rel->relid;
112  Relation relation;
113  bool hasindex;
114  List *indexinfos = NIL;
115 
116  /*
117  * We need not lock the relation since it was already locked, either by
118  * the rewriter or when expand_inherited_rtentry() added it to the query's
119  * rangetable.
120  */
121  relation = heap_open(relationObjectId, NoLock);
122 
123  /* Temporary and unlogged relations are inaccessible during recovery. */
124  if (!RelationNeedsWAL(relation) && RecoveryInProgress())
125  ereport(ERROR,
126  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
127  errmsg("cannot access temporary or unlogged relations during recovery")));
128 
130  rel->max_attr = RelationGetNumberOfAttributes(relation);
131  rel->reltablespace = RelationGetForm(relation)->reltablespace;
132 
133  Assert(rel->max_attr >= rel->min_attr);
134  rel->attr_needed = (Relids *)
135  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
136  rel->attr_widths = (int32 *)
137  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
138 
139  /*
140  * Estimate relation size --- unless it's an inheritance parent, in which
141  * case the size will be computed later in set_append_rel_pathlist, and we
142  * must leave it zero for now to avoid bollixing the total_table_pages
143  * calculation.
144  */
145  if (!inhparent)
146  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
147  &rel->pages, &rel->tuples, &rel->allvisfrac);
148 
149  /* Retrieve the parallel_workers reloption, or -1 if not set. */
151 
152  /*
153  * Make list of indexes. Ignore indexes on system catalogs if told to.
154  * Don't bother with indexes for an inheritance parent, either.
155  */
156  if (inhparent ||
157  (IgnoreSystemIndexes && IsSystemRelation(relation)))
158  hasindex = false;
159  else
160  hasindex = relation->rd_rel->relhasindex;
161 
162  if (hasindex)
163  {
164  List *indexoidlist;
165  ListCell *l;
166  LOCKMODE lmode;
167 
168  indexoidlist = RelationGetIndexList(relation);
169 
170  /*
171  * For each index, we get the same type of lock that the executor will
172  * need, and do not release it. This saves a couple of trips to the
173  * shared lock manager while not creating any real loss of
174  * concurrency, because no schema changes could be happening on the
175  * index while we hold lock on the parent rel, and neither lock type
176  * blocks any other kind of index operation.
177  */
178  if (rel->relid == root->parse->resultRelation)
179  lmode = RowExclusiveLock;
180  else
181  lmode = AccessShareLock;
182 
183  foreach(l, indexoidlist)
184  {
185  Oid indexoid = lfirst_oid(l);
186  Relation indexRelation;
188  IndexAmRoutine *amroutine;
189  IndexOptInfo *info;
190  int ncolumns,
191  nkeycolumns;
192  int i;
193 
194  /*
195  * Extract info from the relation descriptor for the index.
196  */
197  indexRelation = index_open(indexoid, lmode);
198  index = indexRelation->rd_index;
199 
200  /*
201  * Ignore invalid indexes, since they can't safely be used for
202  * queries. Note that this is OK because the data structure we
203  * are constructing is only used by the planner --- the executor
204  * still needs to insert into "invalid" indexes, if they're marked
205  * IndexIsReady.
206  */
207  if (!IndexIsValid(index))
208  {
209  index_close(indexRelation, NoLock);
210  continue;
211  }
212 
213  /*
214  * Ignore partitioned indexes, since they are not usable for
215  * queries.
216  */
217  if (indexRelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
218  {
219  index_close(indexRelation, NoLock);
220  continue;
221  }
222 
223  /*
224  * If the index is valid, but cannot yet be used, ignore it; but
225  * mark the plan we are generating as transient. See
226  * src/backend/access/heap/README.HOT for discussion.
227  */
228  if (index->indcheckxmin &&
231  {
232  root->glob->transientPlan = true;
233  index_close(indexRelation, NoLock);
234  continue;
235  }
236 
237  info = makeNode(IndexOptInfo);
238 
239  info->indexoid = index->indexrelid;
240  info->reltablespace =
241  RelationGetForm(indexRelation)->reltablespace;
242  info->rel = rel;
243  info->ncolumns = ncolumns = index->indnatts;
244  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
245 
246  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
247  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
248  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
249  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
250  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
251 
252  for (i = 0; i < ncolumns; i++)
253  {
254  info->indexkeys[i] = index->indkey.values[i];
255  info->canreturn[i] = index_can_return(indexRelation, i + 1);
256  }
257 
258  for (i = 0; i < nkeycolumns; i++)
259  {
260  info->opfamily[i] = indexRelation->rd_opfamily[i];
261  info->opcintype[i] = indexRelation->rd_opcintype[i];
262  info->indexcollations[i] = indexRelation->rd_indcollation[i];
263  }
264 
265  info->relam = indexRelation->rd_rel->relam;
266 
267  /* We copy just the fields we need, not all of rd_amroutine */
268  amroutine = indexRelation->rd_amroutine;
269  info->amcanorderbyop = amroutine->amcanorderbyop;
270  info->amoptionalkey = amroutine->amoptionalkey;
271  info->amsearcharray = amroutine->amsearcharray;
272  info->amsearchnulls = amroutine->amsearchnulls;
273  info->amcanparallel = amroutine->amcanparallel;
274  info->amhasgettuple = (amroutine->amgettuple != NULL);
275  info->amhasgetbitmap = (amroutine->amgetbitmap != NULL);
276  info->amcostestimate = amroutine->amcostestimate;
277  Assert(info->amcostestimate != NULL);
278 
279  /*
280  * Fetch the ordering information for the index, if any.
281  */
282  if (info->relam == BTREE_AM_OID)
283  {
284  /*
285  * If it's a btree index, we can use its opfamily OIDs
286  * directly as the sort ordering opfamily OIDs.
287  */
288  Assert(amroutine->amcanorder);
289 
290  info->sortopfamily = info->opfamily;
291  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
292  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
293 
294  for (i = 0; i < nkeycolumns; i++)
295  {
296  int16 opt = indexRelation->rd_indoption[i];
297 
298  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
299  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
300  }
301  }
302  else if (amroutine->amcanorder)
303  {
304  /*
305  * Otherwise, identify the corresponding btree opfamilies by
306  * trying to map this index's "<" operators into btree. Since
307  * "<" uniquely defines the behavior of a sort order, this is
308  * a sufficient test.
309  *
310  * XXX This method is rather slow and also requires the
311  * undesirable assumption that the other index AM numbers its
312  * strategies the same as btree. It'd be better to have a way
313  * to explicitly declare the corresponding btree opfamily for
314  * each opfamily of the other index type. But given the lack
315  * of current or foreseeable amcanorder index types, it's not
316  * worth expending more effort on now.
317  */
318  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
319  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
320  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
321 
322  for (i = 0; i < nkeycolumns; i++)
323  {
324  int16 opt = indexRelation->rd_indoption[i];
325  Oid ltopr;
326  Oid btopfamily;
327  Oid btopcintype;
328  int16 btstrategy;
329 
330  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
331  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
332 
333  ltopr = get_opfamily_member(info->opfamily[i],
334  info->opcintype[i],
335  info->opcintype[i],
337  if (OidIsValid(ltopr) &&
339  &btopfamily,
340  &btopcintype,
341  &btstrategy) &&
342  btopcintype == info->opcintype[i] &&
343  btstrategy == BTLessStrategyNumber)
344  {
345  /* Successful mapping */
346  info->sortopfamily[i] = btopfamily;
347  }
348  else
349  {
350  /* Fail ... quietly treat index as unordered */
351  info->sortopfamily = NULL;
352  info->reverse_sort = NULL;
353  info->nulls_first = NULL;
354  break;
355  }
356  }
357  }
358  else
359  {
360  info->sortopfamily = NULL;
361  info->reverse_sort = NULL;
362  info->nulls_first = NULL;
363  }
364 
365  /*
366  * Fetch the index expressions and predicate, if any. We must
367  * modify the copies we obtain from the relcache to have the
368  * correct varno for the parent relation, so that they match up
369  * correctly against qual clauses.
370  */
371  info->indexprs = RelationGetIndexExpressions(indexRelation);
372  info->indpred = RelationGetIndexPredicate(indexRelation);
373  if (info->indexprs && varno != 1)
374  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
375  if (info->indpred && varno != 1)
376  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
377 
378  /* Build targetlist using the completed indexprs data */
379  info->indextlist = build_index_tlist(root, info, relation);
380 
381  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
382  info->predOK = false; /* set later, in indxpath.c */
383  info->unique = index->indisunique;
384  info->immediate = index->indimmediate;
385  info->hypothetical = false;
386 
387  /*
388  * Estimate the index size. If it's not a partial index, we lock
389  * the number-of-tuples estimate to equal the parent table; if it
390  * is partial then we have to use the same methods as we would for
391  * a table, except we can be sure that the index is not larger
392  * than the table.
393  */
394  if (info->indpred == NIL)
395  {
396  info->pages = RelationGetNumberOfBlocks(indexRelation);
397  info->tuples = rel->tuples;
398  }
399  else
400  {
401  double allvisfrac; /* dummy */
402 
403  estimate_rel_size(indexRelation, NULL,
404  &info->pages, &info->tuples, &allvisfrac);
405  if (info->tuples > rel->tuples)
406  info->tuples = rel->tuples;
407  }
408 
409  if (info->relam == BTREE_AM_OID)
410  {
411  /* For btrees, get tree height while we have the index open */
412  info->tree_height = _bt_getrootheight(indexRelation);
413  }
414  else
415  {
416  /* For other index types, just set it to "unknown" for now */
417  info->tree_height = -1;
418  }
419 
420  index_close(indexRelation, NoLock);
421 
422  indexinfos = lcons(info, indexinfos);
423  }
424 
425  list_free(indexoidlist);
426  }
427 
428  rel->indexlist = indexinfos;
429 
430  rel->statlist = get_relation_statistics(rel, relation);
431 
432  /* Grab foreign-table info using the relcache, while we have it */
433  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
434  {
436  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
437  }
438  else
439  {
440  rel->serverid = InvalidOid;
441  rel->fdwroutine = NULL;
442  }
443 
444  /* Collect info about relation's foreign keys, if relevant */
445  get_relation_foreign_keys(root, rel, relation, inhparent);
446 
447  /*
448  * Collect info about relation's partitioning scheme, if any. Only
449  * inheritance parents may be partitioned.
450  */
451  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
452  set_relation_partition_info(root, rel, relation);
453 
454  heap_close(relation, NoLock);
455 
456  /*
457  * Allow a plugin to editorialize on the info we obtained from the
458  * catalogs. Actions might include altering the assumed relation size,
459  * removing an index, or adding a hypothetical index to the indexlist.
460  */
462  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
463 }
signed short int16
Definition: c.h:312
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:169
List * statlist
Definition: relation.h:650
int16 * rd_indoption
Definition: rel.h:158
bool predOK
Definition: relation.h:788
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1312
Oid * indexcollations
Definition: relation.h:767
Relids * attr_needed
Definition: relation.h:645
bool IsSystemRelation(Relation relation)
Definition: catalog.c:63
#define IndexIsValid(indexForm)
Definition: pg_index.h:85
amgettuple_function amgettuple
Definition: amapi.h:219
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:594
int LOCKMODE
Definition: lockdefs.h:26
bool amcanorderbyop
Definition: amapi.h:174
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:413
List * indextlist
Definition: relation.h:780
#define RelationGetForm(relation)
Definition: rel.h:401
double tuples
Definition: relation.h:652
Oid reltablespace
Definition: relation.h:641
int resultRelation
Definition: parsenodes.h:122
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:517
Oid * sortopfamily
Definition: relation.h:770
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid reltablespace
Definition: relation.h:754
bool IgnoreSystemIndexes
Definition: miscinit.c:75
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
bool hypothetical
Definition: relation.h:791
#define heap_close(r, l)
Definition: heapam.h:97
bool immediate
Definition: relation.h:790
double tuples
Definition: relation.h:759
Form_pg_class rd_rel
Definition: rel.h:84
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:7949
int tree_height
Definition: relation.h:760
#define OidIsValid(objectId)
Definition: c.h:605
bool amoptionalkey
Definition: amapi.h:182
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:153
double allvisfrac
Definition: relation.h:653
signed int int32
Definition: c.h:313
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4608
struct HeapTupleData * rd_indextuple
Definition: rel.h:133
TransactionId TransactionXmin
Definition: snapmgr.c:164
bool unique
Definition: relation.h:789
HeapTupleHeader t_data
Definition: htup.h:68
Definition: type.h:89
BlockNumber pages
Definition: relation.h:758
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:783
Form_pg_index rd_index
Definition: rel.h:131
RelOptInfo * rel
Definition: relation.h:755
bool amoptionalkey
Definition: relation.h:795
amgetbitmap_function amgetbitmap
Definition: amapi.h:220
Oid * rd_indcollation
Definition: rel.h:165
#define ERROR
Definition: elog.h:43
amcostestimate_function amcostestimate
Definition: amapi.h:213
#define NoLock
Definition: lockdefs.h:34
bool amcanorderbyop
Definition: relation.h:794
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4546
PlannerGlobal * glob
Definition: relation.h:171
#define RowExclusiveLock
Definition: lockdefs.h:38
struct FdwRoutine * fdwroutine
Definition: relation.h:663
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:1900
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:59
Oid * rd_opfamily
Definition: rel.h:154
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:939
void(* amcostestimate)()
Definition: relation.h:802
int ncolumns
Definition: relation.h:763
#define ereport(elevel, rest)
Definition: elog.h:122
bool amhasgetbitmap
Definition: relation.h:799
bool amcanparallel
Definition: amapi.h:194
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
Index relid
Definition: relation.h:640
Bitmapset * Relids
Definition: relation.h:29
Oid serverid
Definition: relation.h:659
FormData_pg_index * Form_pg_index
Definition: pg_index.h:66
bool amsearchnulls
Definition: amapi.h:186
List * indrestrictinfo
Definition: relation.h:782
void * palloc0(Size size)
Definition: mcxt.c:955
int rel_parallel_workers
Definition: relation.h:656
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
unsigned int Index
Definition: c.h:442
List * indexlist
Definition: relation.h:649
bool amsearcharray
Definition: amapi.h:184
bool amhasgettuple
Definition: relation.h:798
#define InvalidOid
Definition: postgres_ext.h:36
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:565
BlockNumber pages
Definition: relation.h:651
#define Assert(condition)
Definition: c.h:699
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:476
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:312
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:796
bool amcanorder
Definition: amapi.h:172
int nkeycolumns
Definition: relation.h:764
#define RelationNeedsWAL(relation)
Definition: rel.h:510
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4190
Oid * opcintype
Definition: relation.h:769
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
Oid * opfamily
Definition: relation.h:768
AttrNumber max_attr
Definition: relation.h:644
void * palloc(Size size)
Definition: mcxt.c:924
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:317
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1678
int * indexkeys
Definition: relation.h:765
Oid indexoid
Definition: relation.h:753
bool * canreturn
Definition: relation.h:773
bool amsearchnulls
Definition: relation.h:797
Oid * rd_opcintype
Definition: rel.h:155
bool * nulls_first
Definition: relation.h:772
bool * reverse_sort
Definition: relation.h:771
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:778
int32 * attr_widths
Definition: relation.h:646
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:407
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:150
bool amcanparallel
Definition: relation.h:800
#define lfirst_oid(lc)
Definition: pg_list.h:108
List * indexprs
Definition: relation.h:777
bool transientPlan
Definition: relation.h:139
AttrNumber min_attr
Definition: relation.h:643

◆ has_row_triggers()

bool has_row_triggers ( PlannerInfo root,
Index  rti,
CmdType  event 
)

Definition at line 1854 of file plancat.c.

References CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ERROR, heap_close, heap_open(), NoLock, planner_rt_fetch, RangeTblEntry::relid, 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().

1855 {
1856  RangeTblEntry *rte = planner_rt_fetch(rti, root);
1857  Relation relation;
1858  TriggerDesc *trigDesc;
1859  bool result = false;
1860 
1861  /* Assume we already have adequate lock */
1862  relation = heap_open(rte->relid, NoLock);
1863 
1864  trigDesc = relation->trigdesc;
1865  switch (event)
1866  {
1867  case CMD_INSERT:
1868  if (trigDesc &&
1869  (trigDesc->trig_insert_after_row ||
1870  trigDesc->trig_insert_before_row))
1871  result = true;
1872  break;
1873  case CMD_UPDATE:
1874  if (trigDesc &&
1875  (trigDesc->trig_update_after_row ||
1876  trigDesc->trig_update_before_row))
1877  result = true;
1878  break;
1879  case CMD_DELETE:
1880  if (trigDesc &&
1881  (trigDesc->trig_delete_after_row ||
1882  trigDesc->trig_delete_before_row))
1883  result = true;
1884  break;
1885  default:
1886  elog(ERROR, "unrecognized CmdType: %d", (int) event);
1887  break;
1888  }
1889 
1890  heap_close(relation, NoLock);
1891  return result;
1892 }
#define heap_close(r, l)
Definition: heapam.h:97
#define planner_rt_fetch(rti, root)
Definition: relation.h:344
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:90
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:1294
#define elog
Definition: elog.h:219
bool trig_delete_before_row
Definition: reltrigger.h:65

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 1822 of file plancat.c.

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

Referenced by examine_variable().

1823 {
1824  ListCell *ilist;
1825 
1826  foreach(ilist, rel->indexlist)
1827  {
1828  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1829 
1830  /*
1831  * Note: ignore partial indexes, since they don't allow us to conclude
1832  * that all attr values are distinct, *unless* they are marked predOK
1833  * which means we know the index's predicate is satisfied by the
1834  * query. We don't take any interest in expressional indexes either.
1835  * Also, a multicolumn unique index doesn't allow us to conclude that
1836  * just the specified attr is unique.
1837  */
1838  if (index->unique &&
1839  index->nkeycolumns == 1 &&
1840  index->indexkeys[0] == attno &&
1841  (index->indpred == NIL || index->predOK))
1842  return true;
1843  }
1844  return false;
1845 }
#define NIL
Definition: pg_list.h:69
bool predOK
Definition: relation.h:788
bool unique
Definition: relation.h:789
Definition: type.h:89
List * indexlist
Definition: relation.h:649
#define lfirst(lc)
Definition: pg_list.h:106
int nkeycolumns
Definition: relation.h:764
int * indexkeys
Definition: relation.h:765
List * indpred
Definition: relation.h:778

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

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

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

◆ join_selectivity()

Selectivity join_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1778 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1784 {
1785  RegProcedure oprjoin = get_oprjoin(operatorid);
1786  float8 result;
1787 
1788  /*
1789  * if the oprjoin procedure is missing for whatever reason, use a
1790  * selectivity of 0.5
1791  */
1792  if (!oprjoin)
1793  return (Selectivity) 0.5;
1794 
1795  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1796  inputcollid,
1797  PointerGetDatum(root),
1798  ObjectIdGetDatum(operatorid),
1799  PointerGetDatum(args),
1800  Int16GetDatum(jointype),
1801  PointerGetDatum(sjinfo)));
1802 
1803  if (result < 0.0 || result > 1.0)
1804  elog(ERROR, "invalid join selectivity: %f", result);
1805 
1806  return (Selectivity) result;
1807 }
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1370
#define PointerGetDatum(X)
Definition: postgres.h:541
regproc RegProcedure
Definition: c.h:472
#define Int16GetDatum(X)
Definition: postgres.h:436
double Selectivity
Definition: nodes.h:647
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:458
#define DatumGetFloat8(X)
Definition: postgres.h:713
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1511
#define elog
Definition: elog.h:219

◆ relation_excluded_by_constraints()

bool relation_excluded_by_constraints ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)

Definition at line 1387 of file plancat.c.

References Assert, RelOptInfo::baserestrictinfo, RestrictInfo::clause, constraint_exclusion, CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_ON, CONSTRAINT_EXCLUSION_PARTITION, contain_mutable_functions(), DatumGetBool, get_relation_constraints(), RangeTblEntry::inh, INHKIND_NONE, INHKIND_PARTITIONED, PlannerInfo::inhTargetKind, IS_SIMPLE_REL, IsA, lappend(), lfirst, linitial, list_length(), NIL, PlannerInfo::parse, predicate_refuted_by(), RelOptInfo::relid, RangeTblEntry::relid, RangeTblEntry::relkind, 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().

1389 {
1390  List *safe_restrictions;
1391  List *constraint_pred;
1392  List *safe_constraints;
1393  ListCell *lc;
1394 
1395  /* As of now, constraint exclusion works only with simple relations. */
1396  Assert(IS_SIMPLE_REL(rel));
1397 
1398  /*
1399  * Regardless of the setting of constraint_exclusion, detect
1400  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1401  * reduce "anything AND FALSE" to just "FALSE", any such case should
1402  * result in exactly one baserestrictinfo entry. This doesn't fire very
1403  * often, but it seems cheap enough to be worth doing anyway. (Without
1404  * this, we'd miss some optimizations that 9.5 and earlier found via much
1405  * more roundabout methods.)
1406  */
1407  if (list_length(rel->baserestrictinfo) == 1)
1408  {
1410  Expr *clause = rinfo->clause;
1411 
1412  if (clause && IsA(clause, Const) &&
1413  (((Const *) clause)->constisnull ||
1414  !DatumGetBool(((Const *) clause)->constvalue)))
1415  return true;
1416  }
1417 
1418  /*
1419  * Skip further tests, depending on constraint_exclusion.
1420  */
1421  switch (constraint_exclusion)
1422  {
1424 
1425  /*
1426  * Don't prune if feature turned off -- except if the relation is
1427  * a partition. While partprune.c-style partition pruning is not
1428  * yet in use for all cases (update/delete is not handled), it
1429  * would be a UI horror to use different user-visible controls
1430  * depending on such a volatile implementation detail. Therefore,
1431  * for partitioned tables we use enable_partition_pruning to
1432  * control this behavior.
1433  */
1434  if (root->inhTargetKind == INHKIND_PARTITIONED)
1435  break;
1436  return false;
1437 
1439 
1440  /*
1441  * When constraint_exclusion is set to 'partition' we only handle
1442  * OTHER_MEMBER_RELs, or BASERELs in cases where the result target
1443  * is an inheritance parent or a partitioned table.
1444  */
1445  if ((rel->reloptkind != RELOPT_OTHER_MEMBER_REL) &&
1446  !(rel->reloptkind == RELOPT_BASEREL &&
1447  root->inhTargetKind != INHKIND_NONE &&
1448  rel->relid == root->parse->resultRelation))
1449  return false;
1450  break;
1451 
1453  break; /* always try to exclude */
1454  }
1455 
1456  /*
1457  * Check for self-contradictory restriction clauses. We dare not make
1458  * deductions with non-immutable functions, but any immutable clauses that
1459  * are self-contradictory allow us to conclude the scan is unnecessary.
1460  *
1461  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1462  * expecting to see any in its predicate argument.
1463  */
1464  safe_restrictions = NIL;
1465  foreach(lc, rel->baserestrictinfo)
1466  {
1467  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1468 
1469  if (!contain_mutable_functions((Node *) rinfo->clause))
1470  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1471  }
1472 
1473  /*
1474  * We can use weak refutation here, since we're comparing restriction
1475  * clauses with restriction clauses.
1476  */
1477  if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1478  return true;
1479 
1480  /*
1481  * Only plain relations have constraints. In a partitioning hierarchy,
1482  * but not with regular table inheritance, it's OK to assume that any
1483  * constraints that hold for the parent also hold for every child; for
1484  * instance, table inheritance allows the parent to have constraints
1485  * marked NO INHERIT, but table partitioning does not. We choose to check
1486  * whether the partitioning parents can be excluded here; doing so
1487  * consumes some cycles, but potentially saves us the work of excluding
1488  * each child individually.
1489  */
1490  if (rte->rtekind != RTE_RELATION ||
1491  (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE))
1492  return false;
1493 
1494  /*
1495  * OK to fetch the constraint expressions. Include "col IS NOT NULL"
1496  * expressions for attnotnull columns, in case we can refute those.
1497  */
1498  constraint_pred = get_relation_constraints(root, rte->relid, rel, true);
1499 
1500  /*
1501  * We do not currently enforce that CHECK constraints contain only
1502  * immutable functions, so it's necessary to check here. We daren't draw
1503  * conclusions from plan-time evaluation of non-immutable functions. Since
1504  * they're ANDed, we can just ignore any mutable constraints in the list,
1505  * and reason about the rest.
1506  */
1507  safe_constraints = NIL;
1508  foreach(lc, constraint_pred)
1509  {
1510  Node *pred = (Node *) lfirst(lc);
1511 
1512  if (!contain_mutable_functions(pred))
1513  safe_constraints = lappend(safe_constraints, pred);
1514  }
1515 
1516  /*
1517  * The constraints are effectively ANDed together, so we can just try to
1518  * refute the entire collection at once. This may allow us to make proofs
1519  * that would fail if we took them individually.
1520  *
1521  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1522  * an obvious optimization. Some of the clauses might be OR clauses that
1523  * have volatile and nonvolatile subclauses, and it's OK to make
1524  * deductions with the nonvolatile parts.
1525  *
1526  * We need strong refutation because we have to prove that the constraints
1527  * would yield false, not just NULL.
1528  */
1529  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1530  return true;
1531 
1532  return false;
1533 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Query * parse
Definition: relation.h:169
RelOptKind reloptkind
Definition: relation.h:609
List * baserestrictinfo
Definition: relation.h:672
int constraint_exclusion
Definition: plancat.c:56
int resultRelation
Definition: parsenodes.h:122
Definition: nodes.h:517
#define IS_SIMPLE_REL(rel)
Definition: relation.h:585
#define linitial(l)
Definition: pg_list.h:111
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:219
#define DatumGetBool(X)
Definition: postgres.h:378
Index relid
Definition: relation.h:640
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1880
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
InheritanceKind inhTargetKind
Definition: relation.h:312
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:962
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:879
Definition: pg_list.h:45
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
Definition: plancat.c:1175

◆ restriction_selectivity()

Selectivity restriction_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
int  varRelid 
)

Definition at line 1741 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1746 {
1747  RegProcedure oprrest = get_oprrest(operatorid);
1748  float8 result;
1749 
1750  /*
1751  * if the oprrest procedure is missing for whatever reason, use a
1752  * selectivity of 0.5
1753  */
1754  if (!oprrest)
1755  return (Selectivity) 0.5;
1756 
1757  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1758  inputcollid,
1759  PointerGetDatum(root),
1760  ObjectIdGetDatum(operatorid),
1761  PointerGetDatum(args),
1762  Int32GetDatum(varRelid)));
1763 
1764  if (result < 0.0 || result > 1.0)
1765  elog(ERROR, "invalid restriction selectivity: %f", result);
1766 
1767  return (Selectivity) result;
1768 }
#define PointerGetDatum(X)
Definition: postgres.h:541
regproc RegProcedure
Definition: c.h:472
double Selectivity
Definition: nodes.h:647
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:458
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1346
#define DatumGetFloat8(X)
Definition: postgres.h:713
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1481
#define Int32GetDatum(X)
Definition: postgres.h:464
#define elog
Definition: elog.h:219

Variable Documentation

◆ get_relation_info_hook

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook

Definition at line 59 of file plancat.c.

Referenced by get_relation_info().