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 1388 of file plancat.c.

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

Referenced by create_scan_plan().

1389 {
1390  List *tlist = NIL;
1391  Index varno = rel->relid;
1392  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1393  Relation relation;
1394  Query *subquery;
1395  Var *var;
1396  ListCell *l;
1397  int attrno,
1398  numattrs;
1399  List *colvars;
1400 
1401  switch (rte->rtekind)
1402  {
1403  case RTE_RELATION:
1404  /* Assume we already have adequate lock */
1405  relation = heap_open(rte->relid, NoLock);
1406 
1407  numattrs = RelationGetNumberOfAttributes(relation);
1408  for (attrno = 1; attrno <= numattrs; attrno++)
1409  {
1410  Form_pg_attribute att_tup = relation->rd_att->attrs[attrno - 1];
1411 
1412  if (att_tup->attisdropped)
1413  {
1414  /* found a dropped col, so punt */
1415  tlist = NIL;
1416  break;
1417  }
1418 
1419  var = makeVar(varno,
1420  attrno,
1421  att_tup->atttypid,
1422  att_tup->atttypmod,
1423  att_tup->attcollation,
1424  0);
1425 
1426  tlist = lappend(tlist,
1427  makeTargetEntry((Expr *) var,
1428  attrno,
1429  NULL,
1430  false));
1431  }
1432 
1433  heap_close(relation, NoLock);
1434  break;
1435 
1436  case RTE_SUBQUERY:
1437  subquery = rte->subquery;
1438  foreach(l, subquery->targetList)
1439  {
1440  TargetEntry *tle = (TargetEntry *) lfirst(l);
1441 
1442  /*
1443  * A resjunk column of the subquery can be reflected as
1444  * resjunk in the physical tlist; we need not punt.
1445  */
1446  var = makeVarFromTargetEntry(varno, tle);
1447 
1448  tlist = lappend(tlist,
1449  makeTargetEntry((Expr *) var,
1450  tle->resno,
1451  NULL,
1452  tle->resjunk));
1453  }
1454  break;
1455 
1456  case RTE_FUNCTION:
1457  case RTE_VALUES:
1458  case RTE_CTE:
1459  /* Not all of these can have dropped cols, but share code anyway */
1460  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1461  NULL, &colvars);
1462  foreach(l, colvars)
1463  {
1464  var = (Var *) lfirst(l);
1465 
1466  /*
1467  * A non-Var in expandRTE's output means a dropped column;
1468  * must punt.
1469  */
1470  if (!IsA(var, Var))
1471  {
1472  tlist = NIL;
1473  break;
1474  }
1475 
1476  tlist = lappend(tlist,
1477  makeTargetEntry((Expr *) var,
1478  var->varattno,
1479  NULL,
1480  false));
1481  }
1482  break;
1483 
1484  default:
1485  /* caller error */
1486  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1487  (int) rte->rtekind);
1488  break;
1489  }
1490 
1491  return tlist;
1492 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:419
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:104
AttrNumber varattno
Definition: primnodes.h:146
#define heap_close(r, l)
Definition: heapam.h:97
Definition: primnodes.h:141
List * targetList
Definition: parsenodes.h:131
bool resjunk
Definition: primnodes.h:1337
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
AttrNumber resno
Definition: primnodes.h:1331
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:518
List * lappend(List *list, void *datum)
Definition: list.c:128
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
unsigned int Index
Definition: c.h:361
TupleDesc rd_att
Definition: rel.h:114
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:882
Query * subquery
Definition: parsenodes.h:900
#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 901 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().

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

1104 {
1105  int32 result;
1106  Relation relation;
1107 
1108  /* As above, assume relation is already locked */
1109  relation = heap_open(relid, NoLock);
1110 
1111  result = get_rel_data_width(relation, attr_widths);
1112 
1113  heap_close(relation, NoLock);
1114 
1115  return result;
1116 }
#define heap_close(r, l)
Definition: heapam.h:97
signed int int32
Definition: c.h:253
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1061
#define NoLock
Definition: lockdefs.h:34
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
void get_relation_info ( PlannerInfo root,
Oid  relationObjectId,
bool  inhparent,
RelOptInfo rel 
)

Definition at line 96 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, 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, HeapTupleData::t_data, TransactionIdPrecedes(), TransactionXmin, PlannerGlobal::transientPlan, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by build_simple_rel().

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

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

1682 {
1683  RangeTblEntry *rte = planner_rt_fetch(rti, root);
1684  Relation relation;
1685  TriggerDesc *trigDesc;
1686  bool result = false;
1687 
1688  /* Assume we already have adequate lock */
1689  relation = heap_open(rte->relid, NoLock);
1690 
1691  trigDesc = relation->trigdesc;
1692  switch (event)
1693  {
1694  case CMD_INSERT:
1695  if (trigDesc &&
1696  (trigDesc->trig_insert_after_row ||
1697  trigDesc->trig_insert_before_row))
1698  result = true;
1699  break;
1700  case CMD_UPDATE:
1701  if (trigDesc &&
1702  (trigDesc->trig_update_after_row ||
1703  trigDesc->trig_update_before_row))
1704  result = true;
1705  break;
1706  case CMD_DELETE:
1707  if (trigDesc &&
1708  (trigDesc->trig_delete_after_row ||
1709  trigDesc->trig_delete_before_row))
1710  result = true;
1711  break;
1712  default:
1713  elog(ERROR, "unrecognized CmdType: %d", (int) event);
1714  break;
1715  }
1716 
1717  heap_close(relation, NoLock);
1718  return result;
1719 }
#define heap_close(r, l)
Definition: heapam.h:97
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:119
bool trig_delete_after_row
Definition: reltrigger.h:66
#define NoLock
Definition: lockdefs.h:34
bool trig_update_before_row
Definition: reltrigger.h:60
bool trig_insert_after_row
Definition: reltrigger.h:56
bool trig_update_after_row
Definition: reltrigger.h:61
bool trig_insert_before_row
Definition: reltrigger.h:55
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define elog
Definition: elog.h:219
bool trig_delete_before_row
Definition: reltrigger.h:65
bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 1649 of file plancat.c.

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

Referenced by examine_variable().

1650 {
1651  ListCell *ilist;
1652 
1653  foreach(ilist, rel->indexlist)
1654  {
1655  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1656 
1657  /*
1658  * Note: ignore partial indexes, since they don't allow us to conclude
1659  * that all attr values are distinct, *unless* they are marked predOK
1660  * which means we know the index's predicate is satisfied by the
1661  * query. We don't take any interest in expressional indexes either.
1662  * Also, a multicolumn unique index doesn't allow us to conclude that
1663  * just the specified attr is unique.
1664  */
1665  if (index->unique &&
1666  index->ncolumns == 1 &&
1667  index->indexkeys[0] == attno &&
1668  (index->indpred == NIL || index->predOK))
1669  return true;
1670  }
1671  return false;
1672 }
#define NIL
Definition: pg_list.h:69
bool predOK
Definition: relation.h:620
bool unique
Definition: relation.h:621
Definition: type.h:90
int ncolumns
Definition: relation.h:598
List * indexlist
Definition: relation.h:527
#define lfirst(lc)
Definition: pg_list.h:106
int * indexkeys
Definition: relation.h:599
List * indpred
Definition: relation.h:611
List* infer_arbiter_indexes ( PlannerInfo root)

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

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

Definition at line 1605 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1611 {
1612  RegProcedure oprjoin = get_oprjoin(operatorid);
1613  float8 result;
1614 
1615  /*
1616  * if the oprjoin procedure is missing for whatever reason, use a
1617  * selectivity of 0.5
1618  */
1619  if (!oprjoin)
1620  return (Selectivity) 0.5;
1621 
1622  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1623  inputcollid,
1624  PointerGetDatum(root),
1625  ObjectIdGetDatum(operatorid),
1626  PointerGetDatum(args),
1627  Int16GetDatum(jointype),
1628  PointerGetDatum(sjinfo)));
1629 
1630  if (result < 0.0 || result > 1.0)
1631  elog(ERROR, "invalid join selectivity: %f", result);
1632 
1633  return (Selectivity) result;
1634 }
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1353
#define PointerGetDatum(X)
Definition: postgres.h:564
regproc RegProcedure
Definition: c.h:391
#define Int16GetDatum(X)
Definition: postgres.h:459
double Selectivity
Definition: nodes.h:631
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:377
#define DatumGetFloat8(X)
Definition: postgres.h:736
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1684
#define elog
Definition: elog.h:219
bool relation_excluded_by_constraints ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)

Definition at line 1267 of file plancat.c.

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

Referenced by set_append_rel_size(), and set_rel_size().

1269 {
1270  List *safe_restrictions;
1271  List *constraint_pred;
1272  List *safe_constraints;
1273  ListCell *lc;
1274 
1275  /*
1276  * Regardless of the setting of constraint_exclusion, detect
1277  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1278  * reduce "anything AND FALSE" to just "FALSE", any such case should
1279  * result in exactly one baserestrictinfo entry. This doesn't fire very
1280  * often, but it seems cheap enough to be worth doing anyway. (Without
1281  * this, we'd miss some optimizations that 9.5 and earlier found via much
1282  * more roundabout methods.)
1283  */
1284  if (list_length(rel->baserestrictinfo) == 1)
1285  {
1287  Expr *clause = rinfo->clause;
1288 
1289  if (clause && IsA(clause, Const) &&
1290  (((Const *) clause)->constisnull ||
1291  !DatumGetBool(((Const *) clause)->constvalue)))
1292  return true;
1293  }
1294 
1295  /* Skip further tests if constraint exclusion is disabled for the rel */
1298  !(rel->reloptkind == RELOPT_OTHER_MEMBER_REL ||
1299  (root->hasInheritedTarget &&
1300  rel->reloptkind == RELOPT_BASEREL &&
1301  rel->relid == root->parse->resultRelation))))
1302  return false;
1303 
1304  /*
1305  * Check for self-contradictory restriction clauses. We dare not make
1306  * deductions with non-immutable functions, but any immutable clauses that
1307  * are self-contradictory allow us to conclude the scan is unnecessary.
1308  *
1309  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1310  * expecting to see any in its predicate argument.
1311  */
1312  safe_restrictions = NIL;
1313  foreach(lc, rel->baserestrictinfo)
1314  {
1315  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1316 
1317  if (!contain_mutable_functions((Node *) rinfo->clause))
1318  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1319  }
1320 
1321  if (predicate_refuted_by(safe_restrictions, safe_restrictions))
1322  return true;
1323 
1324  /* Only plain relations have constraints */
1325  if (rte->rtekind != RTE_RELATION || rte->inh)
1326  return false;
1327 
1328  /*
1329  * OK to fetch the constraint expressions. Include "col IS NOT NULL"
1330  * expressions for attnotnull columns, in case we can refute those.
1331  */
1332  constraint_pred = get_relation_constraints(root, rte->relid, rel, true);
1333 
1334  /*
1335  * We do not currently enforce that CHECK constraints contain only
1336  * immutable functions, so it's necessary to check here. We daren't draw
1337  * conclusions from plan-time evaluation of non-immutable functions. Since
1338  * they're ANDed, we can just ignore any mutable constraints in the list,
1339  * and reason about the rest.
1340  */
1341  safe_constraints = NIL;
1342  foreach(lc, constraint_pred)
1343  {
1344  Node *pred = (Node *) lfirst(lc);
1345 
1346  if (!contain_mutable_functions(pred))
1347  safe_constraints = lappend(safe_constraints, pred);
1348  }
1349 
1350  /*
1351  * The constraints are effectively ANDed together, so we can just try to
1352  * refute the entire collection at once. This may allow us to make proofs
1353  * that would fail if we took them individually.
1354  *
1355  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1356  * an obvious optimization. Some of the clauses might be OR clauses that
1357  * have volatile and nonvolatile subclauses, and it's OK to make
1358  * deductions with the nonvolatile parts.
1359  */
1360  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo))
1361  return true;
1362 
1363  return false;
1364 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Query * parse
Definition: relation.h:152
RelOptKind reloptkind
Definition: relation.h:487
List * baserestrictinfo
Definition: relation.h:544
int constraint_exclusion
Definition: plancat.c:50
int resultRelation
Definition: parsenodes.h:113
Definition: nodes.h:508
#define linitial(l)
Definition: pg_list.h:110
#define DatumGetBool(X)
Definition: postgres.h:401
Index relid
Definition: relation.h:518
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1637
#define lfirst(lc)
Definition: pg_list.h:106
bool hasInheritedTarget
Definition: relation.h:292
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:882
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:877
bool predicate_refuted_by(List *predicate_list, List *restrictinfo_list)
Definition: predtest.c:186
Definition: pg_list.h:45
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
Definition: plancat.c:1137
Selectivity restriction_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
int  varRelid 
)

Definition at line 1568 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1573 {
1574  RegProcedure oprrest = get_oprrest(operatorid);
1575  float8 result;
1576 
1577  /*
1578  * if the oprrest procedure is missing for whatever reason, use a
1579  * selectivity of 0.5
1580  */
1581  if (!oprrest)
1582  return (Selectivity) 0.5;
1583 
1584  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1585  inputcollid,
1586  PointerGetDatum(root),
1587  ObjectIdGetDatum(operatorid),
1588  PointerGetDatum(args),
1589  Int32GetDatum(varRelid)));
1590 
1591  if (result < 0.0 || result > 1.0)
1592  elog(ERROR, "invalid restriction selectivity: %f", result);
1593 
1594  return (Selectivity) result;
1595 }
#define PointerGetDatum(X)
Definition: postgres.h:564
regproc RegProcedure
Definition: c.h:391
double Selectivity
Definition: nodes.h:631
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:377
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1329
#define DatumGetFloat8(X)
Definition: postgres.h:736
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1654
#define Int32GetDatum(X)
Definition: postgres.h:487
#define elog
Definition: elog.h:219

Variable Documentation

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook

Definition at line 53 of file plancat.c.

Referenced by get_relation_info().