PostgreSQL Source Code  git master
plancat.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/supportnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "optimizer/prep.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "partitioning/partdesc.h"
#include "rewrite/rewriteManip.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for plancat.c:

Go to the source code of this file.

Functions

static void get_relation_foreign_keys (PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
 
static bool infer_collation_opclass_match (InferenceElem *elem, Relation idxRel, List *idxExprs)
 
static Listget_relation_constraints (PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
 
static Listbuild_index_tlist (PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
 
static Listget_relation_statistics (RelOptInfo *rel, Relation relation)
 
static void set_relation_partition_info (PlannerInfo *root, RelOptInfo *rel, Relation relation)
 
static PartitionScheme find_partition_scheme (PlannerInfo *root, Relation relation)
 
static void set_baserel_partition_key_exprs (Relation relation, RelOptInfo *rel)
 
static void set_baserel_partition_constraint (Relation relation, RelOptInfo *rel)
 
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)
 
static void get_relation_statistics_worker (List **stainfos, RelOptInfo *rel, Oid statOid, bool inh, Bitmapset *keys, List *exprs)
 
bool relation_excluded_by_constraints (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
Listbuild_physical_tlist (PlannerInfo *root, RelOptInfo *rel)
 
Selectivity restriction_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
 
Selectivity join_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
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_unique_index (RelOptInfo *rel, AttrNumber attno)
 
bool has_row_triggers (PlannerInfo *root, Index rti, CmdType event)
 
bool has_stored_generated_columns (PlannerInfo *root, Index rti)
 

Variables

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION
 
get_relation_info_hook_type get_relation_info_hook = NULL
 

Function Documentation

◆ add_function_cost()

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

Definition at line 2007 of file plancat.c.

2009 {
2010  HeapTuple proctup;
2011  Form_pg_proc procform;
2012 
2013  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2014  if (!HeapTupleIsValid(proctup))
2015  elog(ERROR, "cache lookup failed for function %u", funcid);
2016  procform = (Form_pg_proc) GETSTRUCT(proctup);
2017 
2018  if (OidIsValid(procform->prosupport))
2019  {
2020  SupportRequestCost req;
2021  SupportRequestCost *sresult;
2022 
2023  req.type = T_SupportRequestCost;
2024  req.root = root;
2025  req.funcid = funcid;
2026  req.node = node;
2027 
2028  /* Initialize cost fields so that support function doesn't have to */
2029  req.startup = 0;
2030  req.per_tuple = 0;
2031 
2032  sresult = (SupportRequestCost *)
2033  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2034  PointerGetDatum(&req)));
2035 
2036  if (sresult == &req)
2037  {
2038  /* Success, so accumulate support function's estimate into *cost */
2039  cost->startup += req.startup;
2040  cost->per_tuple += req.per_tuple;
2041  ReleaseSysCache(proctup);
2042  return;
2043  }
2044  }
2045 
2046  /* No support function, or it failed, so rely on procost */
2047  cost->per_tuple += procform->procost * cpu_operator_cost;
2048 
2049  ReleaseSysCache(proctup);
2050 }
#define OidIsValid(objectId)
Definition: c.h:711
double cpu_operator_cost
Definition: costsize.c:124
#define ERROR
Definition: elog.h:35
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
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:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ PROCOID
Definition: syscache.h:79

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

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

◆ build_index_tlist()

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

Definition at line 1803 of file plancat.c.

1805 {
1806  List *tlist = NIL;
1807  Index varno = index->rel->relid;
1808  ListCell *indexpr_item;
1809  int i;
1810 
1811  indexpr_item = list_head(index->indexprs);
1812  for (i = 0; i < index->ncolumns; i++)
1813  {
1814  int indexkey = index->indexkeys[i];
1815  Expr *indexvar;
1816 
1817  if (indexkey != 0)
1818  {
1819  /* simple column */
1820  const FormData_pg_attribute *att_tup;
1821 
1822  if (indexkey < 0)
1823  att_tup = SystemAttributeDefinition(indexkey);
1824  else
1825  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1826 
1827  indexvar = (Expr *) makeVar(varno,
1828  indexkey,
1829  att_tup->atttypid,
1830  att_tup->atttypmod,
1831  att_tup->attcollation,
1832  0);
1833  }
1834  else
1835  {
1836  /* expression column */
1837  if (indexpr_item == NULL)
1838  elog(ERROR, "wrong number of index expressions");
1839  indexvar = (Expr *) lfirst(indexpr_item);
1840  indexpr_item = lnext(index->indexprs, indexpr_item);
1841  }
1842 
1843  tlist = lappend(tlist,
1844  makeTargetEntry(indexvar,
1845  i + 1,
1846  NULL,
1847  false));
1848  }
1849  if (indexpr_item != NULL)
1850  elog(ERROR, "wrong number of index expressions");
1851 
1852  return tlist;
1853 }
unsigned int Index
Definition: c.h:550
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:239
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:338
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
FormData_pg_attribute
Definition: pg_attribute.h:191
#define lfirst(lc)
Definition: pg_list.h:170
#define NIL
Definition: pg_list.h:66
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
Definition: pg_list.h:52
TupleDesc rd_att
Definition: rel.h:111
Definition: type.h:95
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References elog(), ERROR, FormData_pg_attribute, i, lappend(), lfirst, list_head(), lnext(), makeTargetEntry(), makeVar(), NIL, RelationData::rd_att, SystemAttributeDefinition(), and TupleDescAttr.

Referenced by get_relation_info().

◆ build_physical_tlist()

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1682 of file plancat.c.

1683 {
1684  List *tlist = NIL;
1685  Index varno = rel->relid;
1686  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1687  Relation relation;
1688  Query *subquery;
1689  Var *var;
1690  ListCell *l;
1691  int attrno,
1692  numattrs;
1693  List *colvars;
1694 
1695  switch (rte->rtekind)
1696  {
1697  case RTE_RELATION:
1698  /* Assume we already have adequate lock */
1699  relation = table_open(rte->relid, NoLock);
1700 
1701  numattrs = RelationGetNumberOfAttributes(relation);
1702  for (attrno = 1; attrno <= numattrs; attrno++)
1703  {
1704  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1705  attrno - 1);
1706 
1707  if (att_tup->attisdropped || att_tup->atthasmissing)
1708  {
1709  /* found a dropped or missing col, so punt */
1710  tlist = NIL;
1711  break;
1712  }
1713 
1714  var = makeVar(varno,
1715  attrno,
1716  att_tup->atttypid,
1717  att_tup->atttypmod,
1718  att_tup->attcollation,
1719  0);
1720 
1721  tlist = lappend(tlist,
1722  makeTargetEntry((Expr *) var,
1723  attrno,
1724  NULL,
1725  false));
1726  }
1727 
1728  table_close(relation, NoLock);
1729  break;
1730 
1731  case RTE_SUBQUERY:
1732  subquery = rte->subquery;
1733  foreach(l, subquery->targetList)
1734  {
1735  TargetEntry *tle = (TargetEntry *) lfirst(l);
1736 
1737  /*
1738  * A resjunk column of the subquery can be reflected as
1739  * resjunk in the physical tlist; we need not punt.
1740  */
1741  var = makeVarFromTargetEntry(varno, tle);
1742 
1743  tlist = lappend(tlist,
1744  makeTargetEntry((Expr *) var,
1745  tle->resno,
1746  NULL,
1747  tle->resjunk));
1748  }
1749  break;
1750 
1751  case RTE_FUNCTION:
1752  case RTE_TABLEFUNC:
1753  case RTE_VALUES:
1754  case RTE_CTE:
1755  case RTE_NAMEDTUPLESTORE:
1756  case RTE_RESULT:
1757  /* Not all of these can have dropped cols, but share code anyway */
1758  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1759  NULL, &colvars);
1760  foreach(l, colvars)
1761  {
1762  var = (Var *) lfirst(l);
1763 
1764  /*
1765  * A non-Var in expandRTE's output means a dropped column;
1766  * must punt.
1767  */
1768  if (!IsA(var, Var))
1769  {
1770  tlist = NIL;
1771  break;
1772  }
1773 
1774  tlist = lappend(tlist,
1775  makeTargetEntry((Expr *) var,
1776  var->varattno,
1777  NULL,
1778  false));
1779  }
1780  break;
1781 
1782  default:
1783  /* caller error */
1784  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1785  (int) rte->rtekind);
1786  break;
1787  }
1788 
1789  return tlist;
1790 }
#define NoLock
Definition: lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:103
#define IsA(nodeptr, _type_)
Definition: nodes.h:162
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_CTE
Definition: parsenodes.h:1015
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1016
@ RTE_VALUES
Definition: parsenodes.h:1014
@ RTE_SUBQUERY
Definition: parsenodes.h:1010
@ RTE_RESULT
Definition: parsenodes.h:1017
@ RTE_FUNCTION
Definition: parsenodes.h:1012
@ RTE_TABLEFUNC
Definition: parsenodes.h:1013
@ RTE_RELATION
Definition: parsenodes.h:1009
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:514
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:507
List * targetList
Definition: parsenodes.h:160
Query * subquery
Definition: parsenodes.h:1063
RTEKind rtekind
Definition: parsenodes.h:1028
Index relid
Definition: pathnodes.h:862
AttrNumber resno
Definition: primnodes.h:1556
bool resjunk
Definition: primnodes.h:1562
Definition: primnodes.h:205
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

Referenced by create_scan_plan().

◆ estimate_rel_size()

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

Definition at line 979 of file plancat.c.

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

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().

◆ find_partition_scheme()

static PartitionScheme find_partition_scheme ( PlannerInfo root,
Relation  relation 
)
static

Definition at line 2257 of file plancat.c.

2258 {
2259  PartitionKey partkey = RelationGetPartitionKey(relation);
2260  ListCell *lc;
2261  int partnatts,
2262  i;
2263  PartitionScheme part_scheme;
2264 
2265  /* A partitioned table should have a partition key. */
2266  Assert(partkey != NULL);
2267 
2268  partnatts = partkey->partnatts;
2269 
2270  /* Search for a matching partition scheme and return if found one. */
2271  foreach(lc, root->part_schemes)
2272  {
2273  part_scheme = lfirst(lc);
2274 
2275  /* Match partitioning strategy and number of keys. */
2276  if (partkey->strategy != part_scheme->strategy ||
2277  partnatts != part_scheme->partnatts)
2278  continue;
2279 
2280  /* Match partition key type properties. */
2281  if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2282  sizeof(Oid) * partnatts) != 0 ||
2283  memcmp(partkey->partopcintype, part_scheme->partopcintype,
2284  sizeof(Oid) * partnatts) != 0 ||
2285  memcmp(partkey->partcollation, part_scheme->partcollation,
2286  sizeof(Oid) * partnatts) != 0)
2287  continue;
2288 
2289  /*
2290  * Length and byval information should match when partopcintype
2291  * matches.
2292  */
2293  Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2294  sizeof(int16) * partnatts) == 0);
2295  Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2296  sizeof(bool) * partnatts) == 0);
2297 
2298  /*
2299  * If partopfamily and partopcintype matched, must have the same
2300  * partition comparison functions. Note that we cannot reliably
2301  * Assert the equality of function structs themselves for they might
2302  * be different across PartitionKey's, so just Assert for the function
2303  * OIDs.
2304  */
2305 #ifdef USE_ASSERT_CHECKING
2306  for (i = 0; i < partkey->partnatts; i++)
2307  Assert(partkey->partsupfunc[i].fn_oid ==
2308  part_scheme->partsupfunc[i].fn_oid);
2309 #endif
2310 
2311  /* Found matching partition scheme. */
2312  return part_scheme;
2313  }
2314 
2315  /*
2316  * Did not find matching partition scheme. Create one copying relevant
2317  * information from the relcache. We need to copy the contents of the
2318  * array since the relcache entry may not survive after we have closed the
2319  * relation.
2320  */
2321  part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
2322  part_scheme->strategy = partkey->strategy;
2323  part_scheme->partnatts = partkey->partnatts;
2324 
2325  part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
2326  memcpy(part_scheme->partopfamily, partkey->partopfamily,
2327  sizeof(Oid) * partnatts);
2328 
2329  part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
2330  memcpy(part_scheme->partopcintype, partkey->partopcintype,
2331  sizeof(Oid) * partnatts);
2332 
2333  part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
2334  memcpy(part_scheme->partcollation, partkey->partcollation,
2335  sizeof(Oid) * partnatts);
2336 
2337  part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
2338  memcpy(part_scheme->parttyplen, partkey->parttyplen,
2339  sizeof(int16) * partnatts);
2340 
2341  part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
2342  memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2343  sizeof(bool) * partnatts);
2344 
2345  part_scheme->partsupfunc = (FmgrInfo *)
2346  palloc(sizeof(FmgrInfo) * partnatts);
2347  for (i = 0; i < partnatts; i++)
2348  fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2350 
2351  /* Add the partitioning scheme to PlannerInfo. */
2352  root->part_schemes = lappend(root->part_schemes, part_scheme);
2353 
2354  return part_scheme;
2355 }
signed short int16
Definition: c.h:429
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:594
Assert(fmt[strlen(fmt) - 1] !='\n')
void * palloc0(Size size)
Definition: mcxt.c:1230
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
void * palloc(Size size)
Definition: mcxt.c:1199
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
struct PartitionSchemeData * PartitionScheme
Definition: pathnodes.h:548
unsigned int Oid
Definition: postgres_ext.h:31
Definition: fmgr.h:57
Oid fn_oid
Definition: fmgr.h:59
Oid * partcollation
Definition: partcache.h:39
Oid * partopfamily
Definition: partcache.h:34
bool * parttypbyval
Definition: partcache.h:45
PartitionStrategy strategy
Definition: partcache.h:27
int16 * parttyplen
Definition: partcache.h:44
FmgrInfo * partsupfunc
Definition: partcache.h:36
Oid * partopcintype
Definition: partcache.h:35
struct FmgrInfo * partsupfunc
Definition: pathnodes.h:545

References Assert(), CurrentMemoryContext, fmgr_info_copy(), FmgrInfo::fn_oid, i, lappend(), lfirst, palloc(), palloc0(), PartitionSchemeData::partcollation, PartitionKeyData::partcollation, PartitionSchemeData::partnatts, PartitionKeyData::partnatts, PartitionSchemeData::partopcintype, PartitionKeyData::partopcintype, PartitionSchemeData::partopfamily, PartitionKeyData::partopfamily, PartitionSchemeData::partsupfunc, PartitionKeyData::partsupfunc, PartitionSchemeData::parttypbyval, PartitionKeyData::parttypbyval, PartitionSchemeData::parttyplen, PartitionKeyData::parttyplen, RelationGetPartitionKey(), PartitionSchemeData::strategy, and PartitionKeyData::strategy.

Referenced by set_relation_partition_info().

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

1953 {
1954  RegProcedure prosupport = get_func_support(funcid);
1956  SupportRequestSelectivity *sresult;
1957 
1958  /*
1959  * If no support function is provided, use our historical default
1960  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
1961  * Postgres has been using that estimate for function calls since 1992.
1962  * The hoariness of this behavior suggests that we should not be in too
1963  * much hurry to use another value.
1964  */
1965  if (!prosupport)
1966  return (Selectivity) 0.3333333;
1967 
1968  req.type = T_SupportRequestSelectivity;
1969  req.root = root;
1970  req.funcid = funcid;
1971  req.args = args;
1972  req.inputcollid = inputcollid;
1973  req.is_join = is_join;
1974  req.varRelid = varRelid;
1975  req.jointype = jointype;
1976  req.sjinfo = sjinfo;
1977  req.selectivity = -1; /* to catch failure to set the value */
1978 
1979  sresult = (SupportRequestSelectivity *)
1980  DatumGetPointer(OidFunctionCall1(prosupport,
1981  PointerGetDatum(&req)));
1982 
1983  /* If support function fails, use default */
1984  if (sresult != &req)
1985  return (Selectivity) 0.3333333;
1986 
1987  if (req.selectivity < 0.0 || req.selectivity > 1.0)
1988  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
1989 
1990  return (Selectivity) req.selectivity;
1991 }
regproc RegProcedure
Definition: c.h:586
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1840
double Selectivity
Definition: nodes.h:244
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(), SupportRequestSelectivity::root, SupportRequestSelectivity::selectivity, SupportRequestSelectivity::sjinfo, SupportRequestSelectivity::type, and SupportRequestSelectivity::varRelid.

Referenced by clause_selectivity_ext().

◆ get_function_rows()

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

Definition at line 2068 of file plancat.c.

2069 {
2070  HeapTuple proctup;
2071  Form_pg_proc procform;
2072  double result;
2073 
2074  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2075  if (!HeapTupleIsValid(proctup))
2076  elog(ERROR, "cache lookup failed for function %u", funcid);
2077  procform = (Form_pg_proc) GETSTRUCT(proctup);
2078 
2079  Assert(procform->proretset); /* else caller error */
2080 
2081  if (OidIsValid(procform->prosupport))
2082  {
2083  SupportRequestRows req;
2084  SupportRequestRows *sresult;
2085 
2086  req.type = T_SupportRequestRows;
2087  req.root = root;
2088  req.funcid = funcid;
2089  req.node = node;
2090 
2091  req.rows = 0; /* just for sanity */
2092 
2093  sresult = (SupportRequestRows *)
2094  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2095  PointerGetDatum(&req)));
2096 
2097  if (sresult == &req)
2098  {
2099  /* Success */
2100  ReleaseSysCache(proctup);
2101  return req.rows;
2102  }
2103  }
2104 
2105  /* No support function, or it failed, so rely on prorows */
2106  result = procform->prorows;
2107 
2108  ReleaseSysCache(proctup);
2109 
2110  return result;
2111 }
struct PlannerInfo * root
Definition: supportnodes.h:163

References Assert(), DatumGetPointer(), elog(), ERROR, SupportRequestRows::funcid, GETSTRUCT, HeapTupleIsValid, SupportRequestRows::node, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, PointerGetDatum(), PROCOID, ReleaseSysCache(), 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 1104 of file plancat.c.

1105 {
1106  int32 tuple_width = 0;
1107  int i;
1108 
1109  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1110  {
1111  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1112  int32 item_width;
1113 
1114  if (att->attisdropped)
1115  continue;
1116 
1117  /* use previously cached data, if any */
1118  if (attr_widths != NULL && attr_widths[i] > 0)
1119  {
1120  tuple_width += attr_widths[i];
1121  continue;
1122  }
1123 
1124  /* This should match set_rel_width() in costsize.c */
1125  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1126  if (item_width <= 0)
1127  {
1128  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1129  Assert(item_width > 0);
1130  }
1131  if (attr_widths != NULL)
1132  attr_widths[i] = item_width;
1133  tuple_width += item_width;
1134  }
1135 
1136  return tuple_width;
1137 }
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3116
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2536
#define RelationGetRelid(relation)
Definition: rel.h:501

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

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

◆ get_relation_constraints()

static List * get_relation_constraints ( PlannerInfo root,
Oid  relationObjectId,
RelOptInfo rel,
bool  include_noinherit,
bool  include_notnull,
bool  include_partition 
)
static

Definition at line 1186 of file plancat.c.

1191 {
1192  List *result = NIL;
1193  Index varno = rel->relid;
1194  Relation relation;
1195  TupleConstr *constr;
1196 
1197  /*
1198  * We assume the relation has already been safely locked.
1199  */
1200  relation = table_open(relationObjectId, NoLock);
1201 
1202  constr = relation->rd_att->constr;
1203  if (constr != NULL)
1204  {
1205  int num_check = constr->num_check;
1206  int i;
1207 
1208  for (i = 0; i < num_check; i++)
1209  {
1210  Node *cexpr;
1211 
1212  /*
1213  * If this constraint hasn't been fully validated yet, we must
1214  * ignore it here. Also ignore if NO INHERIT and we weren't told
1215  * that that's safe.
1216  */
1217  if (!constr->check[i].ccvalid)
1218  continue;
1219  if (constr->check[i].ccnoinherit && !include_noinherit)
1220  continue;
1221 
1222  cexpr = stringToNode(constr->check[i].ccbin);
1223 
1224  /*
1225  * Run each expression through const-simplification and
1226  * canonicalization. This is not just an optimization, but is
1227  * necessary, because we will be comparing it to
1228  * similarly-processed qual clauses, and may fail to detect valid
1229  * matches without this. This must match the processing done to
1230  * qual clauses in preprocess_expression()! (We can skip the
1231  * stuff involving subqueries, however, since we don't allow any
1232  * in check constraints.)
1233  */
1234  cexpr = eval_const_expressions(root, cexpr);
1235 
1236  cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1237 
1238  /* Fix Vars to have the desired varno */
1239  if (varno != 1)
1240  ChangeVarNodes(cexpr, 1, varno, 0);
1241 
1242  /*
1243  * Finally, convert to implicit-AND format (that is, a List) and
1244  * append the resulting item(s) to our output list.
1245  */
1246  result = list_concat(result,
1247  make_ands_implicit((Expr *) cexpr));
1248  }
1249 
1250  /* Add NOT NULL constraints in expression form, if requested */
1251  if (include_notnull && constr->has_not_null)
1252  {
1253  int natts = relation->rd_att->natts;
1254 
1255  for (i = 1; i <= natts; i++)
1256  {
1257  Form_pg_attribute att = TupleDescAttr(relation->rd_att, i - 1);
1258 
1259  if (att->attnotnull && !att->attisdropped)
1260  {
1261  NullTest *ntest = makeNode(NullTest);
1262 
1263  ntest->arg = (Expr *) makeVar(varno,
1264  i,
1265  att->atttypid,
1266  att->atttypmod,
1267  att->attcollation,
1268  0);
1269  ntest->nulltesttype = IS_NOT_NULL;
1270 
1271  /*
1272  * argisrow=false is correct even for a composite column,
1273  * because attnotnull does not represent a SQL-spec IS NOT
1274  * NULL test in such a case, just IS DISTINCT FROM NULL.
1275  */
1276  ntest->argisrow = false;
1277  ntest->location = -1;
1278  result = lappend(result, ntest);
1279  }
1280  }
1281  }
1282  }
1283 
1284  /*
1285  * Add partitioning constraints, if requested.
1286  */
1287  if (include_partition && relation->rd_rel->relispartition)
1288  {
1289  /* make sure rel->partition_qual is set */
1290  set_baserel_partition_constraint(relation, rel);
1291  result = list_concat(result, rel->partition_qual);
1292  }
1293 
1294  table_close(relation, NoLock);
1295 
1296  return result;
1297 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2132
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
#define makeNode(_type_)
Definition: nodes.h:159
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2432
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:294
@ IS_NOT_NULL
Definition: primnodes.h:1359
void * stringToNode(const char *str)
Definition: read.c:90
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
bool ccnoinherit
Definition: tupdesc.h:33
bool ccvalid
Definition: tupdesc.h:32
char * ccbin
Definition: tupdesc.h:31
Definition: nodes.h:112
NullTestType nulltesttype
Definition: primnodes.h:1366
int location
Definition: primnodes.h:1368
bool argisrow
Definition: primnodes.h:1367
Expr * arg
Definition: primnodes.h:1365
List * partition_qual
Definition: pathnodes.h:966
bool has_not_null
Definition: tupdesc.h:44
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:85

References NullTest::arg, NullTest::argisrow, canonicalize_qual(), ConstrCheck::ccbin, ConstrCheck::ccnoinherit, ConstrCheck::ccvalid, ChangeVarNodes(), TupleConstr::check, TupleDescData::constr, eval_const_expressions(), TupleConstr::has_not_null, i, IS_NOT_NULL, lappend(), list_concat(), NullTest::location, make_ands_implicit(), makeNode, makeVar(), TupleDescData::natts, NIL, NoLock, NullTest::nulltesttype, TupleConstr::num_check, RelOptInfo::partition_qual, RelationData::rd_att, RelationData::rd_rel, RelOptInfo::relid, set_baserel_partition_constraint(), stringToNode(), table_close(), table_open(), and TupleDescAttr.

Referenced by relation_excluded_by_constraints().

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1146 of file plancat.c.

1147 {
1148  int32 result;
1149  Relation relation;
1150 
1151  /* As above, assume relation is already locked */
1152  relation = table_open(relid, NoLock);
1153 
1154  result = get_rel_data_width(relation, attr_widths);
1155 
1156  table_close(relation, NoLock);
1157 
1158  return result;
1159 }

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

◆ get_relation_foreign_keys()

static void get_relation_foreign_keys ( PlannerInfo root,
RelOptInfo rel,
Relation  relation,
bool  inhparent 
)
static

Definition at line 516 of file plancat.c.

518 {
519  List *rtable = root->parse->rtable;
520  List *cachedfkeys;
521  ListCell *lc;
522 
523  /*
524  * If it's not a baserel, we don't care about its FKs. Also, if the query
525  * references only a single relation, we can skip the lookup since no FKs
526  * could satisfy the requirements below.
527  */
528  if (rel->reloptkind != RELOPT_BASEREL ||
529  list_length(rtable) < 2)
530  return;
531 
532  /*
533  * If it's the parent of an inheritance tree, ignore its FKs. We could
534  * make useful FK-based deductions if we found that all members of the
535  * inheritance tree have equivalent FK constraints, but detecting that
536  * would require code that hasn't been written.
537  */
538  if (inhparent)
539  return;
540 
541  /*
542  * Extract data about relation's FKs from the relcache. Note that this
543  * list belongs to the relcache and might disappear in a cache flush, so
544  * we must not do any further catalog access within this function.
545  */
546  cachedfkeys = RelationGetFKeyList(relation);
547 
548  /*
549  * Figure out which FKs are of interest for this query, and create
550  * ForeignKeyOptInfos for them. We want only FKs that reference some
551  * other RTE of the current query. In queries containing self-joins,
552  * there might be more than one other RTE for a referenced table, and we
553  * should make a ForeignKeyOptInfo for each occurrence.
554  *
555  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
556  * too hard to identify those here, so we might end up making some useless
557  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
558  * them again.
559  */
560  foreach(lc, cachedfkeys)
561  {
562  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
563  Index rti;
564  ListCell *lc2;
565 
566  /* conrelid should always be that of the table we're considering */
567  Assert(cachedfk->conrelid == RelationGetRelid(relation));
568 
569  /* Scan to find other RTEs matching confrelid */
570  rti = 0;
571  foreach(lc2, rtable)
572  {
573  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
574  ForeignKeyOptInfo *info;
575 
576  rti++;
577  /* Ignore if not the correct table */
578  if (rte->rtekind != RTE_RELATION ||
579  rte->relid != cachedfk->confrelid)
580  continue;
581  /* Ignore if it's an inheritance parent; doesn't really match */
582  if (rte->inh)
583  continue;
584  /* Ignore self-referential FKs; we only care about joins */
585  if (rti == rel->relid)
586  continue;
587 
588  /* OK, let's make an entry */
589  info = makeNode(ForeignKeyOptInfo);
590  info->con_relid = rel->relid;
591  info->ref_relid = rti;
592  info->nkeys = cachedfk->nkeys;
593  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
594  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
595  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
596  /* zero out fields to be filled by match_foreign_keys_to_quals */
597  info->nmatched_ec = 0;
598  info->nconst_ec = 0;
599  info->nmatched_rcols = 0;
600  info->nmatched_ri = 0;
601  memset(info->eclass, 0, sizeof(info->eclass));
602  memset(info->fk_eclass_member, 0, sizeof(info->fk_eclass_member));
603  memset(info->rinfos, 0, sizeof(info->rinfos));
604 
605  root->fkey_list = lappend(root->fkey_list, info);
606  }
607  }
608 }
@ RELOPT_BASEREL
Definition: pathnodes.h:770
static int list_length(const List *l)
Definition: pg_list.h:150
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4622
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1195
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:1199
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1197
List * fkey_list
Definition: pathnodes.h:366
Query * parse
Definition: pathnodes.h:196
List * rtable
Definition: parsenodes.h:153
RelOptKind reloptkind
Definition: pathnodes.h:809

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

Referenced by get_relation_info().

◆ 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  * Estimate relation size --- unless it's an inheritance parent, in which
166  * case the size we want is not the rel's own size but the size of its
167  * inheritance tree. That will be computed in set_append_rel_size().
168  */
169  if (!inhparent)
170  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
171  &rel->pages, &rel->tuples, &rel->allvisfrac);
172 
173  /* Retrieve the parallel_workers reloption, or -1 if not set. */
175 
176  /*
177  * Make list of indexes. Ignore indexes on system catalogs if told to.
178  * Don't bother with indexes for an inheritance parent, either.
179  */
180  if (inhparent ||
181  (IgnoreSystemIndexes && IsSystemRelation(relation)))
182  hasindex = false;
183  else
184  hasindex = relation->rd_rel->relhasindex;
185 
186  if (hasindex)
187  {
188  List *indexoidlist;
189  LOCKMODE lmode;
190  ListCell *l;
191 
192  indexoidlist = RelationGetIndexList(relation);
193 
194  /*
195  * For each index, we get the same type of lock that the executor will
196  * need, and do not release it. This saves a couple of trips to the
197  * shared lock manager while not creating any real loss of
198  * concurrency, because no schema changes could be happening on the
199  * index while we hold lock on the parent rel, and no lock type used
200  * for queries blocks any other kind of index operation.
201  */
202  lmode = root->simple_rte_array[varno]->rellockmode;
203 
204  foreach(l, indexoidlist)
205  {
206  Oid indexoid = lfirst_oid(l);
207  Relation indexRelation;
209  IndexAmRoutine *amroutine;
210  IndexOptInfo *info;
211  int ncolumns,
212  nkeycolumns;
213  int i;
214 
215  /*
216  * Extract info from the relation descriptor for the index.
217  */
218  indexRelation = index_open(indexoid, lmode);
219  index = indexRelation->rd_index;
220 
221  /*
222  * Ignore invalid indexes, since they can't safely be used for
223  * queries. Note that this is OK because the data structure we
224  * are constructing is only used by the planner --- the executor
225  * still needs to insert into "invalid" indexes, if they're marked
226  * indisready.
227  */
228  if (!index->indisvalid)
229  {
230  index_close(indexRelation, NoLock);
231  continue;
232  }
233 
234  /*
235  * Ignore partitioned indexes, since they are not usable for
236  * queries.
237  */
238  if (indexRelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
239  {
240  index_close(indexRelation, NoLock);
241  continue;
242  }
243 
244  /*
245  * If the index is valid, but cannot yet be used, ignore it; but
246  * mark the plan we are generating as transient. See
247  * src/backend/access/heap/README.HOT for discussion.
248  */
249  if (index->indcheckxmin &&
252  {
253  root->glob->transientPlan = true;
254  index_close(indexRelation, NoLock);
255  continue;
256  }
257 
258  info = makeNode(IndexOptInfo);
259 
260  info->indexoid = index->indexrelid;
261  info->reltablespace =
262  RelationGetForm(indexRelation)->reltablespace;
263  info->rel = rel;
264  info->ncolumns = ncolumns = index->indnatts;
265  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
266 
267  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
268  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
269  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
270  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
271  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
272 
273  for (i = 0; i < ncolumns; i++)
274  {
275  info->indexkeys[i] = index->indkey.values[i];
276  info->canreturn[i] = index_can_return(indexRelation, i + 1);
277  }
278 
279  for (i = 0; i < nkeycolumns; i++)
280  {
281  info->opfamily[i] = indexRelation->rd_opfamily[i];
282  info->opcintype[i] = indexRelation->rd_opcintype[i];
283  info->indexcollations[i] = indexRelation->rd_indcollation[i];
284  }
285 
286  info->relam = indexRelation->rd_rel->relam;
287 
288  /* We copy just the fields we need, not all of rd_indam */
289  amroutine = indexRelation->rd_indam;
290  info->amcanorderbyop = amroutine->amcanorderbyop;
291  info->amoptionalkey = amroutine->amoptionalkey;
292  info->amsearcharray = amroutine->amsearcharray;
293  info->amsearchnulls = amroutine->amsearchnulls;
294  info->amcanparallel = amroutine->amcanparallel;
295  info->amhasgettuple = (amroutine->amgettuple != NULL);
296  info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
297  relation->rd_tableam->scan_bitmap_next_block != NULL;
298  info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
299  amroutine->amrestrpos != NULL);
300  info->amcostestimate = amroutine->amcostestimate;
301  Assert(info->amcostestimate != NULL);
302 
303  /* Fetch index opclass options */
304  info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
305 
306  /*
307  * Fetch the ordering information for the index, if any.
308  */
309  if (info->relam == BTREE_AM_OID)
310  {
311  /*
312  * If it's a btree index, we can use its opfamily OIDs
313  * directly as the sort ordering opfamily OIDs.
314  */
315  Assert(amroutine->amcanorder);
316 
317  info->sortopfamily = info->opfamily;
318  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
319  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
320 
321  for (i = 0; i < nkeycolumns; i++)
322  {
323  int16 opt = indexRelation->rd_indoption[i];
324 
325  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
326  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
327  }
328  }
329  else if (amroutine->amcanorder)
330  {
331  /*
332  * Otherwise, identify the corresponding btree opfamilies by
333  * trying to map this index's "<" operators into btree. Since
334  * "<" uniquely defines the behavior of a sort order, this is
335  * a sufficient test.
336  *
337  * XXX This method is rather slow and also requires the
338  * undesirable assumption that the other index AM numbers its
339  * strategies the same as btree. It'd be better to have a way
340  * to explicitly declare the corresponding btree opfamily for
341  * each opfamily of the other index type. But given the lack
342  * of current or foreseeable amcanorder index types, it's not
343  * worth expending more effort on now.
344  */
345  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
346  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
347  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
348 
349  for (i = 0; i < nkeycolumns; i++)
350  {
351  int16 opt = indexRelation->rd_indoption[i];
352  Oid ltopr;
353  Oid btopfamily;
354  Oid btopcintype;
355  int16 btstrategy;
356 
357  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
358  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
359 
360  ltopr = get_opfamily_member(info->opfamily[i],
361  info->opcintype[i],
362  info->opcintype[i],
364  if (OidIsValid(ltopr) &&
366  &btopfamily,
367  &btopcintype,
368  &btstrategy) &&
369  btopcintype == info->opcintype[i] &&
370  btstrategy == BTLessStrategyNumber)
371  {
372  /* Successful mapping */
373  info->sortopfamily[i] = btopfamily;
374  }
375  else
376  {
377  /* Fail ... quietly treat index as unordered */
378  info->sortopfamily = NULL;
379  info->reverse_sort = NULL;
380  info->nulls_first = NULL;
381  break;
382  }
383  }
384  }
385  else
386  {
387  info->sortopfamily = NULL;
388  info->reverse_sort = NULL;
389  info->nulls_first = NULL;
390  }
391 
392  /*
393  * Fetch the index expressions and predicate, if any. We must
394  * modify the copies we obtain from the relcache to have the
395  * correct varno for the parent relation, so that they match up
396  * correctly against qual clauses.
397  */
398  info->indexprs = RelationGetIndexExpressions(indexRelation);
399  info->indpred = RelationGetIndexPredicate(indexRelation);
400  if (info->indexprs && varno != 1)
401  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
402  if (info->indpred && varno != 1)
403  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
404 
405  /* Build targetlist using the completed indexprs data */
406  info->indextlist = build_index_tlist(root, info, relation);
407 
408  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
409  info->predOK = false; /* set later, in indxpath.c */
410  info->unique = index->indisunique;
411  info->immediate = index->indimmediate;
412  info->hypothetical = false;
413 
414  /*
415  * Estimate the index size. If it's not a partial index, we lock
416  * the number-of-tuples estimate to equal the parent table; if it
417  * is partial then we have to use the same methods as we would for
418  * a table, except we can be sure that the index is not larger
419  * than the table.
420  */
421  if (info->indpred == NIL)
422  {
423  info->pages = RelationGetNumberOfBlocks(indexRelation);
424  info->tuples = rel->tuples;
425  }
426  else
427  {
428  double allvisfrac; /* dummy */
429 
430  estimate_rel_size(indexRelation, NULL,
431  &info->pages, &info->tuples, &allvisfrac);
432  if (info->tuples > rel->tuples)
433  info->tuples = rel->tuples;
434  }
435 
436  if (info->relam == BTREE_AM_OID)
437  {
438  /* For btrees, get tree height while we have the index open */
439  info->tree_height = _bt_getrootheight(indexRelation);
440  }
441  else
442  {
443  /* For other index types, just set it to "unknown" for now */
444  info->tree_height = -1;
445  }
446 
447  index_close(indexRelation, NoLock);
448 
449  /*
450  * We've historically used lcons() here. It'd make more sense to
451  * use lappend(), but that causes the planner to change behavior
452  * in cases where two indexes seem equally attractive. For now,
453  * stick with lcons() --- few tables should have so many indexes
454  * that the O(N^2) behavior of lcons() is really a problem.
455  */
456  indexinfos = lcons(info, indexinfos);
457  }
458 
459  list_free(indexoidlist);
460  }
461 
462  rel->indexlist = indexinfos;
463 
464  rel->statlist = get_relation_statistics(rel, relation);
465 
466  /* Grab foreign-table info using the relcache, while we have it */
467  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
468  {
470  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
471  }
472  else
473  {
474  rel->serverid = InvalidOid;
475  rel->fdwroutine = NULL;
476  }
477 
478  /* Collect info about relation's foreign keys, if relevant */
479  get_relation_foreign_keys(root, rel, relation, inhparent);
480 
481  /* Collect info about functions implemented by the rel's table AM. */
482  if (relation->rd_tableam &&
483  relation->rd_tableam->scan_set_tidrange != NULL &&
484  relation->rd_tableam->scan_getnextslot_tidrange != NULL)
486 
487  /*
488  * Collect info about relation's partitioning scheme, if any. Only
489  * inheritance parents may be partitioned.
490  */
491  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
492  set_relation_partition_info(root, rel, relation);
493 
494  table_close(relation, NoLock);
495 
496  /*
497  * Allow a plugin to editorialize on the info we obtained from the
498  * catalogs. Actions might include altering the assumed relation size,
499  * removing an index, or adding a hypothetical index to the indexlist.
500  */
502  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
503 }
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:429
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:342
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:308
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:731
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void list_free(List *list)
Definition: list.c:1545
List * lcons(void *datum, List *list)
Definition: list.c:494
int LOCKMODE
Definition: lockdefs.h:26
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:206
bool IgnoreSystemIndexes
Definition: miscinit.c:80
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:672
Bitmapset * Relids
Definition: pathnodes.h:30
#define AMFLAG_HAS_TID_RANGE
Definition: pathnodes.h:766
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:172
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:979
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:516
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:61
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1803
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1389
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:2227
#define InvalidOid
Definition: postgres_ext.h:36
#define RelationGetForm(relation)
Definition: rel.h:495
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:393
#define RelationGetRelationName(relation)
Definition: rel.h:535
#define RelationIsPermanent(relation)
Definition: rel.h:615
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4731
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5078
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5808
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4965
TransactionId TransactionXmin
Definition: snapmgr.c:113
#define BTLessStrategyNumber
Definition: stratnum.h:29
HeapTupleHeader t_data
Definition: htup.h:68
amrestrpos_function amrestrpos
Definition: amapi.h:277
amcostestimate_function amcostestimate
Definition: amapi.h:265
bool amcanorderbyop
Definition: amapi.h:222
bool amoptionalkey
Definition: amapi.h:230
amgettuple_function amgettuple
Definition: amapi.h:273
amgetbitmap_function amgetbitmap
Definition: amapi.h:274
bool amsearcharray
Definition: amapi.h:232
ammarkpos_function ammarkpos
Definition: amapi.h:276
bool amcanparallel
Definition: amapi.h:242
bool amcanorder
Definition: amapi.h:220
bool amsearchnulls
Definition: amapi.h:234
bool amcanparallel
Definition: pathnodes.h:1143
bool amoptionalkey
Definition: pathnodes.h:1136
Oid reltablespace
Definition: pathnodes.h:1058
bool amcanmarkpos
Definition: pathnodes.h:1145
List * indrestrictinfo
Definition: pathnodes.h:1120
void(* amcostestimate)() pg_node_attr(read_write_ignore)
Definition: pathnodes.h:1148
bool amhasgettuple
Definition: pathnodes.h:1140
bool amcanorderbyop
Definition: pathnodes.h:1135
bool hypothetical
Definition: pathnodes.h:1129
List * indpred
Definition: pathnodes.h:1110
Cardinality tuples
Definition: pathnodes.h:1068
bool amsearcharray
Definition: pathnodes.h:1137
BlockNumber pages
Definition: pathnodes.h:1066
bool amsearchnulls
Definition: pathnodes.h:1138
bool amhasgetbitmap
Definition: pathnodes.h:1142
List * indextlist
Definition: pathnodes.h:1113
bool immediate
Definition: pathnodes.h:1127
bool transientPlan
Definition: pathnodes.h:144
PlannerGlobal * glob
Definition: pathnodes.h:199
uint32 amflags
Definition: pathnodes.h:897
List * statlist
Definition: pathnodes.h:882
Cardinality tuples
Definition: pathnodes.h:885
BlockNumber pages
Definition: pathnodes.h:884
List * indexlist
Definition: pathnodes.h:880
Oid reltablespace
Definition: pathnodes.h:864
Oid serverid
Definition: pathnodes.h:903
int rel_parallel_workers
Definition: pathnodes.h:895
AttrNumber max_attr
Definition: pathnodes.h:870
double allvisfrac
Definition: pathnodes.h:886
AttrNumber min_attr
Definition: pathnodes.h:868
const struct TableAmRoutine * rd_tableam
Definition: rel.h:185
struct IndexAmRoutine * rd_indam
Definition: rel.h:202
Oid * rd_opcintype
Definition: rel.h:204
struct HeapTupleData * rd_indextuple
Definition: rel.h:190
int16 * rd_indoption
Definition: rel.h:207
Form_pg_index rd_index
Definition: rel.h:188
Oid * rd_opfamily
Definition: rel.h:203
Oid * rd_indcollation
Definition: rel.h:213
bool(* scan_getnextslot_tidrange)(TableScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:356
void(* scan_set_tidrange)(TableScanDesc scan, ItemPointer mintid, ItemPointer maxtid)
Definition: tableam.h:348
bool(* scan_bitmap_next_block)(TableScanDesc scan, struct TBMIterateResult *tbmres)
Definition: tableam.h:790
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:273
bool RecoveryInProgress(void)
Definition: xlog.c:5912

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(), BTLessStrategyNumber, build_index_tlist(), ChangeVarNodes(), ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, estimate_rel_size(), FirstLowInvalidHeapAttributeNumber, get_opfamily_member(), get_ordering_op_properties(), get_relation_foreign_keys(), get_relation_info_hook, get_relation_statistics(), GetFdwRoutineForRelation(), GetForeignServerIdByRelId(), PlannerInfo::glob, HeapTupleHeaderGetXmin, IndexOptInfo::hypothetical, i, IgnoreSystemIndexes, IndexOptInfo::immediate, index_can_return(), index_close(), index_open(), RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indextlist, IndexOptInfo::indpred, IndexOptInfo::indrestrictinfo, InvalidOid, IsSystemRelation(), lcons(), lfirst_oid, list_free(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, NoLock, OidIsValid, RelOptInfo::pages, IndexOptInfo::pages, palloc(), palloc0(), IndexOptInfo::predOK, RelationData::rd_indam, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_opcintype, RelationData::rd_opfamily, RelationData::rd_rel, RelationData::rd_tableam, RecoveryInProgress(), RelOptInfo::rel_parallel_workers, IndexOptInfo::relam, RelationGetForm, RelationGetIndexAttOptions(), RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNumberOfAttributes, RelationGetNumberOfBlocks, RelationGetParallelWorkers, RelationGetRelationName, RelationGetRelid, RelationIsPermanent, RelOptInfo::relid, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, 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, PlannerGlobal::transientPlan, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by build_simple_rel().

◆ get_relation_statistics()

static List * get_relation_statistics ( RelOptInfo rel,
Relation  relation 
)
static

Definition at line 1389 of file plancat.c.

1390 {
1391  Index varno = rel->relid;
1392  List *statoidlist;
1393  List *stainfos = NIL;
1394  ListCell *l;
1395 
1396  statoidlist = RelationGetStatExtList(relation);
1397 
1398  foreach(l, statoidlist)
1399  {
1400  Oid statOid = lfirst_oid(l);
1401  Form_pg_statistic_ext staForm;
1402  HeapTuple htup;
1403  Bitmapset *keys = NULL;
1404  List *exprs = NIL;
1405  int i;
1406 
1407  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1408  if (!HeapTupleIsValid(htup))
1409  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1410  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1411 
1412  /*
1413  * First, build the array of columns covered. This is ultimately
1414  * wasted if no stats within the object have actually been built, but
1415  * it doesn't seem worth troubling over that case.
1416  */
1417  for (i = 0; i < staForm->stxkeys.dim1; i++)
1418  keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1419 
1420  /*
1421  * Preprocess expressions (if any). We read the expressions, run them
1422  * through eval_const_expressions, and fix the varnos.
1423  *
1424  * XXX We don't know yet if there are any data for this stats object,
1425  * with either stxdinherit value. But it's reasonable to assume there
1426  * is at least one of those, possibly both. So it's better to process
1427  * keys and expressions here.
1428  */
1429  {
1430  bool isnull;
1431  Datum datum;
1432 
1433  /* decode expression (if any) */
1434  datum = SysCacheGetAttr(STATEXTOID, htup,
1435  Anum_pg_statistic_ext_stxexprs, &isnull);
1436 
1437  if (!isnull)
1438  {
1439  char *exprsString;
1440 
1441  exprsString = TextDatumGetCString(datum);
1442  exprs = (List *) stringToNode(exprsString);
1443  pfree(exprsString);
1444 
1445  /*
1446  * Run the expressions through eval_const_expressions. This is
1447  * not just an optimization, but is necessary, because the
1448  * planner will be comparing them to similarly-processed qual
1449  * clauses, and may fail to detect valid matches without this.
1450  * We must not use canonicalize_qual, however, since these
1451  * aren't qual expressions.
1452  */
1453  exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
1454 
1455  /* May as well fix opfuncids too */
1456  fix_opfuncids((Node *) exprs);
1457 
1458  /*
1459  * Modify the copies we obtain from the relcache to have the
1460  * correct varno for the parent relation, so that they match
1461  * up correctly against qual clauses.
1462  */
1463  if (varno != 1)
1464  ChangeVarNodes((Node *) exprs, 1, varno, 0);
1465  }
1466  }
1467 
1468  /* extract statistics for possible values of stxdinherit flag */
1469 
1470  get_relation_statistics_worker(&stainfos, rel, statOid, true, keys, exprs);
1471 
1472  get_relation_statistics_worker(&stainfos, rel, statOid, false, keys, exprs);
1473 
1474  ReleaseSysCache(htup);
1475  bms_free(keys);
1476  }
1477 
1478  list_free(statoidlist);
1479 
1480  return stainfos;
1481 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:209
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
#define TextDatumGetCString(d)
Definition: builtins.h:86
void pfree(void *pointer)
Definition: mcxt.c:1306
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1641
FormData_pg_statistic_ext * Form_pg_statistic_ext
static void get_relation_statistics_worker(List **stainfos, RelOptInfo *rel, Oid statOid, bool inh, Bitmapset *keys, List *exprs)
Definition: plancat.c:1306
uintptr_t Datum
Definition: postgres.h:412
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4850
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ STATEXTOID
Definition: syscache.h:96

References bms_add_member(), bms_free(), ChangeVarNodes(), elog(), ERROR, eval_const_expressions(), fix_opfuncids(), get_relation_statistics_worker(), GETSTRUCT, HeapTupleIsValid, i, lfirst_oid, list_free(), NIL, ObjectIdGetDatum(), pfree(), RelationGetStatExtList(), ReleaseSysCache(), RelOptInfo::relid, SearchSysCache1(), STATEXTOID, stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

Referenced by get_relation_info().

◆ get_relation_statistics_worker()

static void get_relation_statistics_worker ( List **  stainfos,
RelOptInfo rel,
Oid  statOid,
bool  inh,
Bitmapset keys,
List exprs 
)
static

Definition at line 1306 of file plancat.c.

1309 {
1310  Form_pg_statistic_ext_data dataForm;
1311  HeapTuple dtup;
1312 
1314  ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1315  if (!HeapTupleIsValid(dtup))
1316  return;
1317 
1318  dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
1319 
1320  /* add one StatisticExtInfo for each kind built */
1321  if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1322  {
1324 
1325  info->statOid = statOid;
1326  info->inherit = dataForm->stxdinherit;
1327  info->rel = rel;
1328  info->kind = STATS_EXT_NDISTINCT;
1329  info->keys = bms_copy(keys);
1330  info->exprs = exprs;
1331 
1332  *stainfos = lappend(*stainfos, info);
1333  }
1334 
1335  if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1336  {
1338 
1339  info->statOid = statOid;
1340  info->inherit = dataForm->stxdinherit;
1341  info->rel = rel;
1342  info->kind = STATS_EXT_DEPENDENCIES;
1343  info->keys = bms_copy(keys);
1344  info->exprs = exprs;
1345 
1346  *stainfos = lappend(*stainfos, info);
1347  }
1348 
1349  if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1350  {
1352 
1353  info->statOid = statOid;
1354  info->inherit = dataForm->stxdinherit;
1355  info->rel = rel;
1356  info->kind = STATS_EXT_MCV;
1357  info->keys = bms_copy(keys);
1358  info->exprs = exprs;
1359 
1360  *stainfos = lappend(*stainfos, info);
1361  }
1362 
1363  if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
1364  {
1366 
1367  info->statOid = statOid;
1368  info->inherit = dataForm->stxdinherit;
1369  info->rel = rel;
1370  info->kind = STATS_EXT_EXPRESSIONS;
1371  info->keys = bms_copy(keys);
1372  info->exprs = exprs;
1373 
1374  *stainfos = lappend(*stainfos, info);
1375  }
1376 
1377  ReleaseSysCache(dtup);
1378 }
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
bool statext_is_kind_built(HeapTuple htup, char type)
FormData_pg_statistic_ext_data * Form_pg_statistic_ext_data
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
Bitmapset * keys
Definition: pathnodes.h:1228
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1184
@ STATEXTDATASTXOID
Definition: syscache.h:94

References bms_copy(), BoolGetDatum(), StatisticExtInfo::exprs, GETSTRUCT, HeapTupleIsValid, StatisticExtInfo::inherit, StatisticExtInfo::keys, StatisticExtInfo::kind, lappend(), makeNode, ObjectIdGetDatum(), ReleaseSysCache(), SearchSysCache2(), statext_is_kind_built(), STATEXTDATASTXOID, and StatisticExtInfo::statOid.

Referenced by get_relation_statistics().

◆ has_row_triggers()

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

Definition at line 2158 of file plancat.c.

2159 {
2160  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2161  Relation relation;
2162  TriggerDesc *trigDesc;
2163  bool result = false;
2164 
2165  /* Assume we already have adequate lock */
2166  relation = table_open(rte->relid, NoLock);
2167 
2168  trigDesc = relation->trigdesc;
2169  switch (event)
2170  {
2171  case CMD_INSERT:
2172  if (trigDesc &&
2173  (trigDesc->trig_insert_after_row ||
2174  trigDesc->trig_insert_before_row))
2175  result = true;
2176  break;
2177  case CMD_UPDATE:
2178  if (trigDesc &&
2179  (trigDesc->trig_update_after_row ||
2180  trigDesc->trig_update_before_row))
2181  result = true;
2182  break;
2183  case CMD_DELETE:
2184  if (trigDesc &&
2185  (trigDesc->trig_delete_after_row ||
2186  trigDesc->trig_delete_before_row))
2187  result = true;
2188  break;
2189  /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2190  case CMD_MERGE:
2191  result = false;
2192  break;
2193  default:
2194  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2195  break;
2196  }
2197 
2198  table_close(relation, NoLock);
2199  return result;
2200 }
@ CMD_MERGE
Definition: nodes.h:263
@ CMD_INSERT
Definition: nodes.h:261
@ CMD_DELETE
Definition: nodes.h:262
@ CMD_UPDATE
Definition: nodes.h:260
TriggerDesc * trigdesc
Definition: rel.h:116
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, 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 2203 of file plancat.c.

2204 {
2205  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2206  Relation relation;
2207  TupleDesc tupdesc;
2208  bool result = false;
2209 
2210  /* Assume we already have adequate lock */
2211  relation = table_open(rte->relid, NoLock);
2212 
2213  tupdesc = RelationGetDescr(relation);
2214  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2215 
2216  table_close(relation, NoLock);
2217 
2218  return result;
2219 }
#define RelationGetDescr(relation)
Definition: rel.h:527
bool has_generated_stored
Definition: tupdesc.h:45

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

Referenced by make_modifytable().

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2126 of file plancat.c.

2127 {
2128  ListCell *ilist;
2129 
2130  foreach(ilist, rel->indexlist)
2131  {
2132  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2133 
2134  /*
2135  * Note: ignore partial indexes, since they don't allow us to conclude
2136  * that all attr values are distinct, *unless* they are marked predOK
2137  * which means we know the index's predicate is satisfied by the
2138  * query. We don't take any interest in expressional indexes either.
2139  * Also, a multicolumn unique index doesn't allow us to conclude that
2140  * just the specified attr is unique.
2141  */
2142  if (index->unique &&
2143  index->nkeycolumns == 1 &&
2144  index->indexkeys[0] == attno &&
2145  (index->indpred == NIL || index->predOK))
2146  return true;
2147  }
2148  return false;
2149 }

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 631 of file plancat.c.

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

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, Query::onConflict, ONCONFLICT_UPDATE, PlannerInfo::parse, predicate_implied_by(), RelationData::rd_index, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RangeTblEntry::relid, RangeTblEntry::rellockmode, Query::resultRelation, rt_fetch, Query::rtable, table_close(), table_open(), and Var::varattno.

Referenced by make_modifytable().

◆ infer_collation_opclass_match()

static bool infer_collation_opclass_match ( InferenceElem elem,
Relation  idxRel,
List idxExprs 
)
static

Definition at line 897 of file plancat.c.

899 {
900  AttrNumber natt;
901  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
902  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
903  int nplain = 0; /* # plain attrs observed */
904 
905  /*
906  * If inference specification element lacks collation/opclass, then no
907  * need to check for exact match.
908  */
909  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
910  return true;
911 
912  /*
913  * Lookup opfamily and input type, for matching indexes
914  */
915  if (elem->inferopclass)
916  {
917  inferopfamily = get_opclass_family(elem->inferopclass);
918  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
919  }
920 
921  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
922  {
923  Oid opfamily = idxRel->rd_opfamily[natt - 1];
924  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
925  Oid collation = idxRel->rd_indcollation[natt - 1];
926  int attno = idxRel->rd_index->indkey.values[natt - 1];
927 
928  if (attno != 0)
929  nplain++;
930 
931  if (elem->inferopclass != InvalidOid &&
932  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
933  {
934  /* Attribute needed to match opclass, but didn't */
935  continue;
936  }
937 
938  if (elem->infercollid != InvalidOid &&
939  elem->infercollid != collation)
940  {
941  /* Attribute needed to match collation, but didn't */
942  continue;
943  }
944 
945  /* If one matching index att found, good enough -- return true */
946  if (IsA(elem->expr, Var))
947  {
948  if (((Var *) elem->expr)->varattno == attno)
949  return true;
950  }
951  else if (attno == 0)
952  {
953  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
954 
955  /*
956  * Note that unlike routines like match_index_to_operand() we
957  * don't need to care about RelabelType. Neither the index
958  * definition nor the inference clause should contain them.
959  */
960  if (equal(elem->expr, nattExpr))
961  return true;
962  }
963  }
964 
965  return false;
966 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1216
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1194
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297

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

Referenced by infer_arbiter_indexes().

◆ join_selectivity()

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

Definition at line 1904 of file plancat.c.

1910 {
1911  RegProcedure oprjoin = get_oprjoin(operatorid);
1912  float8 result;
1913 
1914  /*
1915  * if the oprjoin procedure is missing for whatever reason, use a
1916  * selectivity of 0.5
1917  */
1918  if (!oprjoin)
1919  return (Selectivity) 0.5;
1920 
1921  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1922  inputcollid,
1923  PointerGetDatum(root),
1924  ObjectIdGetDatum(operatorid),
1926  Int16GetDatum(jointype),
1927  PointerGetDatum(sjinfo)));
1928 
1929  if (result < 0.0 || result > 1.0)
1930  elog(ERROR, "invalid join selectivity: %f", result);
1931 
1932  return (Selectivity) result;
1933 }
double float8
Definition: c.h:566
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1438
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1563
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:520
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:842

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

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

1497 {
1498  bool include_noinherit;
1499  bool include_notnull;
1500  bool include_partition = false;
1501  List *safe_restrictions;
1502  List *constraint_pred;
1503  List *safe_constraints;
1504  ListCell *lc;
1505 
1506  /* As of now, constraint exclusion works only with simple relations. */
1507  Assert(IS_SIMPLE_REL(rel));
1508 
1509  /*
1510  * If there are no base restriction clauses, we have no hope of proving
1511  * anything below, so fall out quickly.
1512  */
1513  if (rel->baserestrictinfo == NIL)
1514  return false;
1515 
1516  /*
1517  * Regardless of the setting of constraint_exclusion, detect
1518  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1519  * reduce "anything AND FALSE" to just "FALSE", any such case should
1520  * result in exactly one baserestrictinfo entry. This doesn't fire very
1521  * often, but it seems cheap enough to be worth doing anyway. (Without
1522  * this, we'd miss some optimizations that 9.5 and earlier found via much
1523  * more roundabout methods.)
1524  */
1525  if (list_length(rel->baserestrictinfo) == 1)
1526  {
1528  Expr *clause = rinfo->clause;
1529 
1530  if (clause && IsA(clause, Const) &&
1531  (((Const *) clause)->constisnull ||
1532  !DatumGetBool(((Const *) clause)->constvalue)))
1533  return true;
1534  }
1535 
1536  /*
1537  * Skip further tests, depending on constraint_exclusion.
1538  */
1539  switch (constraint_exclusion)
1540  {
1542  /* In 'off' mode, never make any further tests */
1543  return false;
1544 
1546 
1547  /*
1548  * When constraint_exclusion is set to 'partition' we only handle
1549  * appendrel members. Partition pruning has already been applied,
1550  * so there is no need to consider the rel's partition constraints
1551  * here.
1552  */
1553  if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
1554  break; /* appendrel member, so process it */
1555  return false;
1556 
1558 
1559  /*
1560  * In 'on' mode, always apply constraint exclusion. If we are
1561  * considering a baserel that is a partition (i.e., it was
1562  * directly named rather than expanded from a parent table), then
1563  * its partition constraints haven't been considered yet, so
1564  * include them in the processing here.
1565  */
1566  if (rel->reloptkind == RELOPT_BASEREL)
1567  include_partition = true;
1568  break; /* always try to exclude */
1569  }
1570 
1571  /*
1572  * Check for self-contradictory restriction clauses. We dare not make
1573  * deductions with non-immutable functions, but any immutable clauses that
1574  * are self-contradictory allow us to conclude the scan is unnecessary.
1575  *
1576  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1577  * expecting to see any in its predicate argument.
1578  */
1579  safe_restrictions = NIL;
1580  foreach(lc, rel->baserestrictinfo)
1581  {
1582  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1583 
1584  if (!contain_mutable_functions((Node *) rinfo->clause))
1585  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1586  }
1587 
1588  /*
1589  * We can use weak refutation here, since we're comparing restriction
1590  * clauses with restriction clauses.
1591  */
1592  if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1593  return true;
1594 
1595  /*
1596  * Only plain relations have constraints, so stop here for other rtekinds.
1597  */
1598  if (rte->rtekind != RTE_RELATION)
1599  return false;
1600 
1601  /*
1602  * If we are scanning just this table, we can use NO INHERIT constraints,
1603  * but not if we're scanning its children too. (Note that partitioned
1604  * tables should never have NO INHERIT constraints; but it's not necessary
1605  * for us to assume that here.)
1606  */
1607  include_noinherit = !rte->inh;
1608 
1609  /*
1610  * Currently, attnotnull constraints must be treated as NO INHERIT unless
1611  * this is a partitioned table. In future we might track their
1612  * inheritance status more accurately, allowing this to be refined.
1613  */
1614  include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
1615 
1616  /*
1617  * Fetch the appropriate set of constraint expressions.
1618  */
1619  constraint_pred = get_relation_constraints(root, rte->relid, rel,
1620  include_noinherit,
1621  include_notnull,
1622  include_partition);
1623 
1624  /*
1625  * We do not currently enforce that CHECK constraints contain only
1626  * immutable functions, so it's necessary to check here. We daren't draw
1627  * conclusions from plan-time evaluation of non-immutable functions. Since
1628  * they're ANDed, we can just ignore any mutable constraints in the list,
1629  * and reason about the rest.
1630  */
1631  safe_constraints = NIL;
1632  foreach(lc, constraint_pred)
1633  {
1634  Node *pred = (Node *) lfirst(lc);
1635 
1636  if (!contain_mutable_functions(pred))
1637  safe_constraints = lappend(safe_constraints, pred);
1638  }
1639 
1640  /*
1641  * The constraints are effectively ANDed together, so we can just try to
1642  * refute the entire collection at once. This may allow us to make proofs
1643  * that would fail if we took them individually.
1644  *
1645  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1646  * an obvious optimization. Some of the clauses might be OR clauses that
1647  * have volatile and nonvolatile subclauses, and it's OK to make
1648  * deductions with the nonvolatile parts.
1649  *
1650  * We need strong refutation because we have to prove that the constraints
1651  * would yield false, not just NULL.
1652  */
1653  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1654  return true;
1655 
1656  return false;
1657 }
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:365
@ 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:783
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:772
#define linitial(l)
Definition: pg_list.h:176
int constraint_exclusion
Definition: plancat.c:58
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
Definition: plancat.c:1186
static bool DatumGetBool(Datum X)
Definition: postgres.h:438
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:222
List * baserestrictinfo
Definition: pathnodes.h:924
Expr * clause
Definition: pathnodes.h:2423

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

Referenced by set_append_rel_size(), and set_rel_size().

◆ restriction_selectivity()

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

Definition at line 1865 of file plancat.c.

1870 {
1871  RegProcedure oprrest = get_oprrest(operatorid);
1872  float8 result;
1873 
1874  /*
1875  * if the oprrest procedure is missing for whatever reason, use a
1876  * selectivity of 0.5
1877  */
1878  if (!oprrest)
1879  return (Selectivity) 0.5;
1880 
1881  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1882  inputcollid,
1883  PointerGetDatum(root),
1884  ObjectIdGetDatum(operatorid),
1886  Int32GetDatum(varRelid)));
1887 
1888  if (result < 0.0 || result > 1.0)
1889  elog(ERROR, "invalid restriction selectivity: %f", result);
1890 
1891  return (Selectivity) result;
1892 }
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1427
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1539
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560

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

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

◆ set_baserel_partition_constraint()

static void set_baserel_partition_constraint ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2432 of file plancat.c.

2433 {
2434  List *partconstr;
2435 
2436  if (rel->partition_qual) /* already done */
2437  return;
2438 
2439  /*
2440  * Run the partition quals through const-simplification similar to check
2441  * constraints. We skip canonicalize_qual, though, because partition
2442  * quals should be in canonical form already; also, since the qual is in
2443  * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2444  * format and back again.
2445  */
2446  partconstr = RelationGetPartitionQual(relation);
2447  if (partconstr)
2448  {
2449  partconstr = (List *) expression_planner((Expr *) partconstr);
2450  if (rel->relid != 1)
2451  ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2452  rel->partition_qual = partconstr;
2453  }
2454 }
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:282
Expr * expression_planner(Expr *expr)
Definition: planner.c:6146

References ChangeVarNodes(), expression_planner(), RelOptInfo::partition_qual, RelationGetPartitionQual(), and RelOptInfo::relid.

Referenced by get_relation_constraints(), and set_relation_partition_info().

◆ set_baserel_partition_key_exprs()

static void set_baserel_partition_key_exprs ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2364 of file plancat.c.

2366 {
2367  PartitionKey partkey = RelationGetPartitionKey(relation);
2368  int partnatts;
2369  int cnt;
2370  List **partexprs;
2371  ListCell *lc;
2372  Index varno = rel->relid;
2373 
2374  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2375 
2376  /* A partitioned table should have a partition key. */
2377  Assert(partkey != NULL);
2378 
2379  partnatts = partkey->partnatts;
2380  partexprs = (List **) palloc(sizeof(List *) * partnatts);
2381  lc = list_head(partkey->partexprs);
2382 
2383  for (cnt = 0; cnt < partnatts; cnt++)
2384  {
2385  Expr *partexpr;
2386  AttrNumber attno = partkey->partattrs[cnt];
2387 
2388  if (attno != InvalidAttrNumber)
2389  {
2390  /* Single column partition key is stored as a Var node. */
2391  Assert(attno > 0);
2392 
2393  partexpr = (Expr *) makeVar(varno, attno,
2394  partkey->parttypid[cnt],
2395  partkey->parttypmod[cnt],
2396  partkey->parttypcoll[cnt], 0);
2397  }
2398  else
2399  {
2400  if (lc == NULL)
2401  elog(ERROR, "wrong number of partition key expressions");
2402 
2403  /* Re-stamp the expression with given varno. */
2404  partexpr = (Expr *) copyObject(lfirst(lc));
2405  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2406  lc = lnext(partkey->partexprs, lc);
2407  }
2408 
2409  /* Base relations have a single expression per key. */
2410  partexprs[cnt] = list_make1(partexpr);
2411  }
2412 
2413  rel->partexprs = partexprs;
2414 
2415  /*
2416  * A base relation does not have nullable partition key expressions, since
2417  * no outer join is involved. We still allocate an array of empty
2418  * expression lists to keep partition key expression handling code simple.
2419  * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2420  */
2421  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2422 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define copyObject(obj)
Definition: nodes.h:227
#define list_make1(x1)
Definition: pg_list.h:210
Oid * parttypcoll
Definition: partcache.h:47
int32 * parttypmod
Definition: partcache.h:43
List * partexprs
Definition: partcache.h:31
AttrNumber * partattrs
Definition: partcache.h:29

References Assert(), ChangeVarNodes(), copyObject, elog(), ERROR, InvalidAttrNumber, IS_SIMPLE_REL, lfirst, list_head(), list_make1, lnext(), makeVar(), palloc(), palloc0(), PartitionKeyData::partattrs, PartitionKeyData::partexprs, PartitionKeyData::partnatts, PartitionKeyData::parttypcoll, PartitionKeyData::parttypid, PartitionKeyData::parttypmod, RelationGetPartitionKey(), and RelOptInfo::relid.

Referenced by set_relation_partition_info().

◆ set_relation_partition_info()

static void set_relation_partition_info ( PlannerInfo root,
RelOptInfo rel,
Relation  relation 
)
static

Definition at line 2227 of file plancat.c.

2229 {
2230  PartitionDesc partdesc;
2231 
2232  /*
2233  * Create the PartitionDirectory infrastructure if we didn't already.
2234  */
2235  if (root->glob->partition_directory == NULL)
2236  {
2237  root->glob->partition_directory =
2239  }
2240 
2241  partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
2242  relation);
2243  rel->part_scheme = find_partition_scheme(root, relation);
2244  Assert(partdesc != NULL && rel->part_scheme != NULL);
2245  rel->boundinfo = partdesc->boundinfo;
2246  rel->nparts = partdesc->nparts;
2247  set_baserel_partition_key_exprs(relation, rel);
2248  set_baserel_partition_constraint(relation, rel);
2249 }
PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool omit_detached)
Definition: partdesc.c:383
PartitionDesc PartitionDirectoryLookup(PartitionDirectory pdir, Relation rel)
Definition: partdesc.c:416
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation relation)
Definition: plancat.c:2257
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2364
PartitionBoundInfo boundinfo
Definition: partdesc.h:38
int nparts
Definition: pathnodes.h:960

References Assert(), PartitionDescData::boundinfo, CreatePartitionDirectory(), CurrentMemoryContext, find_partition_scheme(), PlannerInfo::glob, RelOptInfo::nparts, PartitionDescData::nparts, PartitionDirectoryLookup(), set_baserel_partition_constraint(), and set_baserel_partition_key_exprs().

Referenced by get_relation_info().

Variable Documentation

◆ constraint_exclusion

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION

Definition at line 58 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ get_relation_info_hook

get_relation_info_hook_type get_relation_info_hook = NULL

Definition at line 61 of file plancat.c.

Referenced by get_relation_info().