PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
plancat.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_statistic_ext.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/plancat.h"
#include "optimizer/predtest.h"
#include "optimizer/prep.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
Include dependency graph for plancat.c:

Go to the source code of this file.

Functions

static void get_relation_foreign_keys (PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
 
static bool infer_collation_opclass_match (InferenceElem *elem, Relation idxRel, List *idxExprs)
 
static int32 get_rel_data_width (Relation rel, int32 *attr_widths)
 
static Listget_relation_constraints (PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
 
static Listbuild_index_tlist (PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
 
static Listget_relation_statistics (RelOptInfo *rel, Relation relation)
 
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)
 
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_unique_index (RelOptInfo *rel, AttrNumber attno)
 
bool has_row_triggers (PlannerInfo *root, Index rti, CmdType event)
 

Variables

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION
 
get_relation_info_hook_type get_relation_info_hook = NULL
 

Function Documentation

static List * build_index_tlist ( PlannerInfo root,
IndexOptInfo index,
Relation  heapRelation 
)
static

Definition at line 1572 of file plancat.c.

References tupleDesc::attrs, elog, ERROR, i, IndexOptInfo::indexkeys, IndexOptInfo::indexprs, lappend(), lfirst, list_head(), lnext, makeTargetEntry(), makeVar(), IndexOptInfo::ncolumns, NIL, NULL, RelationData::rd_att, RelationData::rd_rel, IndexOptInfo::rel, RelOptInfo::relid, and SystemAttributeDefinition().

Referenced by get_relation_info().

1574 {
1575  List *tlist = NIL;
1576  Index varno = index->rel->relid;
1577  ListCell *indexpr_item;
1578  int i;
1579 
1580  indexpr_item = list_head(index->indexprs);
1581  for (i = 0; i < index->ncolumns; i++)
1582  {
1583  int indexkey = index->indexkeys[i];
1584  Expr *indexvar;
1585 
1586  if (indexkey != 0)
1587  {
1588  /* simple column */
1589  Form_pg_attribute att_tup;
1590 
1591  if (indexkey < 0)
1592  att_tup = SystemAttributeDefinition(indexkey,
1593  heapRelation->rd_rel->relhasoids);
1594  else
1595  att_tup = heapRelation->rd_att->attrs[indexkey - 1];
1596 
1597  indexvar = (Expr *) makeVar(varno,
1598  indexkey,
1599  att_tup->atttypid,
1600  att_tup->atttypmod,
1601  att_tup->attcollation,
1602  0);
1603  }
1604  else
1605  {
1606  /* expression column */
1607  if (indexpr_item == NULL)
1608  elog(ERROR, "wrong number of index expressions");
1609  indexvar = (Expr *) lfirst(indexpr_item);
1610  indexpr_item = lnext(indexpr_item);
1611  }
1612 
1613  tlist = lappend(tlist,
1614  makeTargetEntry(indexvar,
1615  i + 1,
1616  NULL,
1617  false));
1618  }
1619  if (indexpr_item != NULL)
1620  elog(ERROR, "wrong number of index expressions");
1621 
1622  return tlist;
1623 }
#define NIL
Definition: pg_list.h:69
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Form_pg_class rd_rel
Definition: rel.h:114
RelOptInfo * rel
Definition: relation.h:595
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
int ncolumns
Definition: relation.h:603
#define lnext(lc)
Definition: pg_list.h:105
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:522
List * lappend(List *list, void *datum)
Definition: list.c:128
unsigned int Index
Definition: c.h:365
TupleDesc rd_att
Definition: rel.h:115
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
int i
int * indexkeys
Definition: relation.h:604
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List * indexprs
Definition: relation.h:615
List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1454 of file plancat.c.

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

Referenced by create_scan_plan().

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

Definition at line 907 of file plancat.c.

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

Referenced by get_relation_info(), and hashbuild().

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

Definition at line 1067 of file plancat.c.

References Assert, tupleDesc::attrs, get_attavgwidth(), get_typavgwidth(), i, NULL, RelationData::rd_att, RelationGetNumberOfAttributes, and RelationGetRelid.

Referenced by estimate_rel_size(), and get_relation_data_width().

1068 {
1069  int32 tuple_width = 0;
1070  int i;
1071 
1072  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1073  {
1074  Form_pg_attribute att = rel->rd_att->attrs[i - 1];
1075  int32 item_width;
1076 
1077  if (att->attisdropped)
1078  continue;
1079 
1080  /* use previously cached data, if any */
1081  if (attr_widths != NULL && attr_widths[i] > 0)
1082  {
1083  tuple_width += attr_widths[i];
1084  continue;
1085  }
1086 
1087  /* This should match set_rel_width() in costsize.c */
1088  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1089  if (item_width <= 0)
1090  {
1091  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1092  Assert(item_width > 0);
1093  }
1094  if (attr_widths != NULL)
1095  attr_widths[i] = item_width;
1096  tuple_width += item_width;
1097  }
1098 
1099  return tuple_width;
1100 }
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:423
Form_pg_attribute * attrs
Definition: tupdesc.h:74
signed int int32
Definition: c.h:256
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
TupleDesc rd_att
Definition: rel.h:115
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2296
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int i
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:2796
#define RelationGetRelid(relation)
Definition: rel.h:417
static List * get_relation_constraints ( PlannerInfo root,
Oid  relationObjectId,
RelOptInfo rel,
bool  include_notnull 
)
static

Definition at line 1143 of file plancat.c.

References NullTest::arg, NullTest::argisrow, tupleDesc::attrs, canonicalize_qual(), constrCheck::ccbin, constrCheck::ccvalid, ChangeVarNodes(), tupleConstr::check, tupleDesc::constr, eval_const_expressions(), tupleConstr::has_not_null, heap_close, heap_open(), i, IS_NOT_NULL, lappend(), list_concat(), NullTest::location, make_ands_implicit(), makeNode, makeVar(), tupleDesc::natts, NIL, NoLock, NULL, NullTest::nulltesttype, tupleConstr::num_check, RelationData::rd_att, RelationGetPartitionQual(), RelOptInfo::relid, result, and stringToNode().

Referenced by relation_excluded_by_constraints().

1146 {
1147  List *result = NIL;
1148  Index varno = rel->relid;
1149  Relation relation;
1150  TupleConstr *constr;
1151  List *pcqual;
1152 
1153  /*
1154  * We assume the relation has already been safely locked.
1155  */
1156  relation = heap_open(relationObjectId, NoLock);
1157 
1158  constr = relation->rd_att->constr;
1159  if (constr != NULL)
1160  {
1161  int num_check = constr->num_check;
1162  int i;
1163 
1164  for (i = 0; i < num_check; i++)
1165  {
1166  Node *cexpr;
1167 
1168  /*
1169  * If this constraint hasn't been fully validated yet, we must
1170  * ignore it here.
1171  */
1172  if (!constr->check[i].ccvalid)
1173  continue;
1174 
1175  cexpr = stringToNode(constr->check[i].ccbin);
1176 
1177  /*
1178  * Run each expression through const-simplification and
1179  * canonicalization. This is not just an optimization, but is
1180  * necessary, because we will be comparing it to
1181  * similarly-processed qual clauses, and may fail to detect valid
1182  * matches without this. This must match the processing done to
1183  * qual clauses in preprocess_expression()! (We can skip the
1184  * stuff involving subqueries, however, since we don't allow any
1185  * in check constraints.)
1186  */
1187  cexpr = eval_const_expressions(root, cexpr);
1188 
1189  cexpr = (Node *) canonicalize_qual((Expr *) cexpr);
1190 
1191  /* Fix Vars to have the desired varno */
1192  if (varno != 1)
1193  ChangeVarNodes(cexpr, 1, varno, 0);
1194 
1195  /*
1196  * Finally, convert to implicit-AND format (that is, a List) and
1197  * append the resulting item(s) to our output list.
1198  */
1199  result = list_concat(result,
1200  make_ands_implicit((Expr *) cexpr));
1201  }
1202 
1203  /* Add NOT NULL constraints in expression form, if requested */
1204  if (include_notnull && constr->has_not_null)
1205  {
1206  int natts = relation->rd_att->natts;
1207 
1208  for (i = 1; i <= natts; i++)
1209  {
1210  Form_pg_attribute att = relation->rd_att->attrs[i - 1];
1211 
1212  if (att->attnotnull && !att->attisdropped)
1213  {
1214  NullTest *ntest = makeNode(NullTest);
1215 
1216  ntest->arg = (Expr *) makeVar(varno,
1217  i,
1218  att->atttypid,
1219  att->atttypmod,
1220  att->attcollation,
1221  0);
1222  ntest->nulltesttype = IS_NOT_NULL;
1223 
1224  /*
1225  * argisrow=false is correct even for a composite column,
1226  * because attnotnull does not represent a SQL-spec IS NOT
1227  * NULL test in such a case, just IS DISTINCT FROM NULL.
1228  */
1229  ntest->argisrow = false;
1230  ntest->location = -1;
1231  result = lappend(result, ntest);
1232  }
1233  }
1234  }
1235  }
1236 
1237  /* Append partition predicates, if any */
1238  pcqual = RelationGetPartitionQual(relation);
1239  if (pcqual)
1240  {
1241  /*
1242  * Run each expression through const-simplification and
1243  * canonicalization similar to check constraints.
1244  */
1245  pcqual = (List *) eval_const_expressions(root, (Node *) pcqual);
1246  pcqual = (List *) canonicalize_qual((Expr *) pcqual);
1247 
1248  /* Fix Vars to have the desired varno */
1249  if (varno != 1)
1250  ChangeVarNodes((Node *) pcqual, 1, varno, 0);
1251 
1252  result = list_concat(result, pcqual);
1253  }
1254 
1255  heap_close(relation, NoLock);
1256 
1257  return result;
1258 }
#define NIL
Definition: pg_list.h:69
void * stringToNode(char *str)
Definition: read.c:38
ConstrCheck * check
Definition: tupdesc.h:40
char * ccbin
Definition: tupdesc.h:31
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Definition: nodes.h:522
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2366
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
int natts
Definition: tupdesc.h:73
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
Expr * arg
Definition: primnodes.h:1178
#define NoLock
Definition: lockdefs.h:34
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:522
bool has_not_null
Definition: tupdesc.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:958
Expr * canonicalize_qual(Expr *qual)
Definition: prepqual.c:286
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
unsigned int Index
Definition: c.h:365
TupleDesc rd_att
Definition: rel.h:115
NullTestType nulltesttype
Definition: primnodes.h:1179
#define makeNode(_type_)
Definition: nodes.h:570
#define NULL
Definition: c.h:229
TupleConstr * constr
Definition: tupdesc.h:76
int location
Definition: primnodes.h:1181
bool ccvalid
Definition: tupdesc.h:32
int i
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
bool argisrow
Definition: primnodes.h:1180
uint16 num_check
Definition: tupdesc.h:42
Definition: pg_list.h:45
int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1109 of file plancat.c.

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

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

Definition at line 444 of file plancat.c.

References Assert, ForeignKeyOptInfo::con_relid, ForeignKeyCacheInfo::confkey, ForeignKeyOptInfo::confkey, ForeignKeyCacheInfo::confrelid, ForeignKeyCacheInfo::conkey, ForeignKeyOptInfo::conkey, ForeignKeyCacheInfo::conpfeqop, ForeignKeyOptInfo::conpfeqop, ForeignKeyCacheInfo::conrelid, ForeignKeyOptInfo::eclass, PlannerInfo::fkey_list, RangeTblEntry::inh, lappend(), lfirst, list_length(), makeNode, ForeignKeyCacheInfo::nkeys, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_rcols, ForeignKeyOptInfo::nmatched_ri, PlannerInfo::parse, ForeignKeyOptInfo::ref_relid, RelationGetFKeyList(), RelationGetRelid, RelOptInfo::relid, RangeTblEntry::relid, RELOPT_BASEREL, RelOptInfo::reloptkind, ForeignKeyOptInfo::rinfos, Query::rtable, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by get_relation_info().

446 {
447  List *rtable = root->parse->rtable;
448  List *cachedfkeys;
449  ListCell *lc;
450 
451  /*
452  * If it's not a baserel, we don't care about its FKs. Also, if the query
453  * references only a single relation, we can skip the lookup since no FKs
454  * could satisfy the requirements below.
455  */
456  if (rel->reloptkind != RELOPT_BASEREL ||
457  list_length(rtable) < 2)
458  return;
459 
460  /*
461  * If it's the parent of an inheritance tree, ignore its FKs. We could
462  * make useful FK-based deductions if we found that all members of the
463  * inheritance tree have equivalent FK constraints, but detecting that
464  * would require code that hasn't been written.
465  */
466  if (inhparent)
467  return;
468 
469  /*
470  * Extract data about relation's FKs from the relcache. Note that this
471  * list belongs to the relcache and might disappear in a cache flush, so
472  * we must not do any further catalog access within this function.
473  */
474  cachedfkeys = RelationGetFKeyList(relation);
475 
476  /*
477  * Figure out which FKs are of interest for this query, and create
478  * ForeignKeyOptInfos for them. We want only FKs that reference some
479  * other RTE of the current query. In queries containing self-joins,
480  * there might be more than one other RTE for a referenced table, and we
481  * should make a ForeignKeyOptInfo for each occurrence.
482  *
483  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
484  * too hard to identify those here, so we might end up making some useless
485  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
486  * them again.
487  */
488  foreach(lc, cachedfkeys)
489  {
490  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
491  Index rti;
492  ListCell *lc2;
493 
494  /* conrelid should always be that of the table we're considering */
495  Assert(cachedfk->conrelid == RelationGetRelid(relation));
496 
497  /* Scan to find other RTEs matching confrelid */
498  rti = 0;
499  foreach(lc2, rtable)
500  {
501  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
502  ForeignKeyOptInfo *info;
503 
504  rti++;
505  /* Ignore if not the correct table */
506  if (rte->rtekind != RTE_RELATION ||
507  rte->relid != cachedfk->confrelid)
508  continue;
509  /* Ignore if it's an inheritance parent; doesn't really match */
510  if (rte->inh)
511  continue;
512  /* Ignore self-referential FKs; we only care about joins */
513  if (rti == rel->relid)
514  continue;
515 
516  /* OK, let's make an entry */
517  info = makeNode(ForeignKeyOptInfo);
518  info->con_relid = rel->relid;
519  info->ref_relid = rti;
520  info->nkeys = cachedfk->nkeys;
521  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
522  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
523  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
524  /* zero out fields to be filled by match_foreign_keys_to_quals */
525  info->nmatched_ec = 0;
526  info->nmatched_rcols = 0;
527  info->nmatched_ri = 0;
528  memset(info->eclass, 0, sizeof(info->eclass));
529  memset(info->rinfos, 0, sizeof(info->rinfos));
530 
531  root->fkey_list = lappend(root->fkey_list, info);
532  }
533  }
534 }
Query * parse
Definition: relation.h:154
RelOptKind reloptkind
Definition: relation.h:491
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: rel.h:243
List * fkey_list
Definition: relation.h:259
List * rtable
Definition: parsenodes.h:128
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: relation.h:660
Index relid
Definition: relation.h:522
List * lappend(List *list, void *datum)
Definition: list.c:128
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: relation.h:667
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: relation.h:658
unsigned int Index
Definition: c.h:365
#define makeNode(_type_)
Definition: nodes.h:570
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: rel.h:245
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:916
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4174
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: rel.h:244
Definition: pg_list.h:45
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: relation.h:659
#define RelationGetRelid(relation)
Definition: rel.h:417
List * rinfos[INDEX_MAX_KEYS]
Definition: relation.h:669
void get_relation_info ( PlannerInfo root,
Oid  relationObjectId,
bool  inhparent,
RelOptInfo rel 
)

Definition at line 100 of file plancat.c.

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

Referenced by build_simple_rel().

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

Definition at line 1269 of file plancat.c.

References bms_add_member(), bms_copy(), bms_free(), elog, ERROR, GETSTRUCT, i, StatisticExtInfo::keys, StatisticExtInfo::kind, lcons(), lfirst_oid, list_free(), makeNode, NIL, NULL, ObjectIdGetDatum, StatisticExtInfo::rel, RelationGetStatExtList(), ReleaseSysCache(), SearchSysCache1, statext_is_kind_built(), STATEXTOID, StatisticExtInfo::statOid, and STATS_EXT_NDISTINCT.

Referenced by get_relation_info().

1270 {
1271  List *statoidlist;
1272  List *stainfos = NIL;
1273  ListCell *l;
1274 
1275  statoidlist = RelationGetStatExtList(relation);
1276 
1277  foreach(l, statoidlist)
1278  {
1279  Oid statOid = lfirst_oid(l);
1280  Form_pg_statistic_ext staForm;
1281  HeapTuple htup;
1282  Bitmapset *keys = NULL;
1283  int i;
1284 
1285  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1286  if (!htup)
1287  elog(ERROR, "cache lookup failed for statistics %u", statOid);
1288  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1289 
1290  /*
1291  * First, build the array of columns covered. This is ultimately
1292  * wasted if no stats are actually built, but it doesn't seem worth
1293  * troubling over that case.
1294  */
1295  for (i = 0; i < staForm->stakeys.dim1; i++)
1296  keys = bms_add_member(keys, staForm->stakeys.values[i]);
1297 
1298  /* add one StatisticExtInfo for each kind built */
1300  {
1302 
1303  info->statOid = statOid;
1304  info->rel = rel;
1305  info->kind = STATS_EXT_NDISTINCT;
1306  info->keys = bms_copy(keys);
1307 
1308  stainfos = lcons(info, stainfos);
1309  }
1310 
1311  ReleaseSysCache(htup);
1312  bms_free(keys);
1313  }
1314 
1315  list_free(statoidlist);
1316 
1317  return stainfos;
1318 }
#define NIL
Definition: pg_list.h:69
#define STATS_EXT_NDISTINCT
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:110
bool statext_is_kind_built(HeapTuple htup, char type)
unsigned int Oid
Definition: postgres_ext.h:31
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:152
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
RelOptInfo * rel
Definition: relation.h:686
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1116
List * lcons(void *datum, List *list)
Definition: list.c:259
void bms_free(Bitmapset *a)
Definition: bitmapset.c:200
#define makeNode(_type_)
Definition: nodes.h:570
#define NULL
Definition: c.h:229
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4477
Bitmapset * keys
Definition: relation.h:688
void list_free(List *list)
Definition: list.c:1133
int i
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define lfirst_oid(lc)
Definition: pg_list.h:108
bool has_row_triggers ( PlannerInfo root,
Index  rti,
CmdType  event 
)

Definition at line 1748 of file plancat.c.

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

Referenced by make_modifytable().

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

Definition at line 1716 of file plancat.c.

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

Referenced by examine_variable().

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

Definition at line 557 of file plancat.c.

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

Referenced by make_modifytable().

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

Definition at line 825 of file plancat.c.

References equal(), InferenceElem::expr, get_opclass_family(), get_opclass_input_type(), InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, IsA, list_nth(), tupleDesc::natts, RelationData::rd_att, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_opcintype, and RelationData::rd_opfamily.

Referenced by infer_arbiter_indexes().

827 {
828  AttrNumber natt;
829  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
830  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
831  int nplain = 0; /* # plain attrs observed */
832 
833  /*
834  * If inference specification element lacks collation/opclass, then no
835  * need to check for exact match.
836  */
837  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
838  return true;
839 
840  /*
841  * Lookup opfamily and input type, for matching indexes
842  */
843  if (elem->inferopclass)
844  {
845  inferopfamily = get_opclass_family(elem->inferopclass);
846  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
847  }
848 
849  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
850  {
851  Oid opfamily = idxRel->rd_opfamily[natt - 1];
852  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
853  Oid collation = idxRel->rd_indcollation[natt - 1];
854  int attno = idxRel->rd_index->indkey.values[natt - 1];
855 
856  if (attno != 0)
857  nplain++;
858 
859  if (elem->inferopclass != InvalidOid &&
860  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
861  {
862  /* Attribute needed to match opclass, but didn't */
863  continue;
864  }
865 
866  if (elem->infercollid != InvalidOid &&
867  elem->infercollid != collation)
868  {
869  /* Attribute needed to match collation, but didn't */
870  continue;
871  }
872 
873  /* If one matching index att found, good enough -- return true */
874  if (IsA(elem->expr, Var))
875  {
876  if (((Var *) elem->expr)->varattno == attno)
877  return true;
878  }
879  else if (attno == 0)
880  {
881  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
882 
883  /*
884  * Note that unlike routines like match_index_to_operand() we
885  * don't need to care about RelabelType. Neither the index
886  * definition nor the inference clause should contain them.
887  */
888  if (equal(elem->expr, nattExpr))
889  return true;
890  }
891  }
892 
893  return false;
894 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:573
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2946
Definition: nodes.h:522
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
int natts
Definition: tupdesc.h:73
Form_pg_index rd_index
Definition: rel.h:159
Oid * rd_indcollation
Definition: rel.h:193
void * list_nth(const List *list, int n)
Definition: list.c:410
Oid * rd_opfamily
Definition: rel.h:182
TupleDesc rd_att
Definition: rel.h:115
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1015
Oid * rd_opcintype
Definition: rel.h:183
int16 AttrNumber
Definition: attnum.h:21
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1037
Selectivity join_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1672 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

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

Definition at line 1332 of file plancat.c.

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

Referenced by set_append_rel_size(), and set_rel_size().

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

Definition at line 1635 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

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

Variable Documentation

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION

Definition at line 54 of file plancat.c.

Referenced by relation_excluded_by_constraints().

get_relation_info_hook_type get_relation_info_hook = NULL

Definition at line 57 of file plancat.c.

Referenced by get_relation_info().