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

2090 {
2091  HeapTuple proctup;
2092  Form_pg_proc procform;
2093 
2094  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2095  if (!HeapTupleIsValid(proctup))
2096  elog(ERROR, "cache lookup failed for function %u", funcid);
2097  procform = (Form_pg_proc) GETSTRUCT(proctup);
2098 
2099  if (OidIsValid(procform->prosupport))
2100  {
2101  SupportRequestCost req;
2102  SupportRequestCost *sresult;
2103 
2104  req.type = T_SupportRequestCost;
2105  req.root = root;
2106  req.funcid = funcid;
2107  req.node = node;
2108 
2109  /* Initialize cost fields so that support function doesn't have to */
2110  req.startup = 0;
2111  req.per_tuple = 0;
2112 
2113  sresult = (SupportRequestCost *)
2114  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2115  PointerGetDatum(&req)));
2116 
2117  if (sresult == &req)
2118  {
2119  /* Success, so accumulate support function's estimate into *cost */
2120  cost->startup += req.startup;
2121  cost->per_tuple += req.per_tuple;
2122  ReleaseSysCache(proctup);
2123  return;
2124  }
2125  }
2126 
2127  /* No support function, or it failed, so rely on procost */
2128  cost->per_tuple += procform->procost * cpu_operator_cost;
2129 
2130  ReleaseSysCache(proctup);
2131 }
#define OidIsValid(objectId)
Definition: c.h:775
double cpu_operator_cost
Definition: costsize.c:134
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:679
#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:1886
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 1763 of file plancat.c.

1764 {
1765  List *tlist = NIL;
1766  Index varno = rel->relid;
1767  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1768  Relation relation;
1769  Query *subquery;
1770  Var *var;
1771  ListCell *l;
1772  int attrno,
1773  numattrs;
1774  List *colvars;
1775 
1776  switch (rte->rtekind)
1777  {
1778  case RTE_RELATION:
1779  /* Assume we already have adequate lock */
1780  relation = table_open(rte->relid, NoLock);
1781 
1782  numattrs = RelationGetNumberOfAttributes(relation);
1783  for (attrno = 1; attrno <= numattrs; attrno++)
1784  {
1785  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1786  attrno - 1);
1787 
1788  if (att_tup->attisdropped || att_tup->atthasmissing)
1789  {
1790  /* found a dropped or missing col, so punt */
1791  tlist = NIL;
1792  break;
1793  }
1794 
1795  var = makeVar(varno,
1796  attrno,
1797  att_tup->atttypid,
1798  att_tup->atttypmod,
1799  att_tup->attcollation,
1800  0);
1801 
1802  tlist = lappend(tlist,
1803  makeTargetEntry((Expr *) var,
1804  attrno,
1805  NULL,
1806  false));
1807  }
1808 
1809  table_close(relation, NoLock);
1810  break;
1811 
1812  case RTE_SUBQUERY:
1813  subquery = rte->subquery;
1814  foreach(l, subquery->targetList)
1815  {
1816  TargetEntry *tle = (TargetEntry *) lfirst(l);
1817 
1818  /*
1819  * A resjunk column of the subquery can be reflected as
1820  * resjunk in the physical tlist; we need not punt.
1821  */
1822  var = makeVarFromTargetEntry(varno, tle);
1823 
1824  tlist = lappend(tlist,
1825  makeTargetEntry((Expr *) var,
1826  tle->resno,
1827  NULL,
1828  tle->resjunk));
1829  }
1830  break;
1831 
1832  case RTE_FUNCTION:
1833  case RTE_TABLEFUNC:
1834  case RTE_VALUES:
1835  case RTE_CTE:
1836  case RTE_NAMEDTUPLESTORE:
1837  case RTE_RESULT:
1838  /* Not all of these can have dropped cols, but share code anyway */
1839  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1840  NULL, &colvars);
1841  foreach(l, colvars)
1842  {
1843  var = (Var *) lfirst(l);
1844 
1845  /*
1846  * A non-Var in expandRTE's output means a dropped column;
1847  * must punt.
1848  */
1849  if (!IsA(var, Var))
1850  {
1851  tlist = NIL;
1852  break;
1853  }
1854 
1855  tlist = lappend(tlist,
1856  makeTargetEntry((Expr *) var,
1857  var->varattno,
1858  NULL,
1859  false));
1860  }
1861  break;
1862 
1863  default:
1864  /* caller error */
1865  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1866  (int) rte->rtekind);
1867  break;
1868  }
1869 
1870  return tlist;
1871 }
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:1023
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1024
@ RTE_VALUES
Definition: parsenodes.h:1022
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
@ RTE_RESULT
Definition: parsenodes.h:1025
@ RTE_FUNCTION
Definition: parsenodes.h:1020
@ RTE_TABLEFUNC
Definition: parsenodes.h:1021
@ RTE_RELATION
Definition: parsenodes.h:1017
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:570
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:193
Query * subquery
Definition: parsenodes.h:1104
RTEKind rtekind
Definition: parsenodes.h:1047
Index relid
Definition: pathnodes.h:918
TupleDesc rd_att
Definition: rel.h:112
AttrNumber resno
Definition: primnodes.h:2188
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 1059 of file plancat.c.

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

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

2034 {
2035  RegProcedure prosupport = get_func_support(funcid);
2037  SupportRequestSelectivity *sresult;
2038 
2039  /*
2040  * If no support function is provided, use our historical default
2041  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
2042  * Postgres has been using that estimate for function calls since 1992.
2043  * The hoariness of this behavior suggests that we should not be in too
2044  * much hurry to use another value.
2045  */
2046  if (!prosupport)
2047  return (Selectivity) 0.3333333;
2048 
2049  req.type = T_SupportRequestSelectivity;
2050  req.root = root;
2051  req.funcid = funcid;
2052  req.args = args;
2053  req.inputcollid = inputcollid;
2054  req.is_join = is_join;
2055  req.varRelid = varRelid;
2056  req.jointype = jointype;
2057  req.sjinfo = sjinfo;
2058  req.selectivity = -1; /* to catch failure to set the value */
2059 
2060  sresult = (SupportRequestSelectivity *)
2061  DatumGetPointer(OidFunctionCall1(prosupport,
2062  PointerGetDatum(&req)));
2063 
2064  /* If support function fails, use default */
2065  if (sresult != &req)
2066  return (Selectivity) 0.3333333;
2067 
2068  if (req.selectivity < 0.0 || req.selectivity > 1.0)
2069  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2070 
2071  return (Selectivity) req.selectivity;
2072 }
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 2316 of file plancat.c.

2318 {
2319  Bitmapset *dependentCols = NULL;
2320  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2321  Relation relation;
2322  TupleDesc tupdesc;
2323  TupleConstr *constr;
2324 
2325  /* Assume we already have adequate lock */
2326  relation = table_open(rte->relid, NoLock);
2327 
2328  tupdesc = RelationGetDescr(relation);
2329  constr = tupdesc->constr;
2330 
2331  if (constr && constr->has_generated_stored)
2332  {
2333  for (int i = 0; i < constr->num_defval; i++)
2334  {
2335  AttrDefault *defval = &constr->defval[i];
2336  Node *expr;
2337  Bitmapset *attrs_used = NULL;
2338 
2339  /* skip if not generated column */
2340  if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
2341  continue;
2342 
2343  /* identify columns this generated column depends on */
2344  expr = stringToNode(defval->adbin);
2345  pull_varattnos(expr, 1, &attrs_used);
2346 
2347  if (bms_overlap(target_cols, attrs_used))
2348  dependentCols = bms_add_member(dependentCols,
2350  }
2351  }
2352 
2353  table_close(relation, NoLock);
2354 
2355  return dependentCols;
2356 }
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:296

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

2150 {
2151  HeapTuple proctup;
2152  Form_pg_proc procform;
2153  double result;
2154 
2155  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2156  if (!HeapTupleIsValid(proctup))
2157  elog(ERROR, "cache lookup failed for function %u", funcid);
2158  procform = (Form_pg_proc) GETSTRUCT(proctup);
2159 
2160  Assert(procform->proretset); /* else caller error */
2161 
2162  if (OidIsValid(procform->prosupport))
2163  {
2164  SupportRequestRows req;
2165  SupportRequestRows *sresult;
2166 
2167  req.type = T_SupportRequestRows;
2168  req.root = root;
2169  req.funcid = funcid;
2170  req.node = node;
2171 
2172  req.rows = 0; /* just for sanity */
2173 
2174  sresult = (SupportRequestRows *)
2175  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2176  PointerGetDatum(&req)));
2177 
2178  if (sresult == &req)
2179  {
2180  /* Success */
2181  ReleaseSysCache(proctup);
2182  return req.rows;
2183  }
2184  }
2185 
2186  /* No support function, or it failed, so rely on prorows */
2187  result = procform->prorows;
2188 
2189  ReleaseSysCache(proctup);
2190 
2191  return result;
2192 }
#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 1184 of file plancat.c.

1185 {
1186  int64 tuple_width = 0;
1187  int i;
1188 
1189  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1190  {
1191  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1192  int32 item_width;
1193 
1194  if (att->attisdropped)
1195  continue;
1196 
1197  /* use previously cached data, if any */
1198  if (attr_widths != NULL && attr_widths[i] > 0)
1199  {
1200  tuple_width += attr_widths[i];
1201  continue;
1202  }
1203 
1204  /* This should match set_rel_width() in costsize.c */
1205  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1206  if (item_width <= 0)
1207  {
1208  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1209  Assert(item_width > 0);
1210  }
1211  if (attr_widths != NULL)
1212  attr_widths[i] = item_width;
1213  tuple_width += item_width;
1214  }
1215 
1216  return clamp_width_est(tuple_width);
1217 }
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:242
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 1226 of file plancat.c.

1227 {
1228  int32 result;
1229  Relation relation;
1230 
1231  /* As above, assume relation is already locked */
1232  relation = table_open(relid, NoLock);
1233 
1234  result = get_rel_data_width(relation, attr_widths);
1235 
1236  table_close(relation, NoLock);
1237 
1238  return result;
1239 }

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

118 {
119  Index varno = rel->relid;
120  Relation relation;
121  bool hasindex;
122  List *indexinfos = NIL;
123 
124  /*
125  * We need not lock the relation since it was already locked, either by
126  * the rewriter or when expand_inherited_rtentry() added it to the query's
127  * rangetable.
128  */
129  relation = table_open(relationObjectId, NoLock);
130 
131  /*
132  * Relations without a table AM can be used in a query only if they are of
133  * special-cased relkinds. This check prevents us from crashing later if,
134  * for example, a view's ON SELECT rule has gone missing. Note that
135  * table_open() already rejected indexes and composite types; spell the
136  * error the same way it does.
137  */
138  if (!relation->rd_tableam)
139  {
140  if (!(relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE ||
141  relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
142  ereport(ERROR,
143  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
144  errmsg("cannot open relation \"%s\"",
145  RelationGetRelationName(relation)),
146  errdetail_relkind_not_supported(relation->rd_rel->relkind)));
147  }
148 
149  /* Temporary and unlogged relations are inaccessible during recovery. */
150  if (!RelationIsPermanent(relation) && RecoveryInProgress())
151  ereport(ERROR,
152  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
153  errmsg("cannot access temporary or unlogged relations during recovery")));
154 
156  rel->max_attr = RelationGetNumberOfAttributes(relation);
157  rel->reltablespace = RelationGetForm(relation)->reltablespace;
158 
159  Assert(rel->max_attr >= rel->min_attr);
160  rel->attr_needed = (Relids *)
161  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
162  rel->attr_widths = (int32 *)
163  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
164 
165  /*
166  * Record which columns are defined as NOT NULL. We leave this
167  * unpopulated for non-partitioned inheritance parent relations as it's
168  * ambiguous as to what it means. Some child tables may have a NOT NULL
169  * constraint for a column while others may not. We could work harder and
170  * build a unioned set of all child relations notnullattnums, but there's
171  * currently no need. The RelOptInfo corresponding to the !inh
172  * RangeTblEntry does get populated.
173  */
174  if (!inhparent || relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
175  {
176  for (int i = 0; i < relation->rd_att->natts; i++)
177  {
178  Form_pg_attribute attr = TupleDescAttr(relation->rd_att, i);
179 
180  if (attr->attnotnull)
181  {
183  attr->attnum);
184 
185  /*
186  * Per RemoveAttributeById(), dropped columns will have their
187  * attnotnull unset, so we needn't check for dropped columns
188  * in the above condition.
189  */
190  Assert(!attr->attisdropped);
191  }
192  }
193  }
194 
195  /*
196  * Estimate relation size --- unless it's an inheritance parent, in which
197  * case the size we want is not the rel's own size but the size of its
198  * inheritance tree. That will be computed in set_append_rel_size().
199  */
200  if (!inhparent)
201  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
202  &rel->pages, &rel->tuples, &rel->allvisfrac);
203 
204  /* Retrieve the parallel_workers reloption, or -1 if not set. */
206 
207  /*
208  * Make list of indexes. Ignore indexes on system catalogs if told to.
209  * Don't bother with indexes from traditional inheritance parents. For
210  * partitioned tables, we need a list of at least unique indexes as these
211  * serve as unique proofs for certain planner optimizations. However,
212  * let's not discriminate here and just record all partitioned indexes
213  * whether they're unique indexes or not.
214  */
215  if ((inhparent && relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
216  || (IgnoreSystemIndexes && IsSystemRelation(relation)))
217  hasindex = false;
218  else
219  hasindex = relation->rd_rel->relhasindex;
220 
221  if (hasindex)
222  {
223  List *indexoidlist;
224  LOCKMODE lmode;
225  ListCell *l;
226 
227  indexoidlist = RelationGetIndexList(relation);
228 
229  /*
230  * For each index, we get the same type of lock that the executor will
231  * need, and do not release it. This saves a couple of trips to the
232  * shared lock manager while not creating any real loss of
233  * concurrency, because no schema changes could be happening on the
234  * index while we hold lock on the parent rel, and no lock type used
235  * for queries blocks any other kind of index operation.
236  */
237  lmode = root->simple_rte_array[varno]->rellockmode;
238 
239  foreach(l, indexoidlist)
240  {
241  Oid indexoid = lfirst_oid(l);
242  Relation indexRelation;
244  IndexAmRoutine *amroutine = NULL;
245  IndexOptInfo *info;
246  int ncolumns,
247  nkeycolumns;
248  int i;
249 
250  /*
251  * Extract info from the relation descriptor for the index.
252  */
253  indexRelation = index_open(indexoid, lmode);
254  index = indexRelation->rd_index;
255 
256  /*
257  * Ignore invalid indexes, since they can't safely be used for
258  * queries. Note that this is OK because the data structure we
259  * are constructing is only used by the planner --- the executor
260  * still needs to insert into "invalid" indexes, if they're marked
261  * indisready.
262  */
263  if (!index->indisvalid)
264  {
265  index_close(indexRelation, NoLock);
266  continue;
267  }
268 
269  /*
270  * If the index is valid, but cannot yet be used, ignore it; but
271  * mark the plan we are generating as transient. See
272  * src/backend/access/heap/README.HOT for discussion.
273  */
274  if (index->indcheckxmin &&
277  {
278  root->glob->transientPlan = true;
279  index_close(indexRelation, NoLock);
280  continue;
281  }
282 
283  info = makeNode(IndexOptInfo);
284 
285  info->indexoid = index->indexrelid;
286  info->reltablespace =
287  RelationGetForm(indexRelation)->reltablespace;
288  info->rel = rel;
289  info->ncolumns = ncolumns = index->indnatts;
290  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
291 
292  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
293  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
294  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
295  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
296  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
297 
298  for (i = 0; i < ncolumns; i++)
299  {
300  info->indexkeys[i] = index->indkey.values[i];
301  info->canreturn[i] = index_can_return(indexRelation, i + 1);
302  }
303 
304  for (i = 0; i < nkeycolumns; i++)
305  {
306  info->opfamily[i] = indexRelation->rd_opfamily[i];
307  info->opcintype[i] = indexRelation->rd_opcintype[i];
308  info->indexcollations[i] = indexRelation->rd_indcollation[i];
309  }
310 
311  info->relam = indexRelation->rd_rel->relam;
312 
313  /*
314  * We don't have an AM for partitioned indexes, so we'll just
315  * NULLify the AM related fields for those.
316  */
317  if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
318  {
319  /* We copy just the fields we need, not all of rd_indam */
320  amroutine = indexRelation->rd_indam;
321  info->amcanorderbyop = amroutine->amcanorderbyop;
322  info->amoptionalkey = amroutine->amoptionalkey;
323  info->amsearcharray = amroutine->amsearcharray;
324  info->amsearchnulls = amroutine->amsearchnulls;
325  info->amcanparallel = amroutine->amcanparallel;
326  info->amhasgettuple = (amroutine->amgettuple != NULL);
327  info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
328  relation->rd_tableam->scan_bitmap_next_block != NULL;
329  info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
330  amroutine->amrestrpos != NULL);
331  info->amcostestimate = amroutine->amcostestimate;
332  Assert(info->amcostestimate != NULL);
333 
334  /* Fetch index opclass options */
335  info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
336 
337  /*
338  * Fetch the ordering information for the index, if any.
339  */
340  if (info->relam == BTREE_AM_OID)
341  {
342  /*
343  * If it's a btree index, we can use its opfamily OIDs
344  * directly as the sort ordering opfamily OIDs.
345  */
346  Assert(amroutine->amcanorder);
347 
348  info->sortopfamily = info->opfamily;
349  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
350  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
351 
352  for (i = 0; i < nkeycolumns; i++)
353  {
354  int16 opt = indexRelation->rd_indoption[i];
355 
356  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
357  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
358  }
359  }
360  else if (amroutine->amcanorder)
361  {
362  /*
363  * Otherwise, identify the corresponding btree opfamilies
364  * by trying to map this index's "<" operators into btree.
365  * Since "<" uniquely defines the behavior of a sort
366  * order, this is a sufficient test.
367  *
368  * XXX This method is rather slow and also requires the
369  * undesirable assumption that the other index AM numbers
370  * its strategies the same as btree. It'd be better to
371  * have a way to explicitly declare the corresponding
372  * btree opfamily for each opfamily of the other index
373  * type. But given the lack of current or foreseeable
374  * amcanorder index types, it's not worth expending more
375  * effort on now.
376  */
377  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
378  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
379  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
380 
381  for (i = 0; i < nkeycolumns; i++)
382  {
383  int16 opt = indexRelation->rd_indoption[i];
384  Oid ltopr;
385  Oid btopfamily;
386  Oid btopcintype;
387  int16 btstrategy;
388 
389  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
390  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
391 
392  ltopr = get_opfamily_member(info->opfamily[i],
393  info->opcintype[i],
394  info->opcintype[i],
396  if (OidIsValid(ltopr) &&
398  &btopfamily,
399  &btopcintype,
400  &btstrategy) &&
401  btopcintype == info->opcintype[i] &&
402  btstrategy == BTLessStrategyNumber)
403  {
404  /* Successful mapping */
405  info->sortopfamily[i] = btopfamily;
406  }
407  else
408  {
409  /* Fail ... quietly treat index as unordered */
410  info->sortopfamily = NULL;
411  info->reverse_sort = NULL;
412  info->nulls_first = NULL;
413  break;
414  }
415  }
416  }
417  else
418  {
419  info->sortopfamily = NULL;
420  info->reverse_sort = NULL;
421  info->nulls_first = NULL;
422  }
423  }
424  else
425  {
426  info->amcanorderbyop = false;
427  info->amoptionalkey = false;
428  info->amsearcharray = false;
429  info->amsearchnulls = false;
430  info->amcanparallel = false;
431  info->amhasgettuple = false;
432  info->amhasgetbitmap = false;
433  info->amcanmarkpos = false;
434  info->amcostestimate = NULL;
435 
436  info->sortopfamily = NULL;
437  info->reverse_sort = NULL;
438  info->nulls_first = NULL;
439  }
440 
441  /*
442  * Fetch the index expressions and predicate, if any. We must
443  * modify the copies we obtain from the relcache to have the
444  * correct varno for the parent relation, so that they match up
445  * correctly against qual clauses.
446  */
447  info->indexprs = RelationGetIndexExpressions(indexRelation);
448  info->indpred = RelationGetIndexPredicate(indexRelation);
449  if (info->indexprs && varno != 1)
450  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
451  if (info->indpred && varno != 1)
452  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
453 
454  /* Build targetlist using the completed indexprs data */
455  info->indextlist = build_index_tlist(root, info, relation);
456 
457  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
458  info->predOK = false; /* set later, in indxpath.c */
459  info->unique = index->indisunique;
460  info->immediate = index->indimmediate;
461  info->hypothetical = false;
462 
463  /*
464  * Estimate the index size. If it's not a partial index, we lock
465  * the number-of-tuples estimate to equal the parent table; if it
466  * is partial then we have to use the same methods as we would for
467  * a table, except we can be sure that the index is not larger
468  * than the table. We must ignore partitioned indexes here as
469  * there are not physical indexes.
470  */
471  if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
472  {
473  if (info->indpred == NIL)
474  {
475  info->pages = RelationGetNumberOfBlocks(indexRelation);
476  info->tuples = rel->tuples;
477  }
478  else
479  {
480  double allvisfrac; /* dummy */
481 
482  estimate_rel_size(indexRelation, NULL,
483  &info->pages, &info->tuples, &allvisfrac);
484  if (info->tuples > rel->tuples)
485  info->tuples = rel->tuples;
486  }
487 
488  /*
489  * Get tree height while we have the index open
490  */
491  if (amroutine->amgettreeheight)
492  {
493  info->tree_height = amroutine->amgettreeheight(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  {
531  /* Check if the access to foreign tables is restricted */
533  {
534  /* there must not be built-in foreign tables */
536 
537  ereport(ERROR,
538  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
539  errmsg("access to non-system foreign table is restricted")));
540  }
541 
543  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
544  }
545  else
546  {
547  rel->serverid = InvalidOid;
548  rel->fdwroutine = NULL;
549  }
550 
551  /* Collect info about relation's foreign keys, if relevant */
552  get_relation_foreign_keys(root, rel, relation, inhparent);
553 
554  /* Collect info about functions implemented by the rel's table AM. */
555  if (relation->rd_tableam &&
556  relation->rd_tableam->scan_set_tidrange != NULL &&
557  relation->rd_tableam->scan_getnextslot_tidrange != NULL)
559 
560  /*
561  * Collect info about relation's partitioning scheme, if any. Only
562  * inheritance parents may be partitioned.
563  */
564  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
565  set_relation_partition_info(root, rel, relation);
566 
567  table_close(relation, NoLock);
568 
569  /*
570  * Allow a plugin to editorialize on the info we obtained from the
571  * catalogs. Actions might include altering the assumed relation size,
572  * removing an index, or adding a hypothetical index to the indexlist.
573  */
575  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
576 }
signed short int16
Definition: c.h:493
#define unlikely(x)
Definition: c.h:311
bool IsSystemRelation(Relation relation)
Definition: catalog.c:73
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:442
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:355
#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:1347
void * palloc(Size size)
Definition: mcxt.c:1317
bool IgnoreSystemIndexes
Definition: miscinit.c:80
#define makeNode(_type_)
Definition: nodes.h:155
Bitmapset * Relids
Definition: pathnodes.h:30
#define AMFLAG_HAS_TID_RANGE
Definition: pathnodes.h:823
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:1059
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:589
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:60
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1884
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1469
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:2364
int restrict_nonsystem_relation_kind
Definition: postgres.c:108
#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:4801
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5151
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5891
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:5038
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:294
amcostestimate_function amcostestimate
Definition: amapi.h:281
bool amcanorderbyop
Definition: amapi.h:233
bool amoptionalkey
Definition: amapi.h:241
amgettuple_function amgettuple
Definition: amapi.h:290
amgetbitmap_function amgetbitmap
Definition: amapi.h:291
bool amsearcharray
Definition: amapi.h:243
ammarkpos_function ammarkpos
Definition: amapi.h:293
bool amcanparallel
Definition: amapi.h:253
bool amcanorder
Definition: amapi.h:231
amgettreeheight_function amgettreeheight
Definition: amapi.h:282
bool amsearchnulls
Definition: amapi.h:245
bool amcanparallel
Definition: pathnodes.h:1204
bool amoptionalkey
Definition: pathnodes.h:1197
Oid reltablespace
Definition: pathnodes.h:1119
bool amcanmarkpos
Definition: pathnodes.h:1206
List * indrestrictinfo
Definition: pathnodes.h:1181
void(* amcostestimate)() pg_node_attr(read_write_ignore)
Definition: pathnodes.h:1209
bool amhasgettuple
Definition: pathnodes.h:1201
bool amcanorderbyop
Definition: pathnodes.h:1196
bool hypothetical
Definition: pathnodes.h:1190
List * indpred
Definition: pathnodes.h:1171
Cardinality tuples
Definition: pathnodes.h:1129
bool amsearcharray
Definition: pathnodes.h:1198
BlockNumber pages
Definition: pathnodes.h:1127
bool amsearchnulls
Definition: pathnodes.h:1199
bool amhasgetbitmap
Definition: pathnodes.h:1203
List * indextlist
Definition: pathnodes.h:1174
bool immediate
Definition: pathnodes.h:1188
uint32 amflags
Definition: pathnodes.h:958
Bitmapset * notnullattnums
Definition: pathnodes.h:936
List * statlist
Definition: pathnodes.h:946
Cardinality tuples
Definition: pathnodes.h:949
BlockNumber pages
Definition: pathnodes.h:948
List * indexlist
Definition: pathnodes.h:944
Oid reltablespace
Definition: pathnodes.h:920
Oid serverid
Definition: pathnodes.h:964
int rel_parallel_workers
Definition: pathnodes.h:956
AttrNumber max_attr
Definition: pathnodes.h:926
double allvisfrac
Definition: pathnodes.h:950
AttrNumber min_attr
Definition: pathnodes.h:924
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:813
Definition: type.h:95
#define RESTRICT_RELKIND_FOREIGN_TABLE
Definition: tcopprot.h:48
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define FirstNormalObjectId
Definition: transam.h:197
bool RecoveryInProgress(void)
Definition: xlog.c:6333

References 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::amgettreeheight, IndexAmRoutine::amgettuple, IndexOptInfo::amhasgetbitmap, IndexOptInfo::amhasgettuple, IndexAmRoutine::ammarkpos, IndexAmRoutine::amoptionalkey, IndexOptInfo::amoptionalkey, IndexAmRoutine::amrestrpos, IndexAmRoutine::amsearcharray, IndexOptInfo::amsearcharray, IndexAmRoutine::amsearchnulls, IndexOptInfo::amsearchnulls, Assert, bms_add_member(), BTLessStrategyNumber, build_index_tlist(), ChangeVarNodes(), ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, estimate_rel_size(), FirstLowInvalidHeapAttributeNumber, FirstNormalObjectId, 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, restrict_nonsystem_relation_kind, RESTRICT_RELKIND_FOREIGN_TABLE, 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, TupleDescAttr, RelOptInfo::tuples, IndexOptInfo::tuples, IndexOptInfo::unique, and unlikely.

Referenced by build_simple_rel().

◆ has_row_triggers()

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

Definition at line 2239 of file plancat.c.

2240 {
2241  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2242  Relation relation;
2243  TriggerDesc *trigDesc;
2244  bool result = false;
2245 
2246  /* Assume we already have adequate lock */
2247  relation = table_open(rte->relid, NoLock);
2248 
2249  trigDesc = relation->trigdesc;
2250  switch (event)
2251  {
2252  case CMD_INSERT:
2253  if (trigDesc &&
2254  (trigDesc->trig_insert_after_row ||
2255  trigDesc->trig_insert_before_row))
2256  result = true;
2257  break;
2258  case CMD_UPDATE:
2259  if (trigDesc &&
2260  (trigDesc->trig_update_after_row ||
2261  trigDesc->trig_update_before_row))
2262  result = true;
2263  break;
2264  case CMD_DELETE:
2265  if (trigDesc &&
2266  (trigDesc->trig_delete_after_row ||
2267  trigDesc->trig_delete_before_row))
2268  result = true;
2269  break;
2270  /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2271  case CMD_MERGE:
2272  result = false;
2273  break;
2274  default:
2275  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2276  break;
2277  }
2278 
2279  table_close(relation, NoLock);
2280  return result;
2281 }
@ 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 2289 of file plancat.c.

2290 {
2291  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2292  Relation relation;
2293  TupleDesc tupdesc;
2294  bool result = false;
2295 
2296  /* Assume we already have adequate lock */
2297  relation = table_open(rte->relid, NoLock);
2298 
2299  tupdesc = RelationGetDescr(relation);
2300  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2301 
2302  table_close(relation, NoLock);
2303 
2304  return result;
2305 }

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

2208 {
2209  ListCell *ilist;
2210 
2211  foreach(ilist, rel->indexlist)
2212  {
2213  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2214 
2215  /*
2216  * Note: ignore partial indexes, since they don't allow us to conclude
2217  * that all attr values are distinct, *unless* they are marked predOK
2218  * which means we know the index's predicate is satisfied by the
2219  * query. We don't take any interest in expressional indexes either.
2220  * Also, a multicolumn unique index doesn't allow us to conclude that
2221  * just the specified attr is unique.
2222  */
2223  if (index->unique &&
2224  index->nkeycolumns == 1 &&
2225  index->indexkeys[0] == attno &&
2226  (index->indpred == NIL || index->predOK))
2227  return true;
2228  }
2229  return false;
2230 }

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 704 of file plancat.c.

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

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, bms_add_member(), bms_equal(), ChangeVarNodes(), 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 1985 of file plancat.c.

1991 {
1992  RegProcedure oprjoin = get_oprjoin(operatorid);
1993  float8 result;
1994 
1995  /*
1996  * if the oprjoin procedure is missing for whatever reason, use a
1997  * selectivity of 0.5
1998  */
1999  if (!oprjoin)
2000  return (Selectivity) 0.5;
2001 
2002  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
2003  inputcollid,
2005  ObjectIdGetDatum(operatorid),
2007  Int16GetDatum(jointype),
2008  PointerGetDatum(sjinfo)));
2009 
2010  if (result < 0.0 || result > 1.0)
2011  elog(ERROR, "invalid join selectivity: %f", result);
2012 
2013  return (Selectivity) result;
2014 }
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 1575 of file plancat.c.

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

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

1951 {
1952  RegProcedure oprrest = get_oprrest(operatorid);
1953  float8 result;
1954 
1955  /*
1956  * if the oprrest procedure is missing for whatever reason, use a
1957  * selectivity of 0.5
1958  */
1959  if (!oprrest)
1960  return (Selectivity) 0.5;
1961 
1962  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1963  inputcollid,
1965  ObjectIdGetDatum(operatorid),
1967  Int32GetDatum(varRelid)));
1968 
1969  if (result < 0.0 || result > 1.0)
1970  elog(ERROR, "invalid restriction selectivity: %f", result);
1971 
1972  return (Selectivity) result;
1973 }
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 60 of file plancat.c.

Referenced by get_relation_info().