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)
 
Bitmapsetget_dependent_generated_columns (PlannerInfo *root, Index rti, Bitmapset *target_cols)
 

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

2074 {
2075  HeapTuple proctup;
2076  Form_pg_proc procform;
2077 
2078  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2079  if (!HeapTupleIsValid(proctup))
2080  elog(ERROR, "cache lookup failed for function %u", funcid);
2081  procform = (Form_pg_proc) GETSTRUCT(proctup);
2082 
2083  if (OidIsValid(procform->prosupport))
2084  {
2085  SupportRequestCost req;
2086  SupportRequestCost *sresult;
2087 
2088  req.type = T_SupportRequestCost;
2089  req.root = root;
2090  req.funcid = funcid;
2091  req.node = node;
2092 
2093  /* Initialize cost fields so that support function doesn't have to */
2094  req.startup = 0;
2095  req.per_tuple = 0;
2096 
2097  sresult = (SupportRequestCost *)
2098  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2099  PointerGetDatum(&req)));
2100 
2101  if (sresult == &req)
2102  {
2103  /* Success, so accumulate support function's estimate into *cost */
2104  cost->startup += req.startup;
2105  cost->per_tuple += req.per_tuple;
2106  ReleaseSysCache(proctup);
2107  return;
2108  }
2109  }
2110 
2111  /* No support function, or it failed, so rely on procost */
2112  cost->per_tuple += procform->procost * cpu_operator_cost;
2113 
2114  ReleaseSysCache(proctup);
2115 }
#define OidIsValid(objectId)
Definition: c.h:775
double cpu_operator_cost
Definition: costsize.c:123
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
tree ctl root
Definition: radixtree.h:1884
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47
struct PlannerInfo * root
Definition: supportnodes.h:136
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218

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

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

◆ build_physical_tlist()

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1747 of file plancat.c.

1748 {
1749  List *tlist = NIL;
1750  Index varno = rel->relid;
1751  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1752  Relation relation;
1753  Query *subquery;
1754  Var *var;
1755  ListCell *l;
1756  int attrno,
1757  numattrs;
1758  List *colvars;
1759 
1760  switch (rte->rtekind)
1761  {
1762  case RTE_RELATION:
1763  /* Assume we already have adequate lock */
1764  relation = table_open(rte->relid, NoLock);
1765 
1766  numattrs = RelationGetNumberOfAttributes(relation);
1767  for (attrno = 1; attrno <= numattrs; attrno++)
1768  {
1769  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1770  attrno - 1);
1771 
1772  if (att_tup->attisdropped || att_tup->atthasmissing)
1773  {
1774  /* found a dropped or missing col, so punt */
1775  tlist = NIL;
1776  break;
1777  }
1778 
1779  var = makeVar(varno,
1780  attrno,
1781  att_tup->atttypid,
1782  att_tup->atttypmod,
1783  att_tup->attcollation,
1784  0);
1785 
1786  tlist = lappend(tlist,
1787  makeTargetEntry((Expr *) var,
1788  attrno,
1789  NULL,
1790  false));
1791  }
1792 
1793  table_close(relation, NoLock);
1794  break;
1795 
1796  case RTE_SUBQUERY:
1797  subquery = rte->subquery;
1798  foreach(l, subquery->targetList)
1799  {
1800  TargetEntry *tle = (TargetEntry *) lfirst(l);
1801 
1802  /*
1803  * A resjunk column of the subquery can be reflected as
1804  * resjunk in the physical tlist; we need not punt.
1805  */
1806  var = makeVarFromTargetEntry(varno, tle);
1807 
1808  tlist = lappend(tlist,
1809  makeTargetEntry((Expr *) var,
1810  tle->resno,
1811  NULL,
1812  tle->resjunk));
1813  }
1814  break;
1815 
1816  case RTE_FUNCTION:
1817  case RTE_TABLEFUNC:
1818  case RTE_VALUES:
1819  case RTE_CTE:
1820  case RTE_NAMEDTUPLESTORE:
1821  case RTE_RESULT:
1822  /* Not all of these can have dropped cols, but share code anyway */
1823  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1824  NULL, &colvars);
1825  foreach(l, colvars)
1826  {
1827  var = (Var *) lfirst(l);
1828 
1829  /*
1830  * A non-Var in expandRTE's output means a dropped column;
1831  * must punt.
1832  */
1833  if (!IsA(var, Var))
1834  {
1835  tlist = NIL;
1836  break;
1837  }
1838 
1839  tlist = lappend(tlist,
1840  makeTargetEntry((Expr *) var,
1841  var->varattno,
1842  NULL,
1843  false));
1844  }
1845  break;
1846 
1847  default:
1848  /* caller error */
1849  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1850  (int) rte->rtekind);
1851  break;
1852  }
1853 
1854  return tlist;
1855 }
unsigned int Index
Definition: c.h:614
List * lappend(List *list, void *datum)
Definition: list.c:339
#define NoLock
Definition: lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:105
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_CTE
Definition: parsenodes.h:1034
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1035
@ RTE_VALUES
Definition: parsenodes.h:1033
@ RTE_SUBQUERY
Definition: parsenodes.h:1029
@ RTE_RESULT
Definition: parsenodes.h:1036
@ RTE_FUNCTION
Definition: parsenodes.h:1031
@ RTE_TABLEFUNC
Definition: parsenodes.h:1032
@ RTE_RELATION
Definition: parsenodes.h:1028
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:560
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:511
Definition: pg_list.h:54
List * targetList
Definition: parsenodes.h:191
Query * subquery
Definition: parsenodes.h:1114
RTEKind rtekind
Definition: parsenodes.h:1057
Index relid
Definition: pathnodes.h:908
TupleDesc rd_att
Definition: rel.h:112
AttrNumber resno
Definition: primnodes.h:2164
Definition: primnodes.h:248
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References elog, ERROR, expandRTE(), IsA, lappend(), lfirst, makeTargetEntry(), makeVar(), makeVarFromTargetEntry(), NIL, NoLock, planner_rt_fetch, RelationData::rd_att, RelationGetNumberOfAttributes, RangeTblEntry::relid, RelOptInfo::relid, TargetEntry::resno, root, 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().

◆ estimate_rel_size()

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

Definition at line 1041 of file plancat.c.

1043 {
1044  BlockNumber curpages;
1045  BlockNumber relpages;
1046  double reltuples;
1047  BlockNumber relallvisible;
1048  double density;
1049 
1050  if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
1051  {
1052  table_relation_estimate_size(rel, attr_widths, pages, tuples,
1053  allvisfrac);
1054  }
1055  else if (rel->rd_rel->relkind == RELKIND_INDEX)
1056  {
1057  /*
1058  * XXX: It'd probably be good to move this into a callback, individual
1059  * index types e.g. know if they have a metapage.
1060  */
1061 
1062  /* it has storage, ok to call the smgr */
1063  curpages = RelationGetNumberOfBlocks(rel);
1064 
1065  /* report estimated # pages */
1066  *pages = curpages;
1067  /* quick exit if rel is clearly empty */
1068  if (curpages == 0)
1069  {
1070  *tuples = 0;
1071  *allvisfrac = 0;
1072  return;
1073  }
1074 
1075  /* coerce values in pg_class to more desirable types */
1076  relpages = (BlockNumber) rel->rd_rel->relpages;
1077  reltuples = (double) rel->rd_rel->reltuples;
1078  relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
1079 
1080  /*
1081  * Discount the metapage while estimating the number of tuples. This
1082  * is a kluge because it assumes more than it ought to about index
1083  * structure. Currently it's OK for btree, hash, and GIN indexes but
1084  * suspect for GiST indexes.
1085  */
1086  if (relpages > 0)
1087  {
1088  curpages--;
1089  relpages--;
1090  }
1091 
1092  /* estimate number of tuples from previous tuple density */
1093  if (reltuples >= 0 && relpages > 0)
1094  density = reltuples / (double) relpages;
1095  else
1096  {
1097  /*
1098  * If we have no data because the relation was never vacuumed,
1099  * estimate tuple width from attribute datatypes. We assume here
1100  * that the pages are completely full, which is OK for tables
1101  * (since they've presumably not been VACUUMed yet) but is
1102  * probably an overestimate for indexes. Fortunately
1103  * get_relation_info() can clamp the overestimate to the parent
1104  * table's size.
1105  *
1106  * Note: this code intentionally disregards alignment
1107  * considerations, because (a) that would be gilding the lily
1108  * considering how crude the estimate is, and (b) it creates
1109  * platform dependencies in the default plans which are kind of a
1110  * headache for regression testing.
1111  *
1112  * XXX: Should this logic be more index specific?
1113  */
1114  int32 tuple_width;
1115 
1116  tuple_width = get_rel_data_width(rel, attr_widths);
1117  tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1118  tuple_width += sizeof(ItemIdData);
1119  /* note: integer division is intentional here */
1120  density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1121  }
1122  *tuples = rint(density * (double) curpages);
1123 
1124  /*
1125  * We use relallvisible as-is, rather than scaling it up like we do
1126  * for the pages and tuples counts, on the theory that any pages added
1127  * since the last VACUUM are most likely not marked all-visible. But
1128  * costsize.c wants it converted to a fraction.
1129  */
1130  if (relallvisible == 0 || curpages <= 0)
1131  *allvisfrac = 0;
1132  else if ((double) relallvisible >= curpages)
1133  *allvisfrac = 1;
1134  else
1135  *allvisfrac = (double) relallvisible / curpages;
1136  }
1137  else
1138  {
1139  /*
1140  * Just use whatever's in pg_class. This covers foreign tables,
1141  * sequences, and also relkinds without storage (shouldn't get here?);
1142  * see initializations in AddNewRelationTuple(). Note that FDW must
1143  * cope if reltuples is -1!
1144  */
1145  *pages = rel->rd_rel->relpages;
1146  *tuples = rel->rd_rel->reltuples;
1147  *allvisfrac = 0;
1148  }
1149 }
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:281
#define SizeOfPageHeaderData
Definition: bufpage.h:213
#define MAXALIGN(LEN)
Definition: c.h:811
signed int int32
Definition: c.h:494
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
struct ItemIdData ItemIdData
int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1166
Form_pg_class rd_rel
Definition: rel.h:111
static void table_relation_estimate_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: tableam.h:1947

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

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

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

2018 {
2019  RegProcedure prosupport = get_func_support(funcid);
2021  SupportRequestSelectivity *sresult;
2022 
2023  /*
2024  * If no support function is provided, use our historical default
2025  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
2026  * Postgres has been using that estimate for function calls since 1992.
2027  * The hoariness of this behavior suggests that we should not be in too
2028  * much hurry to use another value.
2029  */
2030  if (!prosupport)
2031  return (Selectivity) 0.3333333;
2032 
2033  req.type = T_SupportRequestSelectivity;
2034  req.root = root;
2035  req.funcid = funcid;
2036  req.args = args;
2037  req.inputcollid = inputcollid;
2038  req.is_join = is_join;
2039  req.varRelid = varRelid;
2040  req.jointype = jointype;
2041  req.sjinfo = sjinfo;
2042  req.selectivity = -1; /* to catch failure to set the value */
2043 
2044  sresult = (SupportRequestSelectivity *)
2045  DatumGetPointer(OidFunctionCall1(prosupport,
2046  PointerGetDatum(&req)));
2047 
2048  /* If support function fails, use default */
2049  if (sresult != &req)
2050  return (Selectivity) 0.3333333;
2051 
2052  if (req.selectivity < 0.0 || req.selectivity > 1.0)
2053  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2054 
2055  return (Selectivity) req.selectivity;
2056 }
regproc RegProcedure
Definition: c.h:650
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1858
double Selectivity
Definition: nodes.h:250
struct PlannerInfo * root
Definition: supportnodes.h:96
struct SpecialJoinInfo * sjinfo
Definition: supportnodes.h:103

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

Referenced by clause_selectivity_ext().

◆ get_dependent_generated_columns()

Bitmapset* get_dependent_generated_columns ( PlannerInfo root,
Index  rti,
Bitmapset target_cols 
)

Definition at line 2300 of file plancat.c.

2302 {
2303  Bitmapset *dependentCols = NULL;
2304  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2305  Relation relation;
2306  TupleDesc tupdesc;
2307  TupleConstr *constr;
2308 
2309  /* Assume we already have adequate lock */
2310  relation = table_open(rte->relid, NoLock);
2311 
2312  tupdesc = RelationGetDescr(relation);
2313  constr = tupdesc->constr;
2314 
2315  if (constr && constr->has_generated_stored)
2316  {
2317  for (int i = 0; i < constr->num_defval; i++)
2318  {
2319  AttrDefault *defval = &constr->defval[i];
2320  Node *expr;
2321  Bitmapset *attrs_used = NULL;
2322 
2323  /* skip if not generated column */
2324  if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
2325  continue;
2326 
2327  /* identify columns this generated column depends on */
2328  expr = stringToNode(defval->adbin);
2329  pull_varattnos(expr, 1, &attrs_used);
2330 
2331  if (bms_overlap(target_cols, attrs_used))
2332  dependentCols = bms_add_member(dependentCols,
2334  }
2335  }
2336 
2337  table_close(relation, NoLock);
2338 
2339  return dependentCols;
2340 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
int i
Definition: isn.c:73
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetDescr(relation)
Definition: rel.h:531
AttrNumber adnum
Definition: tupdesc.h:24
char * adbin
Definition: tupdesc.h:25
Definition: nodes.h:129
AttrDefault * defval
Definition: tupdesc.h:39
bool has_generated_stored
Definition: tupdesc.h:45
uint16 num_defval
Definition: tupdesc.h:42
TupleConstr * constr
Definition: tupdesc.h:85
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:291

References AttrDefault::adbin, AttrDefault::adnum, bms_add_member(), bms_overlap(), TupleDescData::constr, TupleConstr::defval, FirstLowInvalidHeapAttributeNumber, TupleConstr::has_generated_stored, i, NoLock, TupleConstr::num_defval, planner_rt_fetch, pull_varattnos(), RelationGetDescr, RangeTblEntry::relid, root, stringToNode(), table_close(), table_open(), and TupleDescAttr.

Referenced by get_rel_all_updated_cols().

◆ get_function_rows()

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

Definition at line 2133 of file plancat.c.

2134 {
2135  HeapTuple proctup;
2136  Form_pg_proc procform;
2137  double result;
2138 
2139  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2140  if (!HeapTupleIsValid(proctup))
2141  elog(ERROR, "cache lookup failed for function %u", funcid);
2142  procform = (Form_pg_proc) GETSTRUCT(proctup);
2143 
2144  Assert(procform->proretset); /* else caller error */
2145 
2146  if (OidIsValid(procform->prosupport))
2147  {
2148  SupportRequestRows req;
2149  SupportRequestRows *sresult;
2150 
2151  req.type = T_SupportRequestRows;
2152  req.root = root;
2153  req.funcid = funcid;
2154  req.node = node;
2155 
2156  req.rows = 0; /* just for sanity */
2157 
2158  sresult = (SupportRequestRows *)
2159  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2160  PointerGetDatum(&req)));
2161 
2162  if (sresult == &req)
2163  {
2164  /* Success */
2165  ReleaseSysCache(proctup);
2166  return req.rows;
2167  }
2168  }
2169 
2170  /* No support function, or it failed, so rely on prorows */
2171  result = procform->prorows;
2172 
2173  ReleaseSysCache(proctup);
2174 
2175  return result;
2176 }
#define Assert(condition)
Definition: c.h:858
struct PlannerInfo * root
Definition: supportnodes.h:163

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

Referenced by expression_returns_set_rows().

◆ get_rel_data_width()

int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)

Definition at line 1166 of file plancat.c.

1167 {
1168  int64 tuple_width = 0;
1169  int i;
1170 
1171  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1172  {
1173  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1174  int32 item_width;
1175 
1176  if (att->attisdropped)
1177  continue;
1178 
1179  /* use previously cached data, if any */
1180  if (attr_widths != NULL && attr_widths[i] > 0)
1181  {
1182  tuple_width += attr_widths[i];
1183  continue;
1184  }
1185 
1186  /* This should match set_rel_width() in costsize.c */
1187  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1188  if (item_width <= 0)
1189  {
1190  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1191  Assert(item_width > 0);
1192  }
1193  if (attr_widths != NULL)
1194  attr_widths[i] = item_width;
1195  tuple_width += item_width;
1196  }
1197 
1198  return clamp_width_est(tuple_width);
1199 }
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:231
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3158
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2578
#define RelationGetRelid(relation)
Definition: rel.h:505

References Assert, clamp_width_est(), 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().

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1208 of file plancat.c.

1209 {
1210  int32 result;
1211  Relation relation;
1212 
1213  /* As above, assume relation is already locked */
1214  relation = table_open(relid, NoLock);
1215 
1216  result = get_rel_data_width(relation, attr_widths);
1217 
1218  table_close(relation, NoLock);
1219 
1220  return result;
1221 }

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

◆ get_relation_info()

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

Definition at line 115 of file plancat.c.

117 {
118  Index varno = rel->relid;
119  Relation relation;
120  bool hasindex;
121  List *indexinfos = NIL;
122 
123  /*
124  * We need not lock the relation since it was already locked, either by
125  * the rewriter or when expand_inherited_rtentry() added it to the query's
126  * rangetable.
127  */
128  relation = table_open(relationObjectId, NoLock);
129 
130  /*
131  * Relations without a table AM can be used in a query only if they are of
132  * special-cased relkinds. This check prevents us from crashing later if,
133  * for example, a view's ON SELECT rule has gone missing. Note that
134  * table_open() already rejected indexes and composite types; spell the
135  * error the same way it does.
136  */
137  if (!relation->rd_tableam)
138  {
139  if (!(relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE ||
140  relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
141  ereport(ERROR,
142  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
143  errmsg("cannot open relation \"%s\"",
144  RelationGetRelationName(relation)),
145  errdetail_relkind_not_supported(relation->rd_rel->relkind)));
146  }
147 
148  /* Temporary and unlogged relations are inaccessible during recovery. */
149  if (!RelationIsPermanent(relation) && RecoveryInProgress())
150  ereport(ERROR,
151  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
152  errmsg("cannot access temporary or unlogged relations during recovery")));
153 
155  rel->max_attr = RelationGetNumberOfAttributes(relation);
156  rel->reltablespace = RelationGetForm(relation)->reltablespace;
157 
158  Assert(rel->max_attr >= rel->min_attr);
159  rel->attr_needed = (Relids *)
160  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
161  rel->attr_widths = (int32 *)
162  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
163 
164  /*
165  * Record which columns are defined as NOT NULL. We leave this
166  * unpopulated for non-partitioned inheritance parent relations as it's
167  * ambiguous as to what it means. Some child tables may have a NOT NULL
168  * constraint for a column while others may not. We could work harder and
169  * build a unioned set of all child relations notnullattnums, but there's
170  * currently no need. The RelOptInfo corresponding to the !inh
171  * RangeTblEntry does get populated.
172  */
173  if (!inhparent || relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
174  {
175  for (int i = 0; i < relation->rd_att->natts; i++)
176  {
177  FormData_pg_attribute *attr = &relation->rd_att->attrs[i];
178 
179  if (attr->attnotnull)
180  {
182  attr->attnum);
183 
184  /*
185  * Per RemoveAttributeById(), dropped columns will have their
186  * attnotnull unset, so we needn't check for dropped columns
187  * in the above condition.
188  */
189  Assert(!attr->attisdropped);
190  }
191  }
192  }
193 
194  /*
195  * Estimate relation size --- unless it's an inheritance parent, in which
196  * case the size we want is not the rel's own size but the size of its
197  * inheritance tree. That will be computed in set_append_rel_size().
198  */
199  if (!inhparent)
200  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
201  &rel->pages, &rel->tuples, &rel->allvisfrac);
202 
203  /* Retrieve the parallel_workers reloption, or -1 if not set. */
205 
206  /*
207  * Make list of indexes. Ignore indexes on system catalogs if told to.
208  * Don't bother with indexes from traditional inheritance parents. For
209  * partitioned tables, we need a list of at least unique indexes as these
210  * serve as unique proofs for certain planner optimizations. However,
211  * let's not discriminate here and just record all partitioned indexes
212  * whether they're unique indexes or not.
213  */
214  if ((inhparent && relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
215  || (IgnoreSystemIndexes && IsSystemRelation(relation)))
216  hasindex = false;
217  else
218  hasindex = relation->rd_rel->relhasindex;
219 
220  if (hasindex)
221  {
222  List *indexoidlist;
223  LOCKMODE lmode;
224  ListCell *l;
225 
226  indexoidlist = RelationGetIndexList(relation);
227 
228  /*
229  * For each index, we get the same type of lock that the executor will
230  * need, and do not release it. This saves a couple of trips to the
231  * shared lock manager while not creating any real loss of
232  * concurrency, because no schema changes could be happening on the
233  * index while we hold lock on the parent rel, and no lock type used
234  * for queries blocks any other kind of index operation.
235  */
236  lmode = root->simple_rte_array[varno]->rellockmode;
237 
238  foreach(l, indexoidlist)
239  {
240  Oid indexoid = lfirst_oid(l);
241  Relation indexRelation;
243  IndexAmRoutine *amroutine;
244  IndexOptInfo *info;
245  int ncolumns,
246  nkeycolumns;
247  int i;
248 
249  /*
250  * Extract info from the relation descriptor for the index.
251  */
252  indexRelation = index_open(indexoid, lmode);
253  index = indexRelation->rd_index;
254 
255  /*
256  * Ignore invalid indexes, since they can't safely be used for
257  * queries. Note that this is OK because the data structure we
258  * are constructing is only used by the planner --- the executor
259  * still needs to insert into "invalid" indexes, if they're marked
260  * indisready.
261  */
262  if (!index->indisvalid)
263  {
264  index_close(indexRelation, NoLock);
265  continue;
266  }
267 
268  /*
269  * If the index is valid, but cannot yet be used, ignore it; but
270  * mark the plan we are generating as transient. See
271  * src/backend/access/heap/README.HOT for discussion.
272  */
273  if (index->indcheckxmin &&
276  {
277  root->glob->transientPlan = true;
278  index_close(indexRelation, NoLock);
279  continue;
280  }
281 
282  info = makeNode(IndexOptInfo);
283 
284  info->indexoid = index->indexrelid;
285  info->reltablespace =
286  RelationGetForm(indexRelation)->reltablespace;
287  info->rel = rel;
288  info->ncolumns = ncolumns = index->indnatts;
289  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
290 
291  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
292  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
293  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
294  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
295  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
296 
297  for (i = 0; i < ncolumns; i++)
298  {
299  info->indexkeys[i] = index->indkey.values[i];
300  info->canreturn[i] = index_can_return(indexRelation, i + 1);
301  }
302 
303  for (i = 0; i < nkeycolumns; i++)
304  {
305  info->opfamily[i] = indexRelation->rd_opfamily[i];
306  info->opcintype[i] = indexRelation->rd_opcintype[i];
307  info->indexcollations[i] = indexRelation->rd_indcollation[i];
308  }
309 
310  info->relam = indexRelation->rd_rel->relam;
311 
312  /*
313  * We don't have an AM for partitioned indexes, so we'll just
314  * NULLify the AM related fields for those.
315  */
316  if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
317  {
318  /* We copy just the fields we need, not all of rd_indam */
319  amroutine = indexRelation->rd_indam;
320  info->amcanorderbyop = amroutine->amcanorderbyop;
321  info->amoptionalkey = amroutine->amoptionalkey;
322  info->amsearcharray = amroutine->amsearcharray;
323  info->amsearchnulls = amroutine->amsearchnulls;
324  info->amcanparallel = amroutine->amcanparallel;
325  info->amhasgettuple = (amroutine->amgettuple != NULL);
326  info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
327  relation->rd_tableam->scan_bitmap_next_block != NULL;
328  info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
329  amroutine->amrestrpos != NULL);
330  info->amcostestimate = amroutine->amcostestimate;
331  Assert(info->amcostestimate != NULL);
332 
333  /* Fetch index opclass options */
334  info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
335 
336  /*
337  * Fetch the ordering information for the index, if any.
338  */
339  if (info->relam == BTREE_AM_OID)
340  {
341  /*
342  * If it's a btree index, we can use its opfamily OIDs
343  * directly as the sort ordering opfamily OIDs.
344  */
345  Assert(amroutine->amcanorder);
346 
347  info->sortopfamily = info->opfamily;
348  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
349  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
350 
351  for (i = 0; i < nkeycolumns; i++)
352  {
353  int16 opt = indexRelation->rd_indoption[i];
354 
355  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
356  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
357  }
358  }
359  else if (amroutine->amcanorder)
360  {
361  /*
362  * Otherwise, identify the corresponding btree opfamilies
363  * by trying to map this index's "<" operators into btree.
364  * Since "<" uniquely defines the behavior of a sort
365  * order, this is a sufficient test.
366  *
367  * XXX This method is rather slow and also requires the
368  * undesirable assumption that the other index AM numbers
369  * its strategies the same as btree. It'd be better to
370  * have a way to explicitly declare the corresponding
371  * btree opfamily for each opfamily of the other index
372  * type. But given the lack of current or foreseeable
373  * amcanorder index types, it's not worth expending more
374  * effort on now.
375  */
376  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
377  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
378  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
379 
380  for (i = 0; i < nkeycolumns; i++)
381  {
382  int16 opt = indexRelation->rd_indoption[i];
383  Oid ltopr;
384  Oid btopfamily;
385  Oid btopcintype;
386  int16 btstrategy;
387 
388  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
389  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
390 
391  ltopr = get_opfamily_member(info->opfamily[i],
392  info->opcintype[i],
393  info->opcintype[i],
395  if (OidIsValid(ltopr) &&
397  &btopfamily,
398  &btopcintype,
399  &btstrategy) &&
400  btopcintype == info->opcintype[i] &&
401  btstrategy == BTLessStrategyNumber)
402  {
403  /* Successful mapping */
404  info->sortopfamily[i] = btopfamily;
405  }
406  else
407  {
408  /* Fail ... quietly treat index as unordered */
409  info->sortopfamily = NULL;
410  info->reverse_sort = NULL;
411  info->nulls_first = NULL;
412  break;
413  }
414  }
415  }
416  else
417  {
418  info->sortopfamily = NULL;
419  info->reverse_sort = NULL;
420  info->nulls_first = NULL;
421  }
422  }
423  else
424  {
425  info->amcanorderbyop = false;
426  info->amoptionalkey = false;
427  info->amsearcharray = false;
428  info->amsearchnulls = false;
429  info->amcanparallel = false;
430  info->amhasgettuple = false;
431  info->amhasgetbitmap = false;
432  info->amcanmarkpos = false;
433  info->amcostestimate = NULL;
434 
435  info->sortopfamily = NULL;
436  info->reverse_sort = NULL;
437  info->nulls_first = NULL;
438  }
439 
440  /*
441  * Fetch the index expressions and predicate, if any. We must
442  * modify the copies we obtain from the relcache to have the
443  * correct varno for the parent relation, so that they match up
444  * correctly against qual clauses.
445  */
446  info->indexprs = RelationGetIndexExpressions(indexRelation);
447  info->indpred = RelationGetIndexPredicate(indexRelation);
448  if (info->indexprs && varno != 1)
449  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
450  if (info->indpred && varno != 1)
451  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
452 
453  /* Build targetlist using the completed indexprs data */
454  info->indextlist = build_index_tlist(root, info, relation);
455 
456  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
457  info->predOK = false; /* set later, in indxpath.c */
458  info->unique = index->indisunique;
459  info->immediate = index->indimmediate;
460  info->hypothetical = false;
461 
462  /*
463  * Estimate the index size. If it's not a partial index, we lock
464  * the number-of-tuples estimate to equal the parent table; if it
465  * is partial then we have to use the same methods as we would for
466  * a table, except we can be sure that the index is not larger
467  * than the table. We must ignore partitioned indexes here as
468  * there are not physical indexes.
469  */
470  if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
471  {
472  if (info->indpred == NIL)
473  {
474  info->pages = RelationGetNumberOfBlocks(indexRelation);
475  info->tuples = rel->tuples;
476  }
477  else
478  {
479  double allvisfrac; /* dummy */
480 
481  estimate_rel_size(indexRelation, NULL,
482  &info->pages, &info->tuples, &allvisfrac);
483  if (info->tuples > rel->tuples)
484  info->tuples = rel->tuples;
485  }
486 
487  if (info->relam == BTREE_AM_OID)
488  {
489  /*
490  * For btrees, get tree height while we have the index
491  * open
492  */
493  info->tree_height = _bt_getrootheight(indexRelation);
494  }
495  else
496  {
497  /* For other index types, just set it to "unknown" for now */
498  info->tree_height = -1;
499  }
500  }
501  else
502  {
503  /* Zero these out for partitioned indexes */
504  info->pages = 0;
505  info->tuples = 0.0;
506  info->tree_height = -1;
507  }
508 
509  index_close(indexRelation, NoLock);
510 
511  /*
512  * We've historically used lcons() here. It'd make more sense to
513  * use lappend(), but that causes the planner to change behavior
514  * in cases where two indexes seem equally attractive. For now,
515  * stick with lcons() --- few tables should have so many indexes
516  * that the O(N^2) behavior of lcons() is really a problem.
517  */
518  indexinfos = lcons(info, indexinfos);
519  }
520 
521  list_free(indexoidlist);
522  }
523 
524  rel->indexlist = indexinfos;
525 
526  rel->statlist = get_relation_statistics(rel, relation);
527 
528  /* Grab foreign-table info using the relcache, while we have it */
529  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
530  {
532  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
533  }
534  else
535  {
536  rel->serverid = InvalidOid;
537  rel->fdwroutine = NULL;
538  }
539 
540  /* Collect info about relation's foreign keys, if relevant */
541  get_relation_foreign_keys(root, rel, relation, inhparent);
542 
543  /* Collect info about functions implemented by the rel's table AM. */
544  if (relation->rd_tableam &&
545  relation->rd_tableam->scan_set_tidrange != NULL &&
546  relation->rd_tableam->scan_getnextslot_tidrange != NULL)
548 
549  /*
550  * Collect info about relation's partitioning scheme, if any. Only
551  * inheritance parents may be partitioned.
552  */
553  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
554  set_relation_partition_info(root, rel, relation);
555 
556  table_close(relation, NoLock);
557 
558  /*
559  * Allow a plugin to editorialize on the info we obtained from the
560  * catalogs. Actions might include altering the assumed relation size,
561  * removing an index, or adding a hypothetical index to the indexlist.
562  */
564  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
565 }
signed short int16
Definition: c.h:493
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ereport(elevel,...)
Definition: elog.h:149
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:432
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:345
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:309
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:788
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
void list_free(List *list)
Definition: list.c:1546
List * lcons(void *datum, List *list)
Definition: list.c:495
int LOCKMODE
Definition: lockdefs.h:26
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:166
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:207
void * palloc0(Size size)
Definition: mcxt.c:1346
void * palloc(Size size)
Definition: mcxt.c:1316
bool IgnoreSystemIndexes
Definition: miscinit.c:80
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:675
#define makeNode(_type_)
Definition: nodes.h:155
Bitmapset * Relids
Definition: pathnodes.h:30
#define AMFLAG_HAS_TID_RANGE
Definition: pathnodes.h:813
FormData_pg_attribute
Definition: pg_attribute.h:193
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
FormData_pg_index * Form_pg_index
Definition: pg_index.h:70
#define lfirst_oid(lc)
Definition: pg_list.h:174
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:1041
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:578
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:59
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1868
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1451
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:2348
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetForm(relation)
Definition: rel.h:499
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:397
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationIsPermanent(relation)
Definition: rel.h:617
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4760
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5138
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5884
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:5025
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:674
TransactionId TransactionXmin
Definition: snapmgr.c:98
#define BTLessStrategyNumber
Definition: stratnum.h:29
HeapTupleHeader t_data
Definition: htup.h:68
amrestrpos_function amrestrpos
Definition: amapi.h:286
amcostestimate_function amcostestimate
Definition: amapi.h:274
bool amcanorderbyop
Definition: amapi.h:226
bool amoptionalkey
Definition: amapi.h:234
amgettuple_function amgettuple
Definition: amapi.h:282
amgetbitmap_function amgetbitmap
Definition: amapi.h:283
bool amsearcharray
Definition: amapi.h:236
ammarkpos_function ammarkpos
Definition: amapi.h:285
bool amcanparallel
Definition: amapi.h:246
bool amcanorder
Definition: amapi.h:224
bool amsearchnulls
Definition: amapi.h:238
bool amcanparallel
Definition: pathnodes.h:1194
bool amoptionalkey
Definition: pathnodes.h:1187
Oid reltablespace
Definition: pathnodes.h:1109
bool amcanmarkpos
Definition: pathnodes.h:1196
List * indrestrictinfo
Definition: pathnodes.h:1171
void(* amcostestimate)() pg_node_attr(read_write_ignore)
Definition: pathnodes.h:1199
bool amhasgettuple
Definition: pathnodes.h:1191
bool amcanorderbyop
Definition: pathnodes.h:1186
bool hypothetical
Definition: pathnodes.h:1180
List * indpred
Definition: pathnodes.h:1161
Cardinality tuples
Definition: pathnodes.h:1119
bool amsearcharray
Definition: pathnodes.h:1188
BlockNumber pages
Definition: pathnodes.h:1117
bool amsearchnulls
Definition: pathnodes.h:1189
bool amhasgetbitmap
Definition: pathnodes.h:1193
List * indextlist
Definition: pathnodes.h:1164
bool immediate
Definition: pathnodes.h:1178
uint32 amflags
Definition: pathnodes.h:948
Bitmapset * notnullattnums
Definition: pathnodes.h:926
List * statlist
Definition: pathnodes.h:936
Cardinality tuples
Definition: pathnodes.h:939
BlockNumber pages
Definition: pathnodes.h:938
List * indexlist
Definition: pathnodes.h:934
Oid reltablespace
Definition: pathnodes.h:910
Oid serverid
Definition: pathnodes.h:954
int rel_parallel_workers
Definition: pathnodes.h:946
AttrNumber max_attr
Definition: pathnodes.h:916
double allvisfrac
Definition: pathnodes.h:940
AttrNumber min_attr
Definition: pathnodes.h:914
const struct TableAmRoutine * rd_tableam
Definition: rel.h:189
struct IndexAmRoutine * rd_indam
Definition: rel.h:206
Oid * rd_opcintype
Definition: rel.h:208
struct HeapTupleData * rd_indextuple
Definition: rel.h:194
int16 * rd_indoption
Definition: rel.h:211
Form_pg_index rd_index
Definition: rel.h:192
Oid * rd_opfamily
Definition: rel.h:207
Oid * rd_indcollation
Definition: rel.h:217
bool(* scan_getnextslot_tidrange)(TableScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:380
void(* scan_set_tidrange)(TableScanDesc scan, ItemPointer mintid, ItemPointer maxtid)
Definition: tableam.h:372
bool(* scan_bitmap_next_block)(TableScanDesc scan, struct TBMIterateResult *tbmres)
Definition: tableam.h:823
FormData_pg_attribute attrs[FLEXIBLE_ARRAY_MEMBER]
Definition: tupdesc.h:87
Definition: type.h:95
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
bool RecoveryInProgress(void)
Definition: xlog.c:6290

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, TupleDescData::attrs, bms_add_member(), BTLessStrategyNumber, build_index_tlist(), ChangeVarNodes(), ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, estimate_rel_size(), FirstLowInvalidHeapAttributeNumber, FormData_pg_attribute, get_opfamily_member(), get_ordering_op_properties(), get_relation_foreign_keys(), get_relation_info_hook, get_relation_statistics(), GetFdwRoutineForRelation(), GetForeignServerIdByRelId(), HeapTupleHeaderGetXmin, IndexOptInfo::hypothetical, i, IgnoreSystemIndexes, IndexOptInfo::immediate, index_can_return(), index_close(), index_open(), RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indextlist, IndexOptInfo::indpred, IndexOptInfo::indrestrictinfo, InvalidOid, IsSystemRelation(), lcons(), lfirst_oid, list_free(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, TupleDescData::natts, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, NoLock, RelOptInfo::notnullattnums, OidIsValid, RelOptInfo::pages, IndexOptInfo::pages, palloc(), palloc0(), IndexOptInfo::predOK, RelationData::rd_att, 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(), RelOptInfo::rel_parallel_workers, IndexOptInfo::relam, RelationGetForm, RelationGetIndexAttOptions(), RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNumberOfAttributes, RelationGetNumberOfBlocks, RelationGetParallelWorkers, RelationGetRelationName, RelationGetRelid, RelationIsPermanent, RelOptInfo::relid, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, root, TableAmRoutine::scan_bitmap_next_block, TableAmRoutine::scan_getnextslot_tidrange, TableAmRoutine::scan_set_tidrange, RelOptInfo::serverid, set_relation_partition_info(), RelOptInfo::statlist, HeapTupleData::t_data, table_close(), table_open(), TransactionIdPrecedes(), TransactionXmin, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by build_simple_rel().

◆ has_row_triggers()

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

Definition at line 2223 of file plancat.c.

2224 {
2225  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2226  Relation relation;
2227  TriggerDesc *trigDesc;
2228  bool result = false;
2229 
2230  /* Assume we already have adequate lock */
2231  relation = table_open(rte->relid, NoLock);
2232 
2233  trigDesc = relation->trigdesc;
2234  switch (event)
2235  {
2236  case CMD_INSERT:
2237  if (trigDesc &&
2238  (trigDesc->trig_insert_after_row ||
2239  trigDesc->trig_insert_before_row))
2240  result = true;
2241  break;
2242  case CMD_UPDATE:
2243  if (trigDesc &&
2244  (trigDesc->trig_update_after_row ||
2245  trigDesc->trig_update_before_row))
2246  result = true;
2247  break;
2248  case CMD_DELETE:
2249  if (trigDesc &&
2250  (trigDesc->trig_delete_after_row ||
2251  trigDesc->trig_delete_before_row))
2252  result = true;
2253  break;
2254  /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2255  case CMD_MERGE:
2256  result = false;
2257  break;
2258  default:
2259  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2260  break;
2261  }
2262 
2263  table_close(relation, NoLock);
2264  return result;
2265 }
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
TriggerDesc * trigdesc
Definition: rel.h:117
bool trig_delete_before_row
Definition: reltrigger.h:66
bool trig_update_after_row
Definition: reltrigger.h:62
bool trig_insert_after_row
Definition: reltrigger.h:57
bool trig_update_before_row
Definition: reltrigger.h:61
bool trig_delete_after_row
Definition: reltrigger.h:67
bool trig_insert_before_row
Definition: reltrigger.h:56

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

◆ has_stored_generated_columns()

bool has_stored_generated_columns ( PlannerInfo root,
Index  rti 
)

Definition at line 2273 of file plancat.c.

2274 {
2275  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2276  Relation relation;
2277  TupleDesc tupdesc;
2278  bool result = false;
2279 
2280  /* Assume we already have adequate lock */
2281  relation = table_open(rte->relid, NoLock);
2282 
2283  tupdesc = RelationGetDescr(relation);
2284  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2285 
2286  table_close(relation, NoLock);
2287 
2288  return result;
2289 }

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

Referenced by make_modifytable().

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2191 of file plancat.c.

2192 {
2193  ListCell *ilist;
2194 
2195  foreach(ilist, rel->indexlist)
2196  {
2197  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2198 
2199  /*
2200  * Note: ignore partial indexes, since they don't allow us to conclude
2201  * that all attr values are distinct, *unless* they are marked predOK
2202  * which means we know the index's predicate is satisfied by the
2203  * query. We don't take any interest in expressional indexes either.
2204  * Also, a multicolumn unique index doesn't allow us to conclude that
2205  * just the specified attr is unique.
2206  */
2207  if (index->unique &&
2208  index->nkeycolumns == 1 &&
2209  index->indexkeys[0] == attno &&
2210  (index->indpred == NIL || index->predOK))
2211  return true;
2212  }
2213  return false;
2214 }

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 693 of file plancat.c.

694 {
695  OnConflictExpr *onconflict = root->parse->onConflict;
696 
697  /* Iteration state */
698  RangeTblEntry *rte;
699  Relation relation;
700  Oid indexOidFromConstraint = InvalidOid;
701  List *indexList;
702  ListCell *l;
703 
704  /* Normalized inference attributes and inference expressions: */
705  Bitmapset *inferAttrs = NULL;
706  List *inferElems = NIL;
707 
708  /* Results */
709  List *results = NIL;
710 
711  /*
712  * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
713  * specification or named constraint. ON CONFLICT DO UPDATE statements
714  * must always provide one or the other (but parser ought to have caught
715  * that already).
716  */
717  if (onconflict->arbiterElems == NIL &&
718  onconflict->constraint == InvalidOid)
719  return NIL;
720 
721  /*
722  * We need not lock the relation since it was already locked, either by
723  * the rewriter or when expand_inherited_rtentry() added it to the query's
724  * rangetable.
725  */
726  rte = rt_fetch(root->parse->resultRelation, root->parse->rtable);
727 
728  relation = table_open(rte->relid, NoLock);
729 
730  /*
731  * Build normalized/BMS representation of plain indexed attributes, as
732  * well as a separate list of expression items. This simplifies matching
733  * the cataloged definition of indexes.
734  */
735  foreach(l, onconflict->arbiterElems)
736  {
737  InferenceElem *elem = (InferenceElem *) lfirst(l);
738  Var *var;
739  int attno;
740 
741  if (!IsA(elem->expr, Var))
742  {
743  /* If not a plain Var, just shove it in inferElems for now */
744  inferElems = lappend(inferElems, elem->expr);
745  continue;
746  }
747 
748  var = (Var *) elem->expr;
749  attno = var->varattno;
750 
751  if (attno == 0)
752  ereport(ERROR,
753  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
754  errmsg("whole row unique index inference specifications are not supported")));
755 
756  inferAttrs = bms_add_member(inferAttrs,
758  }
759 
760  /*
761  * Lookup named constraint's index. This is not immediately returned
762  * because some additional sanity checks are required.
763  */
764  if (onconflict->constraint != InvalidOid)
765  {
766  indexOidFromConstraint = get_constraint_index(onconflict->constraint);
767 
768  if (indexOidFromConstraint == InvalidOid)
769  ereport(ERROR,
770  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
771  errmsg("constraint in ON CONFLICT clause has no associated index")));
772  }
773 
774  /*
775  * Using that representation, iterate through the list of indexes on the
776  * target relation to try and find a match
777  */
778  indexList = RelationGetIndexList(relation);
779 
780  foreach(l, indexList)
781  {
782  Oid indexoid = lfirst_oid(l);
783  Relation idxRel;
784  Form_pg_index idxForm;
785  Bitmapset *indexedAttrs;
786  List *idxExprs;
787  List *predExprs;
788  AttrNumber natt;
789  ListCell *el;
790 
791  /*
792  * Extract info from the relation descriptor for the index. Obtain
793  * the same lock type that the executor will ultimately use.
794  *
795  * Let executor complain about !indimmediate case directly, because
796  * enforcement needs to occur there anyway when an inference clause is
797  * omitted.
798  */
799  idxRel = index_open(indexoid, rte->rellockmode);
800  idxForm = idxRel->rd_index;
801 
802  if (!idxForm->indisvalid)
803  goto next;
804 
805  /*
806  * Note that we do not perform a check against indcheckxmin (like e.g.
807  * get_relation_info()) here to eliminate candidates, because
808  * uniqueness checking only cares about the most recently committed
809  * tuple versions.
810  */
811 
812  /*
813  * Look for match on "ON constraint_name" variant, which may not be
814  * unique constraint. This can only be a constraint name.
815  */
816  if (indexOidFromConstraint == idxForm->indexrelid)
817  {
818  if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
819  ereport(ERROR,
820  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
821  errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
822 
823  results = lappend_oid(results, idxForm->indexrelid);
824  list_free(indexList);
825  index_close(idxRel, NoLock);
826  table_close(relation, NoLock);
827  return results;
828  }
829  else if (indexOidFromConstraint != InvalidOid)
830  {
831  /* No point in further work for index in named constraint case */
832  goto next;
833  }
834 
835  /*
836  * Only considering conventional inference at this point (not named
837  * constraints), so index under consideration can be immediately
838  * skipped if it's not unique
839  */
840  if (!idxForm->indisunique)
841  goto next;
842 
843  /* Build BMS representation of plain (non expression) index attrs */
844  indexedAttrs = NULL;
845  for (natt = 0; natt < idxForm->indnkeyatts; natt++)
846  {
847  int attno = idxRel->rd_index->indkey.values[natt];
848 
849  if (attno != 0)
850  indexedAttrs = bms_add_member(indexedAttrs,
852  }
853 
854  /* Non-expression attributes (if any) must match */
855  if (!bms_equal(indexedAttrs, inferAttrs))
856  goto next;
857 
858  /* Expression attributes (if any) must match */
859  idxExprs = RelationGetIndexExpressions(idxRel);
860  foreach(el, onconflict->arbiterElems)
861  {
862  InferenceElem *elem = (InferenceElem *) lfirst(el);
863 
864  /*
865  * Ensure that collation/opclass aspects of inference expression
866  * element match. Even though this loop is primarily concerned
867  * with matching expressions, it is a convenient point to check
868  * this for both expressions and ordinary (non-expression)
869  * attributes appearing as inference elements.
870  */
871  if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
872  goto next;
873 
874  /*
875  * Plain Vars don't factor into count of expression elements, and
876  * the question of whether or not they satisfy the index
877  * definition has already been considered (they must).
878  */
879  if (IsA(elem->expr, Var))
880  continue;
881 
882  /*
883  * Might as well avoid redundant check in the rare cases where
884  * infer_collation_opclass_match() is required to do real work.
885  * Otherwise, check that element expression appears in cataloged
886  * index definition.
887  */
888  if (elem->infercollid != InvalidOid ||
889  elem->inferopclass != InvalidOid ||
890  list_member(idxExprs, elem->expr))
891  continue;
892 
893  goto next;
894  }
895 
896  /*
897  * Now that all inference elements were matched, ensure that the
898  * expression elements from inference clause are not missing any
899  * cataloged expressions. This does the right thing when unique
900  * indexes redundantly repeat the same attribute, or if attributes
901  * redundantly appear multiple times within an inference clause.
902  */
903  if (list_difference(idxExprs, inferElems) != NIL)
904  goto next;
905 
906  /*
907  * If it's a partial index, its predicate must be implied by the ON
908  * CONFLICT's WHERE clause.
909  */
910  predExprs = RelationGetIndexPredicate(idxRel);
911 
912  if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, false))
913  goto next;
914 
915  results = lappend_oid(results, idxForm->indexrelid);
916 next:
917  index_close(idxRel, NoLock);
918  }
919 
920  list_free(indexList);
921  table_close(relation, NoLock);
922 
923  if (results == NIL)
924  ereport(ERROR,
925  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
926  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
927 
928  return results;
929 }
int16 AttrNumber
Definition: attnum.h:21
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
static int32 next
Definition: blutils.c:221
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool list_member(const List *list, const void *datum)
Definition: list.c:661
List * list_difference(const List *list1, const List *list2)
Definition: list.c:1237
Oid get_constraint_index(Oid conoid)
Definition: lsyscache.c:1113
@ ONCONFLICT_UPDATE
Definition: nodes.h:419
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel, List *idxExprs)
Definition: plancat.c:959
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:152
List * arbiterElems
Definition: primnodes.h:2299
OnConflictAction action
Definition: primnodes.h:2296
Node * arbiterWhere
Definition: primnodes.h:2301
AttrNumber varattno
Definition: primnodes.h:260

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, bms_add_member(), bms_equal(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, InferenceElem::expr, FirstLowInvalidHeapAttributeNumber, get_constraint_index(), if(), 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, ONCONFLICT_UPDATE, predicate_implied_by(), RelationData::rd_index, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RangeTblEntry::relid, root, rt_fetch, table_close(), table_open(), and Var::varattno.

Referenced by make_modifytable().

◆ join_selectivity()

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

Definition at line 1969 of file plancat.c.

1975 {
1976  RegProcedure oprjoin = get_oprjoin(operatorid);
1977  float8 result;
1978 
1979  /*
1980  * if the oprjoin procedure is missing for whatever reason, use a
1981  * selectivity of 0.5
1982  */
1983  if (!oprjoin)
1984  return (Selectivity) 0.5;
1985 
1986  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1987  inputcollid,
1989  ObjectIdGetDatum(operatorid),
1991  Int16GetDatum(jointype),
1992  PointerGetDatum(sjinfo)));
1993 
1994  if (result < 0.0 || result > 1.0)
1995  elog(ERROR, "invalid join selectivity: %f", result);
1996 
1997  return (Selectivity) result;
1998 }
double float8
Definition: c.h:630
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1453
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1581
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:172
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:494

References generate_unaccent_rules::args, DatumGetFloat8(), elog, ERROR, get_oprjoin(), Int16GetDatum(), ObjectIdGetDatum(), OidFunctionCall5Coll(), PointerGetDatum(), and root.

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

◆ relation_excluded_by_constraints()

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

Definition at line 1557 of file plancat.c.

1559 {
1560  bool include_noinherit;
1561  bool include_notnull;
1562  bool include_partition = false;
1563  List *safe_restrictions;
1564  List *constraint_pred;
1565  List *safe_constraints;
1566  ListCell *lc;
1567 
1568  /* As of now, constraint exclusion works only with simple relations. */
1569  Assert(IS_SIMPLE_REL(rel));
1570 
1571  /*
1572  * If there are no base restriction clauses, we have no hope of proving
1573  * anything below, so fall out quickly.
1574  */
1575  if (rel->baserestrictinfo == NIL)
1576  return false;
1577 
1578  /*
1579  * Regardless of the setting of constraint_exclusion, detect
1580  * constant-FALSE-or-NULL restriction clauses. Although const-folding
1581  * will reduce "anything AND FALSE" to just "FALSE", the baserestrictinfo
1582  * list can still have other members besides the FALSE constant, due to
1583  * qual pushdown and other mechanisms; so check them all. This doesn't
1584  * fire very often, but it seems cheap enough to be worth doing anyway.
1585  * (Without this, we'd miss some optimizations that 9.5 and earlier found
1586  * via much more roundabout methods.)
1587  */
1588  foreach(lc, rel->baserestrictinfo)
1589  {
1590  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1591  Expr *clause = rinfo->clause;
1592 
1593  if (clause && IsA(clause, Const) &&
1594  (((Const *) clause)->constisnull ||
1595  !DatumGetBool(((Const *) clause)->constvalue)))
1596  return true;
1597  }
1598 
1599  /*
1600  * Skip further tests, depending on constraint_exclusion.
1601  */
1602  switch (constraint_exclusion)
1603  {
1605  /* In 'off' mode, never make any further tests */
1606  return false;
1607 
1609 
1610  /*
1611  * When constraint_exclusion is set to 'partition' we only handle
1612  * appendrel members. Partition pruning has already been applied,
1613  * so there is no need to consider the rel's partition constraints
1614  * here.
1615  */
1616  if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
1617  break; /* appendrel member, so process it */
1618  return false;
1619 
1621 
1622  /*
1623  * In 'on' mode, always apply constraint exclusion. If we are
1624  * considering a baserel that is a partition (i.e., it was
1625  * directly named rather than expanded from a parent table), then
1626  * its partition constraints haven't been considered yet, so
1627  * include them in the processing here.
1628  */
1629  if (rel->reloptkind == RELOPT_BASEREL)
1630  include_partition = true;
1631  break; /* always try to exclude */
1632  }
1633 
1634  /*
1635  * Check for self-contradictory restriction clauses. We dare not make
1636  * deductions with non-immutable functions, but any immutable clauses that
1637  * are self-contradictory allow us to conclude the scan is unnecessary.
1638  *
1639  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1640  * expecting to see any in its predicate argument.
1641  */
1642  safe_restrictions = NIL;
1643  foreach(lc, rel->baserestrictinfo)
1644  {
1645  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1646 
1647  if (!contain_mutable_functions((Node *) rinfo->clause))
1648  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1649  }
1650 
1651  /*
1652  * We can use weak refutation here, since we're comparing restriction
1653  * clauses with restriction clauses.
1654  */
1655  if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1656  return true;
1657 
1658  /*
1659  * Only plain relations have constraints, so stop here for other rtekinds.
1660  */
1661  if (rte->rtekind != RTE_RELATION)
1662  return false;
1663 
1664  /*
1665  * If we are scanning just this table, we can use NO INHERIT constraints,
1666  * but not if we're scanning its children too. (Note that partitioned
1667  * tables should never have NO INHERIT constraints; but it's not necessary
1668  * for us to assume that here.)
1669  */
1670  include_noinherit = !rte->inh;
1671 
1672  /*
1673  * Currently, attnotnull constraints must be treated as NO INHERIT unless
1674  * this is a partitioned table. In future we might track their
1675  * inheritance status more accurately, allowing this to be refined.
1676  *
1677  * XXX do we need/want to change this?
1678  */
1679  include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
1680 
1681  /*
1682  * Fetch the appropriate set of constraint expressions.
1683  */
1684  constraint_pred = get_relation_constraints(root, rte->relid, rel,
1685  include_noinherit,
1686  include_notnull,
1687  include_partition);
1688 
1689  /*
1690  * We do not currently enforce that CHECK constraints contain only
1691  * immutable functions, so it's necessary to check here. We daren't draw
1692  * conclusions from plan-time evaluation of non-immutable functions. Since
1693  * they're ANDed, we can just ignore any mutable constraints in the list,
1694  * and reason about the rest.
1695  */
1696  safe_constraints = NIL;
1697  foreach(lc, constraint_pred)
1698  {
1699  Node *pred = (Node *) lfirst(lc);
1700 
1701  if (!contain_mutable_functions(pred))
1702  safe_constraints = lappend(safe_constraints, pred);
1703  }
1704 
1705  /*
1706  * The constraints are effectively ANDed together, so we can just try to
1707  * refute the entire collection at once. This may allow us to make proofs
1708  * that would fail if we took them individually.
1709  *
1710  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1711  * an obvious optimization. Some of the clauses might be OR clauses that
1712  * have volatile and nonvolatile subclauses, and it's OK to make
1713  * deductions with the nonvolatile parts.
1714  *
1715  * We need strong refutation because we have to prove that the constraints
1716  * would yield false, not just NULL.
1717  */
1718  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1719  return true;
1720 
1721  return false;
1722 }
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:370
@ CONSTRAINT_EXCLUSION_OFF
Definition: cost.h:38
@ CONSTRAINT_EXCLUSION_PARTITION
Definition: cost.h:40
@ CONSTRAINT_EXCLUSION_ON
Definition: cost.h:39
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:829
@ RELOPT_BASEREL
Definition: pathnodes.h:817
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:819
int constraint_exclusion
Definition: plancat.c:56
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
Definition: plancat.c:1248
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:222
List * baserestrictinfo
Definition: pathnodes.h:975
RelOptKind reloptkind
Definition: pathnodes.h:855
Expr * clause
Definition: pathnodes.h:2552

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, NIL, predicate_refuted_by(), RangeTblEntry::relid, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, root, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by set_append_rel_size(), and set_rel_size().

◆ restriction_selectivity()

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

Definition at line 1930 of file plancat.c.

1935 {
1936  RegProcedure oprrest = get_oprrest(operatorid);
1937  float8 result;
1938 
1939  /*
1940  * if the oprrest procedure is missing for whatever reason, use a
1941  * selectivity of 0.5
1942  */
1943  if (!oprrest)
1944  return (Selectivity) 0.5;
1945 
1946  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1947  inputcollid,
1949  ObjectIdGetDatum(operatorid),
1951  Int32GetDatum(varRelid)));
1952 
1953  if (result < 0.0 || result > 1.0)
1954  elog(ERROR, "invalid restriction selectivity: %f", result);
1955 
1956  return (Selectivity) result;
1957 }
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1442
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1557
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212

References generate_unaccent_rules::args, DatumGetFloat8(), elog, ERROR, get_oprrest(), Int32GetDatum(), ObjectIdGetDatum(), OidFunctionCall4Coll(), PointerGetDatum(), and root.

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

Variable Documentation

◆ get_relation_info_hook

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook
extern

Definition at line 59 of file plancat.c.

Referenced by get_relation_info().