PostgreSQL Source Code  git master
plancat.h File Reference
#include "nodes/pathnodes.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_rel_data_width (Relation rel, int32 *attr_widths)
 
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)
 
Selectivity function_selectivity (PlannerInfo *root, Oid funcid, List *args, Oid inputcollid, bool is_join, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
void add_function_cost (PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
 
double get_function_rows (PlannerInfo *root, Oid funcid, Node *node)
 
bool has_row_triggers (PlannerInfo *root, Index rti, CmdType event)
 
bool has_stored_generated_columns (PlannerInfo *root, Index rti)
 

Variables

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook
 

Typedef Documentation

◆ get_relation_info_hook_type

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

Definition at line 21 of file plancat.h.

Function Documentation

◆ add_function_cost()

void add_function_cost ( PlannerInfo root,
Oid  funcid,
Node node,
QualCost cost 
)

Definition at line 1967 of file plancat.c.

References cpu_operator_cost, DatumGetPointer, elog, ERROR, SupportRequestCost::funcid, GETSTRUCT, HeapTupleIsValid, SupportRequestCost::node, ObjectIdGetDatum, OidFunctionCall1, OidIsValid, QualCost::per_tuple, SupportRequestCost::per_tuple, PointerGetDatum, PROCOID, ReleaseSysCache(), SupportRequestCost::root, SearchSysCache1(), QualCost::startup, SupportRequestCost::startup, T_SupportRequestCost, and SupportRequestCost::type.

Referenced by cost_qual_eval_walker(), cost_windowagg(), and get_agg_clause_costs().

1969 {
1970  HeapTuple proctup;
1971  Form_pg_proc procform;
1972 
1973  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1974  if (!HeapTupleIsValid(proctup))
1975  elog(ERROR, "cache lookup failed for function %u", funcid);
1976  procform = (Form_pg_proc) GETSTRUCT(proctup);
1977 
1978  if (OidIsValid(procform->prosupport))
1979  {
1980  SupportRequestCost req;
1981  SupportRequestCost *sresult;
1982 
1983  req.type = T_SupportRequestCost;
1984  req.root = root;
1985  req.funcid = funcid;
1986  req.node = node;
1987 
1988  /* Initialize cost fields so that support function doesn't have to */
1989  req.startup = 0;
1990  req.per_tuple = 0;
1991 
1992  sresult = (SupportRequestCost *)
1993  DatumGetPointer(OidFunctionCall1(procform->prosupport,
1994  PointerGetDatum(&req)));
1995 
1996  if (sresult == &req)
1997  {
1998  /* Success, so accumulate support function's estimate into *cost */
1999  cost->startup += req.startup;
2000  cost->per_tuple += req.per_tuple;
2001  ReleaseSysCache(proctup);
2002  return;
2003  }
2004  }
2005 
2006  /* No support function, or it failed, so rely on procost */
2007  cost->per_tuple += procform->procost * cpu_operator_cost;
2008 
2009  ReleaseSysCache(proctup);
2010 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define PointerGetDatum(X)
Definition: postgres.h:600
#define OidIsValid(objectId)
Definition: c.h:710
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:664
double cpu_operator_cost
Definition: costsize.c:123
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
struct PlannerInfo * root
Definition: supportnodes.h:136
#define DatumGetPointer(X)
Definition: postgres.h:593
#define elog(elevel,...)
Definition: elog.h:232

◆ build_physical_tlist()

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1642 of file plancat.c.

References elog, ERROR, expandRTE(), IsA, lappend(), lfirst, makeTargetEntry(), makeVar(), makeVarFromTargetEntry(), NIL, NoLock, planner_rt_fetch, RelationData::rd_att, RelationGetNumberOfAttributes, RelOptInfo::relid, RangeTblEntry::relid, TargetEntry::resjunk, TargetEntry::resno, RTE_CTE, RTE_FUNCTION, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::subquery, table_close(), table_open(), Query::targetList, and TupleDescAttr.

Referenced by create_scan_plan().

1643 {
1644  List *tlist = NIL;
1645  Index varno = rel->relid;
1646  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1647  Relation relation;
1648  Query *subquery;
1649  Var *var;
1650  ListCell *l;
1651  int attrno,
1652  numattrs;
1653  List *colvars;
1654 
1655  switch (rte->rtekind)
1656  {
1657  case RTE_RELATION:
1658  /* Assume we already have adequate lock */
1659  relation = table_open(rte->relid, NoLock);
1660 
1661  numattrs = RelationGetNumberOfAttributes(relation);
1662  for (attrno = 1; attrno <= numattrs; attrno++)
1663  {
1664  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1665  attrno - 1);
1666 
1667  if (att_tup->attisdropped || att_tup->atthasmissing)
1668  {
1669  /* found a dropped or missing col, so punt */
1670  tlist = NIL;
1671  break;
1672  }
1673 
1674  var = makeVar(varno,
1675  attrno,
1676  att_tup->atttypid,
1677  att_tup->atttypmod,
1678  att_tup->attcollation,
1679  0);
1680 
1681  tlist = lappend(tlist,
1682  makeTargetEntry((Expr *) var,
1683  attrno,
1684  NULL,
1685  false));
1686  }
1687 
1688  table_close(relation, NoLock);
1689  break;
1690 
1691  case RTE_SUBQUERY:
1692  subquery = rte->subquery;
1693  foreach(l, subquery->targetList)
1694  {
1695  TargetEntry *tle = (TargetEntry *) lfirst(l);
1696 
1697  /*
1698  * A resjunk column of the subquery can be reflected as
1699  * resjunk in the physical tlist; we need not punt.
1700  */
1701  var = makeVarFromTargetEntry(varno, tle);
1702 
1703  tlist = lappend(tlist,
1704  makeTargetEntry((Expr *) var,
1705  tle->resno,
1706  NULL,
1707  tle->resjunk));
1708  }
1709  break;
1710 
1711  case RTE_FUNCTION:
1712  case RTE_TABLEFUNC:
1713  case RTE_VALUES:
1714  case RTE_CTE:
1715  case RTE_NAMEDTUPLESTORE:
1716  case RTE_RESULT:
1717  /* Not all of these can have dropped cols, but share code anyway */
1718  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1719  NULL, &colvars);
1720  foreach(l, colvars)
1721  {
1722  var = (Var *) lfirst(l);
1723 
1724  /*
1725  * A non-Var in expandRTE's output means a dropped column;
1726  * must punt.
1727  */
1728  if (!IsA(var, Var))
1729  {
1730  tlist = NIL;
1731  break;
1732  }
1733 
1734  tlist = lappend(tlist,
1735  makeTargetEntry((Expr *) var,
1736  var->varattno,
1737  NULL,
1738  false));
1739  }
1740  break;
1741 
1742  default:
1743  /* caller error */
1744  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1745  (int) rte->rtekind);
1746  break;
1747  }
1748 
1749  return tlist;
1750 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:475
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:103
Definition: primnodes.h:186
List * targetList
Definition: parsenodes.h:150
bool resjunk
Definition: primnodes.h:1451
#define ERROR
Definition: elog.h:46
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
#define NoLock
Definition: lockdefs.h:34
AttrNumber resno
Definition: primnodes.h:1445
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
unsigned int Index
Definition: c.h:549
TupleDesc rd_att
Definition: rel.h:110
#define lfirst(lc)
Definition: pg_list.h:169
RTEKind rtekind
Definition: parsenodes.h:995
Query * subquery
Definition: parsenodes.h:1030
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50

◆ estimate_rel_size()

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

Definition at line 959 of file plancat.c.

References get_rel_data_width(), MAXALIGN, RelationData::rd_rel, RelationGetNumberOfBlocks, SizeofHeapTupleHeader, SizeOfPageHeaderData, and table_relation_estimate_size().

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

961 {
962  BlockNumber curpages;
963  BlockNumber relpages;
964  double reltuples;
965  BlockNumber relallvisible;
966  double density;
967 
968  switch (rel->rd_rel->relkind)
969  {
970  case RELKIND_RELATION:
971  case RELKIND_MATVIEW:
972  case RELKIND_TOASTVALUE:
973  table_relation_estimate_size(rel, attr_widths, pages, tuples,
974  allvisfrac);
975  break;
976 
977  case RELKIND_INDEX:
978 
979  /*
980  * XXX: It'd probably be good to move this into a callback,
981  * individual index types e.g. know if they have a metapage.
982  */
983 
984  /* it has storage, ok to call the smgr */
985  curpages = RelationGetNumberOfBlocks(rel);
986 
987  /* report estimated # pages */
988  *pages = curpages;
989  /* quick exit if rel is clearly empty */
990  if (curpages == 0)
991  {
992  *tuples = 0;
993  *allvisfrac = 0;
994  break;
995  }
996 
997  /* coerce values in pg_class to more desirable types */
998  relpages = (BlockNumber) rel->rd_rel->relpages;
999  reltuples = (double) rel->rd_rel->reltuples;
1000  relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
1001 
1002  /*
1003  * Discount the metapage while estimating the number of tuples.
1004  * This is a kluge because it assumes more than it ought to about
1005  * index structure. Currently it's OK for btree, hash, and GIN
1006  * indexes but suspect for GiST indexes.
1007  */
1008  if (relpages > 0)
1009  {
1010  curpages--;
1011  relpages--;
1012  }
1013 
1014  /* estimate number of tuples from previous tuple density */
1015  if (reltuples >= 0 && relpages > 0)
1016  density = reltuples / (double) relpages;
1017  else
1018  {
1019  /*
1020  * If we have no data because the relation was never vacuumed,
1021  * estimate tuple width from attribute datatypes. We assume
1022  * here that the pages are completely full, which is OK for
1023  * tables (since they've presumably not been VACUUMed yet) but
1024  * is probably an overestimate for indexes. Fortunately
1025  * get_relation_info() can clamp the overestimate to the
1026  * parent table's size.
1027  *
1028  * Note: this code intentionally disregards alignment
1029  * considerations, because (a) that would be gilding the lily
1030  * considering how crude the estimate is, and (b) it creates
1031  * platform dependencies in the default plans which are kind
1032  * of a headache for regression testing.
1033  *
1034  * XXX: Should this logic be more index specific?
1035  */
1036  int32 tuple_width;
1037 
1038  tuple_width = get_rel_data_width(rel, attr_widths);
1039  tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1040  tuple_width += sizeof(ItemIdData);
1041  /* note: integer division is intentional here */
1042  density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1043  }
1044  *tuples = rint(density * (double) curpages);
1045 
1046  /*
1047  * We use relallvisible as-is, rather than scaling it up like we
1048  * do for the pages and tuples counts, on the theory that any
1049  * pages added since the last VACUUM are most likely not marked
1050  * all-visible. But costsize.c wants it converted to a fraction.
1051  */
1052  if (relallvisible == 0 || curpages <= 0)
1053  *allvisfrac = 0;
1054  else if ((double) relallvisible >= curpages)
1055  *allvisfrac = 1;
1056  else
1057  *allvisfrac = (double) relallvisible / curpages;
1058  break;
1059 
1060  case RELKIND_SEQUENCE:
1061  /* Sequences always have a known size */
1062  *pages = 1;
1063  *tuples = 1;
1064  *allvisfrac = 0;
1065  break;
1066  case RELKIND_FOREIGN_TABLE:
1067  /* Just use whatever's in pg_class */
1068  /* Note that FDW must cope if reltuples is -1! */
1069  *pages = rel->rd_rel->relpages;
1070  *tuples = rel->rd_rel->reltuples;
1071  *allvisfrac = 0;
1072  break;
1073  default:
1074  /* else it has no disk storage; probably shouldn't get here? */
1075  *pages = 0;
1076  *tuples = 0;
1077  *allvisfrac = 0;
1078  break;
1079  }
1080 }
static void table_relation_estimate_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: tableam.h:1907
#define SizeofHeapTupleHeader
Definition: htup_details.h:184
uint32 BlockNumber
Definition: block.h:31
#define SizeOfPageHeaderData
Definition: bufpage.h:216
Form_pg_class rd_rel
Definition: rel.h:109
signed int int32
Definition: c.h:429
struct ItemIdData ItemIdData
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
#define MAXALIGN(LEN)
Definition: c.h:757
int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1097

◆ function_selectivity()

Selectivity function_selectivity ( PlannerInfo root,
Oid  funcid,
List args,
Oid  inputcollid,
bool  is_join,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1905 of file plancat.c.

References SupportRequestSelectivity::args, generate_unaccent_rules::args, DatumGetPointer, elog, ERROR, SupportRequestSelectivity::funcid, get_func_support(), SupportRequestSelectivity::inputcollid, SupportRequestSelectivity::is_join, SupportRequestSelectivity::jointype, OidFunctionCall1, PointerGetDatum, SupportRequestSelectivity::root, SupportRequestSelectivity::selectivity, SupportRequestSelectivity::sjinfo, T_SupportRequestSelectivity, SupportRequestSelectivity::type, and SupportRequestSelectivity::varRelid.

Referenced by clause_selectivity_ext().

1913 {
1914  RegProcedure prosupport = get_func_support(funcid);
1916  SupportRequestSelectivity *sresult;
1917 
1918  /*
1919  * If no support function is provided, use our historical default
1920  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
1921  * Postgres has been using that estimate for function calls since 1992.
1922  * The hoariness of this behavior suggests that we should not be in too
1923  * much hurry to use another value.
1924  */
1925  if (!prosupport)
1926  return (Selectivity) 0.3333333;
1927 
1929  req.root = root;
1930  req.funcid = funcid;
1931  req.args = args;
1932  req.inputcollid = inputcollid;
1933  req.is_join = is_join;
1934  req.varRelid = varRelid;
1935  req.jointype = jointype;
1936  req.sjinfo = sjinfo;
1937  req.selectivity = -1; /* to catch failure to set the value */
1938 
1939  sresult = (SupportRequestSelectivity *)
1940  DatumGetPointer(OidFunctionCall1(prosupport,
1941  PointerGetDatum(&req)));
1942 
1943  /* If support function fails, use default */
1944  if (sresult != &req)
1945  return (Selectivity) 0.3333333;
1946 
1947  if (req.selectivity < 0.0 || req.selectivity > 1.0)
1948  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
1949 
1950  return (Selectivity) req.selectivity;
1951 }
#define PointerGetDatum(X)
Definition: postgres.h:600
regproc RegProcedure
Definition: c.h:585
double Selectivity
Definition: nodes.h:672
#define ERROR
Definition: elog.h:46
struct PlannerInfo * root
Definition: supportnodes.h:96
struct SpecialJoinInfo * sjinfo
Definition: supportnodes.h:103
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:664
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1829
#define DatumGetPointer(X)
Definition: postgres.h:593
#define elog(elevel,...)
Definition: elog.h:232

◆ get_function_rows()

double get_function_rows ( PlannerInfo root,
Oid  funcid,
Node node 
)

Definition at line 2028 of file plancat.c.

References Assert, DatumGetPointer, elog, ERROR, SupportRequestRows::funcid, GETSTRUCT, HeapTupleIsValid, SupportRequestRows::node, ObjectIdGetDatum, OidFunctionCall1, OidIsValid, PointerGetDatum, PROCOID, ReleaseSysCache(), SupportRequestRows::root, SupportRequestRows::rows, SearchSysCache1(), T_SupportRequestRows, and SupportRequestRows::type.

Referenced by expression_returns_set_rows().

2029 {
2030  HeapTuple proctup;
2031  Form_pg_proc procform;
2032  double result;
2033 
2034  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2035  if (!HeapTupleIsValid(proctup))
2036  elog(ERROR, "cache lookup failed for function %u", funcid);
2037  procform = (Form_pg_proc) GETSTRUCT(proctup);
2038 
2039  Assert(procform->proretset); /* else caller error */
2040 
2041  if (OidIsValid(procform->prosupport))
2042  {
2043  SupportRequestRows req;
2044  SupportRequestRows *sresult;
2045 
2046  req.type = T_SupportRequestRows;
2047  req.root = root;
2048  req.funcid = funcid;
2049  req.node = node;
2050 
2051  req.rows = 0; /* just for sanity */
2052 
2053  sresult = (SupportRequestRows *)
2054  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2055  PointerGetDatum(&req)));
2056 
2057  if (sresult == &req)
2058  {
2059  /* Success */
2060  ReleaseSysCache(proctup);
2061  return req.rows;
2062  }
2063  }
2064 
2065  /* No support function, or it failed, so rely on prorows */
2066  result = procform->prorows;
2067 
2068  ReleaseSysCache(proctup);
2069 
2070  return result;
2071 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define PointerGetDatum(X)
Definition: postgres.h:600
#define OidIsValid(objectId)
Definition: c.h:710
struct PlannerInfo * root
Definition: supportnodes.h:163
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:664
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define DatumGetPointer(X)
Definition: postgres.h:593
#define elog(elevel,...)
Definition: elog.h:232

◆ get_rel_data_width()

int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)

Definition at line 1097 of file plancat.c.

References Assert, get_attavgwidth(), get_typavgwidth(), i, RelationData::rd_att, RelationGetNumberOfAttributes, RelationGetRelid, and TupleDescAttr.

Referenced by estimate_rel_size(), get_relation_data_width(), and table_block_relation_estimate_size().

1098 {
1099  int32 tuple_width = 0;
1100  int i;
1101 
1102  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1103  {
1104  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1105  int32 item_width;
1106 
1107  if (att->attisdropped)
1108  continue;
1109 
1110  /* use previously cached data, if any */
1111  if (attr_widths != NULL && attr_widths[i] > 0)
1112  {
1113  tuple_width += attr_widths[i];
1114  continue;
1115  }
1116 
1117  /* This should match set_rel_width() in costsize.c */
1118  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1119  if (item_width <= 0)
1120  {
1121  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1122  Assert(item_width > 0);
1123  }
1124  if (attr_widths != NULL)
1125  attr_widths[i] = item_width;
1126  tuple_width += item_width;
1127  }
1128 
1129  return tuple_width;
1130 }
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:475
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
signed int int32
Definition: c.h:429
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:203
TupleDesc rd_att
Definition: rel.h:110
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2525
#define Assert(condition)
Definition: c.h:804
int i
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3105
#define RelationGetRelid(relation)
Definition: rel.h:469

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1139 of file plancat.c.

References get_rel_data_width(), NoLock, table_close(), and table_open().

Referenced by plan_cluster_use_sort(), and set_rel_width().

1140 {
1141  int32 result;
1142  Relation relation;
1143 
1144  /* As above, assume relation is already locked */
1145  relation = table_open(relid, NoLock);
1146 
1147  result = get_rel_data_width(relation, attr_widths);
1148 
1149  table_close(relation, NoLock);
1150 
1151  return result;
1152 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
signed int int32
Definition: c.h:429
#define NoLock
Definition: lockdefs.h:34
int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1097
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ get_relation_info()

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

Definition at line 113 of file plancat.c.

References _bt_getrootheight(), RelOptInfo::allvisfrac, IndexOptInfo::amcanmarkpos, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanorderbyop, IndexOptInfo::amcanorderbyop, IndexAmRoutine::amcanparallel, IndexOptInfo::amcanparallel, IndexAmRoutine::amcostestimate, IndexOptInfo::amcostestimate, AMFLAG_HAS_TID_RANGE, RelOptInfo::amflags, IndexAmRoutine::amgetbitmap, IndexAmRoutine::amgettuple, IndexOptInfo::amhasgetbitmap, IndexOptInfo::amhasgettuple, IndexAmRoutine::ammarkpos, IndexAmRoutine::amoptionalkey, IndexOptInfo::amoptionalkey, IndexAmRoutine::amrestrpos, IndexAmRoutine::amsearcharray, IndexOptInfo::amsearcharray, IndexAmRoutine::amsearchnulls, IndexOptInfo::amsearchnulls, Assert, RelOptInfo::attr_needed, RelOptInfo::attr_widths, BTLessStrategyNumber, build_index_tlist(), IndexOptInfo::canreturn, ChangeVarNodes(), ereport, errcode(), errmsg(), ERROR, estimate_rel_size(), RelOptInfo::fdwroutine, FirstLowInvalidHeapAttributeNumber, get_opfamily_member(), get_ordering_op_properties(), get_relation_foreign_keys(), get_relation_info_hook, get_relation_statistics(), GetFdwRoutineForRelation(), GetForeignServerIdByRelId(), PlannerInfo::glob, HeapTupleHeaderGetXmin, IndexOptInfo::hypothetical, i, IgnoreSystemIndexes, IndexOptInfo::immediate, index_can_return(), index_close(), index_open(), IndexOptInfo::indexcollations, IndexOptInfo::indexkeys, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, IndexOptInfo::indextlist, IndexOptInfo::indpred, IndexOptInfo::indrestrictinfo, InvalidOid, IsSystemRelation(), lcons(), lfirst_oid, list_free(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, NoLock, IndexOptInfo::nulls_first, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opclassoptions, IndexOptInfo::opfamily, RelOptInfo::pages, IndexOptInfo::pages, palloc(), palloc0(), IndexOptInfo::predOK, RelationData::rd_indam, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_opcintype, RelationData::rd_opfamily, RelationData::rd_rel, RelationData::rd_tableam, RecoveryInProgress(), IndexOptInfo::rel, RelOptInfo::rel_parallel_workers, IndexOptInfo::relam, RelationGetForm, RelationGetIndexAttOptions(), RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNumberOfAttributes, RelationGetNumberOfBlocks, RelationGetParallelWorkers, RelationGetRelid, RelationIsPermanent, RelOptInfo::relid, RangeTblEntry::rellockmode, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, IndexOptInfo::reverse_sort, TableAmRoutine::scan_bitmap_next_block, TableAmRoutine::scan_getnextslot_tidrange, TableAmRoutine::scan_set_tidrange, RelOptInfo::serverid, set_relation_partition_info(), PlannerInfo::simple_rte_array, IndexOptInfo::sortopfamily, RelOptInfo::statlist, HeapTupleData::t_data, table_close(), table_open(), TransactionIdPrecedes(), TransactionXmin, PlannerGlobal::transientPlan, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by build_simple_rel().

115 {
116  Index varno = rel->relid;
117  Relation relation;
118  bool hasindex;
119  List *indexinfos = NIL;
120 
121  /*
122  * We need not lock the relation since it was already locked, either by
123  * the rewriter or when expand_inherited_rtentry() added it to the query's
124  * rangetable.
125  */
126  relation = table_open(relationObjectId, NoLock);
127 
128  /* Temporary and unlogged relations are inaccessible during recovery. */
129  if (!RelationIsPermanent(relation) && RecoveryInProgress())
130  ereport(ERROR,
131  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
132  errmsg("cannot access temporary or unlogged relations during recovery")));
133 
135  rel->max_attr = RelationGetNumberOfAttributes(relation);
136  rel->reltablespace = RelationGetForm(relation)->reltablespace;
137 
138  Assert(rel->max_attr >= rel->min_attr);
139  rel->attr_needed = (Relids *)
140  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
141  rel->attr_widths = (int32 *)
142  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
143 
144  /*
145  * Estimate relation size --- unless it's an inheritance parent, in which
146  * case the size we want is not the rel's own size but the size of its
147  * inheritance tree. That will be computed in set_append_rel_size().
148  */
149  if (!inhparent)
150  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
151  &rel->pages, &rel->tuples, &rel->allvisfrac);
152 
153  /* Retrieve the parallel_workers reloption, or -1 if not set. */
155 
156  /*
157  * Make list of indexes. Ignore indexes on system catalogs if told to.
158  * Don't bother with indexes for an inheritance parent, either.
159  */
160  if (inhparent ||
161  (IgnoreSystemIndexes && IsSystemRelation(relation)))
162  hasindex = false;
163  else
164  hasindex = relation->rd_rel->relhasindex;
165 
166  if (hasindex)
167  {
168  List *indexoidlist;
169  LOCKMODE lmode;
170  ListCell *l;
171 
172  indexoidlist = RelationGetIndexList(relation);
173 
174  /*
175  * For each index, we get the same type of lock that the executor will
176  * need, and do not release it. This saves a couple of trips to the
177  * shared lock manager while not creating any real loss of
178  * concurrency, because no schema changes could be happening on the
179  * index while we hold lock on the parent rel, and no lock type used
180  * for queries blocks any other kind of index operation.
181  */
182  lmode = root->simple_rte_array[varno]->rellockmode;
183 
184  foreach(l, indexoidlist)
185  {
186  Oid indexoid = lfirst_oid(l);
187  Relation indexRelation;
189  IndexAmRoutine *amroutine;
190  IndexOptInfo *info;
191  int ncolumns,
192  nkeycolumns;
193  int i;
194 
195  /*
196  * Extract info from the relation descriptor for the index.
197  */
198  indexRelation = index_open(indexoid, lmode);
199  index = indexRelation->rd_index;
200 
201  /*
202  * Ignore invalid indexes, since they can't safely be used for
203  * queries. Note that this is OK because the data structure we
204  * are constructing is only used by the planner --- the executor
205  * still needs to insert into "invalid" indexes, if they're marked
206  * indisready.
207  */
208  if (!index->indisvalid)
209  {
210  index_close(indexRelation, NoLock);
211  continue;
212  }
213 
214  /*
215  * Ignore partitioned indexes, since they are not usable for
216  * queries.
217  */
218  if (indexRelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
219  {
220  index_close(indexRelation, NoLock);
221  continue;
222  }
223 
224  /*
225  * If the index is valid, but cannot yet be used, ignore it; but
226  * mark the plan we are generating as transient. See
227  * src/backend/access/heap/README.HOT for discussion.
228  */
229  if (index->indcheckxmin &&
232  {
233  root->glob->transientPlan = true;
234  index_close(indexRelation, NoLock);
235  continue;
236  }
237 
238  info = makeNode(IndexOptInfo);
239 
240  info->indexoid = index->indexrelid;
241  info->reltablespace =
242  RelationGetForm(indexRelation)->reltablespace;
243  info->rel = rel;
244  info->ncolumns = ncolumns = index->indnatts;
245  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
246 
247  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
248  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
249  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
250  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
251  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
252 
253  for (i = 0; i < ncolumns; i++)
254  {
255  info->indexkeys[i] = index->indkey.values[i];
256  info->canreturn[i] = index_can_return(indexRelation, i + 1);
257  }
258 
259  for (i = 0; i < nkeycolumns; i++)
260  {
261  info->opfamily[i] = indexRelation->rd_opfamily[i];
262  info->opcintype[i] = indexRelation->rd_opcintype[i];
263  info->indexcollations[i] = indexRelation->rd_indcollation[i];
264  }
265 
266  info->relam = indexRelation->rd_rel->relam;
267 
268  /* We copy just the fields we need, not all of rd_indam */
269  amroutine = indexRelation->rd_indam;
270  info->amcanorderbyop = amroutine->amcanorderbyop;
271  info->amoptionalkey = amroutine->amoptionalkey;
272  info->amsearcharray = amroutine->amsearcharray;
273  info->amsearchnulls = amroutine->amsearchnulls;
274  info->amcanparallel = amroutine->amcanparallel;
275  info->amhasgettuple = (amroutine->amgettuple != NULL);
276  info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
277  relation->rd_tableam->scan_bitmap_next_block != NULL;
278  info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
279  amroutine->amrestrpos != NULL);
280  info->amcostestimate = amroutine->amcostestimate;
281  Assert(info->amcostestimate != NULL);
282 
283  /* Fetch index opclass options */
284  info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
285 
286  /*
287  * Fetch the ordering information for the index, if any.
288  */
289  if (info->relam == BTREE_AM_OID)
290  {
291  /*
292  * If it's a btree index, we can use its opfamily OIDs
293  * directly as the sort ordering opfamily OIDs.
294  */
295  Assert(amroutine->amcanorder);
296 
297  info->sortopfamily = info->opfamily;
298  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
299  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
300 
301  for (i = 0; i < nkeycolumns; i++)
302  {
303  int16 opt = indexRelation->rd_indoption[i];
304 
305  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
306  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
307  }
308  }
309  else if (amroutine->amcanorder)
310  {
311  /*
312  * Otherwise, identify the corresponding btree opfamilies by
313  * trying to map this index's "<" operators into btree. Since
314  * "<" uniquely defines the behavior of a sort order, this is
315  * a sufficient test.
316  *
317  * XXX This method is rather slow and also requires the
318  * undesirable assumption that the other index AM numbers its
319  * strategies the same as btree. It'd be better to have a way
320  * to explicitly declare the corresponding btree opfamily for
321  * each opfamily of the other index type. But given the lack
322  * of current or foreseeable amcanorder index types, it's not
323  * worth expending more effort on now.
324  */
325  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
326  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
327  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
328 
329  for (i = 0; i < nkeycolumns; i++)
330  {
331  int16 opt = indexRelation->rd_indoption[i];
332  Oid ltopr;
333  Oid btopfamily;
334  Oid btopcintype;
335  int16 btstrategy;
336 
337  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
338  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
339 
340  ltopr = get_opfamily_member(info->opfamily[i],
341  info->opcintype[i],
342  info->opcintype[i],
344  if (OidIsValid(ltopr) &&
346  &btopfamily,
347  &btopcintype,
348  &btstrategy) &&
349  btopcintype == info->opcintype[i] &&
350  btstrategy == BTLessStrategyNumber)
351  {
352  /* Successful mapping */
353  info->sortopfamily[i] = btopfamily;
354  }
355  else
356  {
357  /* Fail ... quietly treat index as unordered */
358  info->sortopfamily = NULL;
359  info->reverse_sort = NULL;
360  info->nulls_first = NULL;
361  break;
362  }
363  }
364  }
365  else
366  {
367  info->sortopfamily = NULL;
368  info->reverse_sort = NULL;
369  info->nulls_first = NULL;
370  }
371 
372  /*
373  * Fetch the index expressions and predicate, if any. We must
374  * modify the copies we obtain from the relcache to have the
375  * correct varno for the parent relation, so that they match up
376  * correctly against qual clauses.
377  */
378  info->indexprs = RelationGetIndexExpressions(indexRelation);
379  info->indpred = RelationGetIndexPredicate(indexRelation);
380  if (info->indexprs && varno != 1)
381  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
382  if (info->indpred && varno != 1)
383  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
384 
385  /* Build targetlist using the completed indexprs data */
386  info->indextlist = build_index_tlist(root, info, relation);
387 
388  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
389  info->predOK = false; /* set later, in indxpath.c */
390  info->unique = index->indisunique;
391  info->immediate = index->indimmediate;
392  info->hypothetical = false;
393 
394  /*
395  * Estimate the index size. If it's not a partial index, we lock
396  * the number-of-tuples estimate to equal the parent table; if it
397  * is partial then we have to use the same methods as we would for
398  * a table, except we can be sure that the index is not larger
399  * than the table.
400  */
401  if (info->indpred == NIL)
402  {
403  info->pages = RelationGetNumberOfBlocks(indexRelation);
404  info->tuples = rel->tuples;
405  }
406  else
407  {
408  double allvisfrac; /* dummy */
409 
410  estimate_rel_size(indexRelation, NULL,
411  &info->pages, &info->tuples, &allvisfrac);
412  if (info->tuples > rel->tuples)
413  info->tuples = rel->tuples;
414  }
415 
416  if (info->relam == BTREE_AM_OID)
417  {
418  /* For btrees, get tree height while we have the index open */
419  info->tree_height = _bt_getrootheight(indexRelation);
420  }
421  else
422  {
423  /* For other index types, just set it to "unknown" for now */
424  info->tree_height = -1;
425  }
426 
427  index_close(indexRelation, NoLock);
428 
429  /*
430  * We've historically used lcons() here. It'd make more sense to
431  * use lappend(), but that causes the planner to change behavior
432  * in cases where two indexes seem equally attractive. For now,
433  * stick with lcons() --- few tables should have so many indexes
434  * that the O(N^2) behavior of lcons() is really a problem.
435  */
436  indexinfos = lcons(info, indexinfos);
437  }
438 
439  list_free(indexoidlist);
440  }
441 
442  rel->indexlist = indexinfos;
443 
444  rel->statlist = get_relation_statistics(rel, relation);
445 
446  /* Grab foreign-table info using the relcache, while we have it */
447  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
448  {
450  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
451  }
452  else
453  {
454  rel->serverid = InvalidOid;
455  rel->fdwroutine = NULL;
456  }
457 
458  /* Collect info about relation's foreign keys, if relevant */
459  get_relation_foreign_keys(root, rel, relation, inhparent);
460 
461  /* Collect info about functions implemented by the rel's table AM. */
462  if (relation->rd_tableam &&
463  relation->rd_tableam->scan_set_tidrange != NULL &&
464  relation->rd_tableam->scan_getnextslot_tidrange != NULL)
466 
467  /*
468  * Collect info about relation's partitioning scheme, if any. Only
469  * inheritance parents may be partitioned.
470  */
471  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
472  set_relation_partition_info(root, rel, relation);
473 
474  table_close(relation, NoLock);
475 
476  /*
477  * Allow a plugin to editorialize on the info we obtained from the
478  * catalogs. Actions might include altering the assumed relation size,
479  * removing an index, or adding a hypothetical index to the indexlist.
480  */
482  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
483 }
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
#define RelationIsPermanent(relation)
Definition: rel.h:571
struct IndexAmRoutine * rd_indam
Definition: rel.h:201
List * statlist
Definition: pathnodes.h:714
int16 * rd_indoption
Definition: rel.h:206
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1301
Oid * indexcollations
Definition: pathnodes.h:844
Relids * attr_needed
Definition: pathnodes.h:709
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
amgettuple_function amgettuple
Definition: amapi.h:273
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:672
int LOCKMODE
Definition: lockdefs.h:26
bool amcanorderbyop
Definition: amapi.h:222
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:475
List * indextlist
Definition: pathnodes.h:858
#define RelationGetForm(relation)
Definition: rel.h:463
double tuples
Definition: pathnodes.h:716
Oid reltablespace
Definition: pathnodes.h:705
Definition: nodes.h:539
Oid * sortopfamily
Definition: pathnodes.h:847
int errcode(int sqlerrcode)
Definition: elog.c:698
Oid reltablespace
Definition: pathnodes.h:831
bool IgnoreSystemIndexes
Definition: miscinit.c:79
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
bool hypothetical
Definition: pathnodes.h:869
bool immediate
Definition: pathnodes.h:868
double tuples
Definition: pathnodes.h:836
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8210
int tree_height
Definition: pathnodes.h:837
#define OidIsValid(objectId)
Definition: c.h:710
bool amoptionalkey
Definition: amapi.h:230
double allvisfrac
Definition: pathnodes.h:717
signed int int32
Definition: c.h:429
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4917
struct HeapTupleData * rd_indextuple
Definition: rel.h:189
TransactionId TransactionXmin
Definition: snapmgr.c:112
HeapTupleHeader t_data
Definition: htup.h:68
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:835
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:731
Form_pg_index rd_index
Definition: rel.h:187
uint32 amflags
Definition: pathnodes.h:723
RelOptInfo * rel
Definition: pathnodes.h:832
bool amoptionalkey
Definition: pathnodes.h:873
amgetbitmap_function amgetbitmap
Definition: amapi.h:274
Oid * rd_indcollation
Definition: rel.h:212
#define ERROR
Definition: elog.h:46
bool(* scan_bitmap_next_block)(TableScanDesc scan, struct TBMIterateResult *tbmres)
Definition: tableam.h:788
amcostestimate_function amcostestimate
Definition: amapi.h:265
#define NoLock
Definition: lockdefs.h:34
bool amcanorderbyop
Definition: pathnodes.h:872
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4804
PlannerGlobal * glob
Definition: pathnodes.h:163
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:731
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:2183
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:60
Oid * rd_opfamily
Definition: rel.h:202
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:959
void(* amcostestimate)()
Definition: pathnodes.h:881
bool amhasgetbitmap
Definition: pathnodes.h:877
bool amcanparallel
Definition: amapi.h:242
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
Index relid
Definition: pathnodes.h:704
bool(* scan_getnextslot_tidrange)(TableScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:354
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:193
Oid serverid
Definition: pathnodes.h:727
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
bool amsearchnulls
Definition: amapi.h:234
List * indrestrictinfo
Definition: pathnodes.h:860
void * palloc0(Size size)
Definition: mcxt.c:1093
int rel_parallel_workers
Definition: pathnodes.h:722
const struct TableAmRoutine * rd_tableam
Definition: rel.h:184
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:213
unsigned int Index
Definition: c.h:549
List * indexlist
Definition: pathnodes.h:713
bool amsearcharray
Definition: amapi.h:232
bool amhasgettuple
Definition: pathnodes.h:876
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
List * lcons(void *datum, List *list)
Definition: list.c:468
void(* scan_set_tidrange)(TableScanDesc scan, ItemPointer mintid, ItemPointer maxtid)
Definition: tableam.h:346
#define makeNode(_type_)
Definition: nodes.h:587
BlockNumber pages
Definition: pathnodes.h:715
#define Assert(condition)
Definition: c.h:804
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:496
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:340
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:205
bool amsearcharray
Definition: pathnodes.h:874
ammarkpos_function ammarkpos
Definition: amapi.h:276
bool amcanorder
Definition: amapi.h:220
int nkeycolumns
Definition: pathnodes.h:841
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4570
Oid * opcintype
Definition: pathnodes.h:846
Bitmapset * Relids
Definition: pathnodes.h:28
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool amcanmarkpos
Definition: pathnodes.h:879
Oid * opfamily
Definition: pathnodes.h:845
AttrNumber max_attr
Definition: pathnodes.h:708
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:427
void list_free(List *list)
Definition: list.c:1391
int i
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:372
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1763
int * indexkeys
Definition: pathnodes.h:842
bool * canreturn
Definition: pathnodes.h:851
#define AMFLAG_HAS_TID_RANGE
Definition: pathnodes.h:632
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5567
bool amsearchnulls
Definition: pathnodes.h:875
Oid * rd_opcintype
Definition: rel.h:203
bool * nulls_first
Definition: pathnodes.h:849
bool * reverse_sort
Definition: pathnodes.h:848
bytea ** opclassoptions
Definition: pathnodes.h:850
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: pathnodes.h:856
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
int32 * attr_widths
Definition: pathnodes.h:710
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:469
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
bool amcanparallel
Definition: pathnodes.h:878
#define lfirst_oid(lc)
Definition: pg_list.h:171
List * indexprs
Definition: pathnodes.h:855
bool transientPlan
Definition: pathnodes.h:121
amrestrpos_function amrestrpos
Definition: amapi.h:277
AttrNumber min_attr
Definition: pathnodes.h:707

◆ has_row_triggers()

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

Definition at line 2118 of file plancat.c.

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

2119 {
2120  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2121  Relation relation;
2122  TriggerDesc *trigDesc;
2123  bool result = false;
2124 
2125  /* Assume we already have adequate lock */
2126  relation = table_open(rte->relid, NoLock);
2127 
2128  trigDesc = relation->trigdesc;
2129  switch (event)
2130  {
2131  case CMD_INSERT:
2132  if (trigDesc &&
2133  (trigDesc->trig_insert_after_row ||
2134  trigDesc->trig_insert_before_row))
2135  result = true;
2136  break;
2137  case CMD_UPDATE:
2138  if (trigDesc &&
2139  (trigDesc->trig_update_after_row ||
2140  trigDesc->trig_update_before_row))
2141  result = true;
2142  break;
2143  case CMD_DELETE:
2144  if (trigDesc &&
2145  (trigDesc->trig_delete_after_row ||
2146  trigDesc->trig_delete_before_row))
2147  result = true;
2148  break;
2149  default:
2150  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2151  break;
2152  }
2153 
2154  table_close(relation, NoLock);
2155  return result;
2156 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define ERROR
Definition: elog.h:46
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
TriggerDesc * trigdesc
Definition: rel.h:115
bool trig_delete_after_row
Definition: reltrigger.h:67
#define NoLock
Definition: lockdefs.h:34
bool trig_update_before_row
Definition: reltrigger.h:61
bool trig_insert_after_row
Definition: reltrigger.h:57
bool trig_update_after_row
Definition: reltrigger.h:62
bool trig_insert_before_row
Definition: reltrigger.h:56
#define elog(elevel,...)
Definition: elog.h:232
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool trig_delete_before_row
Definition: reltrigger.h:66

◆ has_stored_generated_columns()

bool has_stored_generated_columns ( PlannerInfo root,
Index  rti 
)

Definition at line 2159 of file plancat.c.

References TupleDescData::constr, TupleConstr::has_generated_stored, NoLock, planner_rt_fetch, RelationGetDescr, RangeTblEntry::relid, table_close(), and table_open().

Referenced by make_modifytable().

2160 {
2161  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2162  Relation relation;
2163  TupleDesc tupdesc;
2164  bool result = false;
2165 
2166  /* Assume we already have adequate lock */
2167  relation = table_open(rte->relid, NoLock);
2168 
2169  tupdesc = RelationGetDescr(relation);
2170  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2171 
2172  table_close(relation, NoLock);
2173 
2174  return result;
2175 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:495
bool has_generated_stored
Definition: tupdesc.h:45
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
#define NoLock
Definition: lockdefs.h:34
TupleConstr * constr
Definition: tupdesc.h:85
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2086 of file plancat.c.

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

Referenced by examine_variable().

2087 {
2088  ListCell *ilist;
2089 
2090  foreach(ilist, rel->indexlist)
2091  {
2092  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2093 
2094  /*
2095  * Note: ignore partial indexes, since they don't allow us to conclude
2096  * that all attr values are distinct, *unless* they are marked predOK
2097  * which means we know the index's predicate is satisfied by the
2098  * query. We don't take any interest in expressional indexes either.
2099  * Also, a multicolumn unique index doesn't allow us to conclude that
2100  * just the specified attr is unique.
2101  */
2102  if (index->unique &&
2103  index->nkeycolumns == 1 &&
2104  index->indexkeys[0] == attno &&
2105  (index->indpred == NIL || index->predOK))
2106  return true;
2107  }
2108  return false;
2109 }
#define NIL
Definition: pg_list.h:65
Definition: type.h:89
List * indexlist
Definition: pathnodes.h:713
#define lfirst(lc)
Definition: pg_list.h:169
int nkeycolumns
Definition: pathnodes.h:841
int * indexkeys
Definition: pathnodes.h:842
List * indpred
Definition: pathnodes.h:856

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 611 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(), index_close(), index_open(), infer_collation_opclass_match(), InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, IsA, lappend(), lappend_oid(), lfirst, lfirst_oid, list_difference(), list_free(), list_member(), next, NIL, NoLock, Query::onConflict, ONCONFLICT_UPDATE, PlannerInfo::parse, predicate_implied_by(), RelationData::rd_index, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RangeTblEntry::relid, RangeTblEntry::rellockmode, Query::resultRelation, rt_fetch, Query::rtable, table_close(), table_open(), and Var::varattno.

Referenced by make_modifytable().

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

◆ join_selectivity()

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

Definition at line 1864 of file plancat.c.

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

Referenced by clause_selectivity_ext(), rowcomparesel(), and test_support_func().

1870 {
1871  RegProcedure oprjoin = get_oprjoin(operatorid);
1872  float8 result;
1873 
1874  /*
1875  * if the oprjoin procedure is missing for whatever reason, use a
1876  * selectivity of 0.5
1877  */
1878  if (!oprjoin)
1879  return (Selectivity) 0.5;
1880 
1881  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1882  inputcollid,
1883  PointerGetDatum(root),
1884  ObjectIdGetDatum(operatorid),
1885  PointerGetDatum(args),
1886  Int16GetDatum(jointype),
1887  PointerGetDatum(sjinfo)));
1888 
1889  if (result < 0.0 || result > 1.0)
1890  elog(ERROR, "invalid join selectivity: %f", result);
1891 
1892  return (Selectivity) result;
1893 }
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1552
#define PointerGetDatum(X)
Definition: postgres.h:600
regproc RegProcedure
Definition: c.h:585
#define Int16GetDatum(X)
Definition: postgres.h:495
double Selectivity
Definition: nodes.h:672
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
double float8
Definition: c.h:565
#define DatumGetFloat8(X)
Definition: postgres.h:758
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1452
#define elog(elevel,...)
Definition: elog.h:232

◆ relation_excluded_by_constraints()

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

Definition at line 1455 of file plancat.c.

References Assert, RelOptInfo::baserestrictinfo, RestrictInfo::clause, constraint_exclusion, CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_ON, CONSTRAINT_EXCLUSION_PARTITION, contain_mutable_functions(), DatumGetBool, get_relation_constraints(), RangeTblEntry::inh, IS_SIMPLE_REL, IsA, lappend(), lfirst, linitial, list_length(), NIL, predicate_refuted_by(), RangeTblEntry::relid, RangeTblEntry::relkind, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by set_append_rel_size(), and set_rel_size().

1457 {
1458  bool include_noinherit;
1459  bool include_notnull;
1460  bool include_partition = false;
1461  List *safe_restrictions;
1462  List *constraint_pred;
1463  List *safe_constraints;
1464  ListCell *lc;
1465 
1466  /* As of now, constraint exclusion works only with simple relations. */
1467  Assert(IS_SIMPLE_REL(rel));
1468 
1469  /*
1470  * If there are no base restriction clauses, we have no hope of proving
1471  * anything below, so fall out quickly.
1472  */
1473  if (rel->baserestrictinfo == NIL)
1474  return false;
1475 
1476  /*
1477  * Regardless of the setting of constraint_exclusion, detect
1478  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1479  * reduce "anything AND FALSE" to just "FALSE", any such case should
1480  * result in exactly one baserestrictinfo entry. This doesn't fire very
1481  * often, but it seems cheap enough to be worth doing anyway. (Without
1482  * this, we'd miss some optimizations that 9.5 and earlier found via much
1483  * more roundabout methods.)
1484  */
1485  if (list_length(rel->baserestrictinfo) == 1)
1486  {
1488  Expr *clause = rinfo->clause;
1489 
1490  if (clause && IsA(clause, Const) &&
1491  (((Const *) clause)->constisnull ||
1492  !DatumGetBool(((Const *) clause)->constvalue)))
1493  return true;
1494  }
1495 
1496  /*
1497  * Skip further tests, depending on constraint_exclusion.
1498  */
1499  switch (constraint_exclusion)
1500  {
1502  /* In 'off' mode, never make any further tests */
1503  return false;
1504 
1506 
1507  /*
1508  * When constraint_exclusion is set to 'partition' we only handle
1509  * appendrel members. Partition pruning has already been applied,
1510  * so there is no need to consider the rel's partition constraints
1511  * here.
1512  */
1513  if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
1514  break; /* appendrel member, so process it */
1515  return false;
1516 
1518 
1519  /*
1520  * In 'on' mode, always apply constraint exclusion. If we are
1521  * considering a baserel that is a partition (i.e., it was
1522  * directly named rather than expanded from a parent table), then
1523  * its partition constraints haven't been considered yet, so
1524  * include them in the processing here.
1525  */
1526  if (rel->reloptkind == RELOPT_BASEREL)
1527  include_partition = true;
1528  break; /* always try to exclude */
1529  }
1530 
1531  /*
1532  * Check for self-contradictory restriction clauses. We dare not make
1533  * deductions with non-immutable functions, but any immutable clauses that
1534  * are self-contradictory allow us to conclude the scan is unnecessary.
1535  *
1536  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1537  * expecting to see any in its predicate argument.
1538  */
1539  safe_restrictions = NIL;
1540  foreach(lc, rel->baserestrictinfo)
1541  {
1542  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1543 
1544  if (!contain_mutable_functions((Node *) rinfo->clause))
1545  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1546  }
1547 
1548  /*
1549  * We can use weak refutation here, since we're comparing restriction
1550  * clauses with restriction clauses.
1551  */
1552  if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1553  return true;
1554 
1555  /*
1556  * Only plain relations have constraints, so stop here for other rtekinds.
1557  */
1558  if (rte->rtekind != RTE_RELATION)
1559  return false;
1560 
1561  /*
1562  * If we are scanning just this table, we can use NO INHERIT constraints,
1563  * but not if we're scanning its children too. (Note that partitioned
1564  * tables should never have NO INHERIT constraints; but it's not necessary
1565  * for us to assume that here.)
1566  */
1567  include_noinherit = !rte->inh;
1568 
1569  /*
1570  * Currently, attnotnull constraints must be treated as NO INHERIT unless
1571  * this is a partitioned table. In future we might track their
1572  * inheritance status more accurately, allowing this to be refined.
1573  */
1574  include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
1575 
1576  /*
1577  * Fetch the appropriate set of constraint expressions.
1578  */
1579  constraint_pred = get_relation_constraints(root, rte->relid, rel,
1580  include_noinherit,
1581  include_notnull,
1582  include_partition);
1583 
1584  /*
1585  * We do not currently enforce that CHECK constraints contain only
1586  * immutable functions, so it's necessary to check here. We daren't draw
1587  * conclusions from plan-time evaluation of non-immutable functions. Since
1588  * they're ANDed, we can just ignore any mutable constraints in the list,
1589  * and reason about the rest.
1590  */
1591  safe_constraints = NIL;
1592  foreach(lc, constraint_pred)
1593  {
1594  Node *pred = (Node *) lfirst(lc);
1595 
1596  if (!contain_mutable_functions(pred))
1597  safe_constraints = lappend(safe_constraints, pred);
1598  }
1599 
1600  /*
1601  * The constraints are effectively ANDed together, so we can just try to
1602  * refute the entire collection at once. This may allow us to make proofs
1603  * that would fail if we took them individually.
1604  *
1605  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1606  * an obvious optimization. Some of the clauses might be OR clauses that
1607  * have volatile and nonvolatile subclauses, and it's OK to make
1608  * deductions with the nonvolatile parts.
1609  *
1610  * We need strong refutation because we have to prove that the constraints
1611  * would yield false, not just NULL.
1612  */
1613  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1614  return true;
1615 
1616  return false;
1617 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
RelOptKind reloptkind
Definition: pathnodes.h:673
List * baserestrictinfo
Definition: pathnodes.h:740
int constraint_exclusion
Definition: plancat.c:57
Definition: nodes.h:539
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:649
#define linitial(l)
Definition: pg_list.h:174
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:221
#define DatumGetBool(X)
Definition: postgres.h:437
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
RTEKind rtekind
Definition: parsenodes.h:995
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
Definition: plancat.c:1179
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:359
Definition: pg_list.h:50

◆ restriction_selectivity()

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

Definition at line 1825 of file plancat.c.

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

Referenced by clause_selectivity_ext(), rowcomparesel(), and test_support_func().

1830 {
1831  RegProcedure oprrest = get_oprrest(operatorid);
1832  float8 result;
1833 
1834  /*
1835  * if the oprrest procedure is missing for whatever reason, use a
1836  * selectivity of 0.5
1837  */
1838  if (!oprrest)
1839  return (Selectivity) 0.5;
1840 
1841  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1842  inputcollid,
1843  PointerGetDatum(root),
1844  ObjectIdGetDatum(operatorid),
1845  PointerGetDatum(args),
1846  Int32GetDatum(varRelid)));
1847 
1848  if (result < 0.0 || result > 1.0)
1849  elog(ERROR, "invalid restriction selectivity: %f", result);
1850 
1851  return (Selectivity) result;
1852 }
#define PointerGetDatum(X)
Definition: postgres.h:600
regproc RegProcedure
Definition: c.h:585
double Selectivity
Definition: nodes.h:672
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
double float8
Definition: c.h:565
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1528
#define DatumGetFloat8(X)
Definition: postgres.h:758
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1441
#define Int32GetDatum(X)
Definition: postgres.h:523
#define elog(elevel,...)
Definition: elog.h:232

Variable Documentation

◆ get_relation_info_hook

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook

Definition at line 60 of file plancat.c.

Referenced by get_relation_info().