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 rel)
 
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 1988 of file plancat.c.

1990 {
1991  HeapTuple proctup;
1992  Form_pg_proc procform;
1993 
1994  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1995  if (!HeapTupleIsValid(proctup))
1996  elog(ERROR, "cache lookup failed for function %u", funcid);
1997  procform = (Form_pg_proc) GETSTRUCT(proctup);
1998 
1999  if (OidIsValid(procform->prosupport))
2000  {
2001  SupportRequestCost req;
2002  SupportRequestCost *sresult;
2003 
2004  req.type = T_SupportRequestCost;
2005  req.root = root;
2006  req.funcid = funcid;
2007  req.node = node;
2008 
2009  /* Initialize cost fields so that support function doesn't have to */
2010  req.startup = 0;
2011  req.per_tuple = 0;
2012 
2013  sresult = (SupportRequestCost *)
2014  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2015  PointerGetDatum(&req)));
2016 
2017  if (sresult == &req)
2018  {
2019  /* Success, so accumulate support function's estimate into *cost */
2020  cost->startup += req.startup;
2021  cost->per_tuple += req.per_tuple;
2022  ReleaseSysCache(proctup);
2023  return;
2024  }
2025  }
2026 
2027  /* No support function, or it failed, so rely on procost */
2028  cost->per_tuple += procform->procost * cpu_operator_cost;
2029 
2030  ReleaseSysCache(proctup);
2031 }
#define OidIsValid(objectId)
Definition: c.h:710
double cpu_operator_cost
Definition: costsize.c:124
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:669
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
@ T_SupportRequestCost
Definition: nodes.h:561
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define DatumGetPointer(X)
Definition: postgres.h:593
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define PointerGetDatum(X)
Definition: postgres.h:600
Cost per_tuple
Definition: pathnodes.h:46
Cost startup
Definition: pathnodes.h:45
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, T_SupportRequestCost, and SupportRequestCost::type.

Referenced by compute_cpu_sort_cost(), 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 1784 of file plancat.c.

1786 {
1787  List *tlist = NIL;
1788  Index varno = index->rel->relid;
1789  ListCell *indexpr_item;
1790  int i;
1791 
1792  indexpr_item = list_head(index->indexprs);
1793  for (i = 0; i < index->ncolumns; i++)
1794  {
1795  int indexkey = index->indexkeys[i];
1796  Expr *indexvar;
1797 
1798  if (indexkey != 0)
1799  {
1800  /* simple column */
1801  const FormData_pg_attribute *att_tup;
1802 
1803  if (indexkey < 0)
1804  att_tup = SystemAttributeDefinition(indexkey);
1805  else
1806  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1807 
1808  indexvar = (Expr *) makeVar(varno,
1809  indexkey,
1810  att_tup->atttypid,
1811  att_tup->atttypmod,
1812  att_tup->attcollation,
1813  0);
1814  }
1815  else
1816  {
1817  /* expression column */
1818  if (indexpr_item == NULL)
1819  elog(ERROR, "wrong number of index expressions");
1820  indexvar = (Expr *) lfirst(indexpr_item);
1821  indexpr_item = lnext(index->indexprs, indexpr_item);
1822  }
1823 
1824  tlist = lappend(tlist,
1825  makeTargetEntry(indexvar,
1826  i + 1,
1827  NULL,
1828  false));
1829  }
1830  if (indexpr_item != NULL)
1831  elog(ERROR, "wrong number of index expressions");
1832 
1833  return tlist;
1834 }
unsigned int Index
Definition: c.h:549
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:336
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:239
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
FormData_pg_attribute
Definition: pg_attribute.h:191
#define lfirst(lc)
Definition: pg_list.h:169
#define NIL
Definition: pg_list.h:65
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
Definition: pg_list.h:51
TupleDesc rd_att
Definition: rel.h:110
Definition: type.h:90
#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 1663 of file plancat.c.

1664 {
1665  List *tlist = NIL;
1666  Index varno = rel->relid;
1667  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1668  Relation relation;
1669  Query *subquery;
1670  Var *var;
1671  ListCell *l;
1672  int attrno,
1673  numattrs;
1674  List *colvars;
1675 
1676  switch (rte->rtekind)
1677  {
1678  case RTE_RELATION:
1679  /* Assume we already have adequate lock */
1680  relation = table_open(rte->relid, NoLock);
1681 
1682  numattrs = RelationGetNumberOfAttributes(relation);
1683  for (attrno = 1; attrno <= numattrs; attrno++)
1684  {
1685  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1686  attrno - 1);
1687 
1688  if (att_tup->attisdropped || att_tup->atthasmissing)
1689  {
1690  /* found a dropped or missing col, so punt */
1691  tlist = NIL;
1692  break;
1693  }
1694 
1695  var = makeVar(varno,
1696  attrno,
1697  att_tup->atttypid,
1698  att_tup->atttypmod,
1699  att_tup->attcollation,
1700  0);
1701 
1702  tlist = lappend(tlist,
1703  makeTargetEntry((Expr *) var,
1704  attrno,
1705  NULL,
1706  false));
1707  }
1708 
1709  table_close(relation, NoLock);
1710  break;
1711 
1712  case RTE_SUBQUERY:
1713  subquery = rte->subquery;
1714  foreach(l, subquery->targetList)
1715  {
1716  TargetEntry *tle = (TargetEntry *) lfirst(l);
1717 
1718  /*
1719  * A resjunk column of the subquery can be reflected as
1720  * resjunk in the physical tlist; we need not punt.
1721  */
1722  var = makeVarFromTargetEntry(varno, tle);
1723 
1724  tlist = lappend(tlist,
1725  makeTargetEntry((Expr *) var,
1726  tle->resno,
1727  NULL,
1728  tle->resjunk));
1729  }
1730  break;
1731 
1732  case RTE_FUNCTION:
1733  case RTE_TABLEFUNC:
1734  case RTE_VALUES:
1735  case RTE_CTE:
1736  case RTE_NAMEDTUPLESTORE:
1737  case RTE_RESULT:
1738  /* Not all of these can have dropped cols, but share code anyway */
1739  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1740  NULL, &colvars);
1741  foreach(l, colvars)
1742  {
1743  var = (Var *) lfirst(l);
1744 
1745  /*
1746  * A non-Var in expandRTE's output means a dropped column;
1747  * must punt.
1748  */
1749  if (!IsA(var, Var))
1750  {
1751  tlist = NIL;
1752  break;
1753  }
1754 
1755  tlist = lappend(tlist,
1756  makeTargetEntry((Expr *) var,
1757  var->varattno,
1758  NULL,
1759  false));
1760  }
1761  break;
1762 
1763  default:
1764  /* caller error */
1765  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1766  (int) rte->rtekind);
1767  break;
1768  }
1769 
1770  return tlist;
1771 }
#define NoLock
Definition: lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:104
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_CTE
Definition: parsenodes.h:1004
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1005
@ RTE_VALUES
Definition: parsenodes.h:1003
@ RTE_SUBQUERY
Definition: parsenodes.h:999
@ RTE_RESULT
Definition: parsenodes.h:1006
@ RTE_FUNCTION
Definition: parsenodes.h:1001
@ RTE_TABLEFUNC
Definition: parsenodes.h:1002
@ RTE_RELATION
Definition: parsenodes.h:998
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:389
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:495
List * targetList
Definition: parsenodes.h:155
Query * subquery
Definition: parsenodes.h:1050
RTEKind rtekind
Definition: parsenodes.h:1015
Index relid
Definition: pathnodes.h:710
AttrNumber resno
Definition: primnodes.h:1717
bool resjunk
Definition: primnodes.h:1723
Definition: primnodes.h:196
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

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

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

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  rel 
)
static

Definition at line 2238 of file plancat.c.

2239 {
2240  PartitionKey partkey = RelationGetPartitionKey(relation);
2241  ListCell *lc;
2242  int partnatts,
2243  i;
2244  PartitionScheme part_scheme;
2245 
2246  /* A partitioned table should have a partition key. */
2247  Assert(partkey != NULL);
2248 
2249  partnatts = partkey->partnatts;
2250 
2251  /* Search for a matching partition scheme and return if found one. */
2252  foreach(lc, root->part_schemes)
2253  {
2254  part_scheme = lfirst(lc);
2255 
2256  /* Match partitioning strategy and number of keys. */
2257  if (partkey->strategy != part_scheme->strategy ||
2258  partnatts != part_scheme->partnatts)
2259  continue;
2260 
2261  /* Match partition key type properties. */
2262  if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2263  sizeof(Oid) * partnatts) != 0 ||
2264  memcmp(partkey->partopcintype, part_scheme->partopcintype,
2265  sizeof(Oid) * partnatts) != 0 ||
2266  memcmp(partkey->partcollation, part_scheme->partcollation,
2267  sizeof(Oid) * partnatts) != 0)
2268  continue;
2269 
2270  /*
2271  * Length and byval information should match when partopcintype
2272  * matches.
2273  */
2274  Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2275  sizeof(int16) * partnatts) == 0);
2276  Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2277  sizeof(bool) * partnatts) == 0);
2278 
2279  /*
2280  * If partopfamily and partopcintype matched, must have the same
2281  * partition comparison functions. Note that we cannot reliably
2282  * Assert the equality of function structs themselves for they might
2283  * be different across PartitionKey's, so just Assert for the function
2284  * OIDs.
2285  */
2286 #ifdef USE_ASSERT_CHECKING
2287  for (i = 0; i < partkey->partnatts; i++)
2288  Assert(partkey->partsupfunc[i].fn_oid ==
2289  part_scheme->partsupfunc[i].fn_oid);
2290 #endif
2291 
2292  /* Found matching partition scheme. */
2293  return part_scheme;
2294  }
2295 
2296  /*
2297  * Did not find matching partition scheme. Create one copying relevant
2298  * information from the relcache. We need to copy the contents of the
2299  * array since the relcache entry may not survive after we have closed the
2300  * relation.
2301  */
2302  part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
2303  part_scheme->strategy = partkey->strategy;
2304  part_scheme->partnatts = partkey->partnatts;
2305 
2306  part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
2307  memcpy(part_scheme->partopfamily, partkey->partopfamily,
2308  sizeof(Oid) * partnatts);
2309 
2310  part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
2311  memcpy(part_scheme->partopcintype, partkey->partopcintype,
2312  sizeof(Oid) * partnatts);
2313 
2314  part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
2315  memcpy(part_scheme->partcollation, partkey->partcollation,
2316  sizeof(Oid) * partnatts);
2317 
2318  part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
2319  memcpy(part_scheme->parttyplen, partkey->parttyplen,
2320  sizeof(int16) * partnatts);
2321 
2322  part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
2323  memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2324  sizeof(bool) * partnatts);
2325 
2326  part_scheme->partsupfunc = (FmgrInfo *)
2327  palloc(sizeof(FmgrInfo) * partnatts);
2328  for (i = 0; i < partnatts; i++)
2329  fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2331 
2332  /* Add the partitioning scheme to PlannerInfo. */
2333  root->part_schemes = lappend(root->part_schemes, part_scheme);
2334 
2335  return part_scheme;
2336 }
signed short int16
Definition: c.h:428
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:1099
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void * palloc(Size size)
Definition: mcxt.c:1068
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
struct PartitionSchemeData * PartitionScheme
Definition: pathnodes.h:423
unsigned int Oid
Definition: postgres_ext.h:31
Definition: fmgr.h:57
Oid fn_oid
Definition: fmgr.h:59
Oid * partcollation
Definition: partcache.h:38
Oid * partopfamily
Definition: partcache.h:33
bool * parttypbyval
Definition: partcache.h:44
int16 * parttyplen
Definition: partcache.h:43
FmgrInfo * partsupfunc
Definition: partcache.h:35
Oid * partopcintype
Definition: partcache.h:34
struct FmgrInfo * partsupfunc
Definition: pathnodes.h:420
List * part_schemes
Definition: pathnodes.h:302

References Assert(), CurrentMemoryContext, fmgr_info_copy(), FmgrInfo::fn_oid, i, lappend(), lfirst, palloc(), palloc0(), PlannerInfo::part_schemes, 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 1926 of file plancat.c.

1934 {
1935  RegProcedure prosupport = get_func_support(funcid);
1937  SupportRequestSelectivity *sresult;
1938 
1939  /*
1940  * If no support function is provided, use our historical default
1941  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
1942  * Postgres has been using that estimate for function calls since 1992.
1943  * The hoariness of this behavior suggests that we should not be in too
1944  * much hurry to use another value.
1945  */
1946  if (!prosupport)
1947  return (Selectivity) 0.3333333;
1948 
1950  req.root = root;
1951  req.funcid = funcid;
1952  req.args = args;
1953  req.inputcollid = inputcollid;
1954  req.is_join = is_join;
1955  req.varRelid = varRelid;
1956  req.jointype = jointype;
1957  req.sjinfo = sjinfo;
1958  req.selectivity = -1; /* to catch failure to set the value */
1959 
1960  sresult = (SupportRequestSelectivity *)
1961  DatumGetPointer(OidFunctionCall1(prosupport,
1962  PointerGetDatum(&req)));
1963 
1964  /* If support function fails, use default */
1965  if (sresult != &req)
1966  return (Selectivity) 0.3333333;
1967 
1968  if (req.selectivity < 0.0 || req.selectivity > 1.0)
1969  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
1970 
1971  return (Selectivity) req.selectivity;
1972 }
regproc RegProcedure
Definition: c.h:585
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1839
@ T_SupportRequestSelectivity
Definition: nodes.h:560
double Selectivity
Definition: nodes.h:706
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, T_SupportRequestSelectivity, 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 2049 of file plancat.c.

2050 {
2051  HeapTuple proctup;
2052  Form_pg_proc procform;
2053  double result;
2054 
2055  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2056  if (!HeapTupleIsValid(proctup))
2057  elog(ERROR, "cache lookup failed for function %u", funcid);
2058  procform = (Form_pg_proc) GETSTRUCT(proctup);
2059 
2060  Assert(procform->proretset); /* else caller error */
2061 
2062  if (OidIsValid(procform->prosupport))
2063  {
2064  SupportRequestRows req;
2065  SupportRequestRows *sresult;
2066 
2067  req.type = T_SupportRequestRows;
2068  req.root = root;
2069  req.funcid = funcid;
2070  req.node = node;
2071 
2072  req.rows = 0; /* just for sanity */
2073 
2074  sresult = (SupportRequestRows *)
2075  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2076  PointerGetDatum(&req)));
2077 
2078  if (sresult == &req)
2079  {
2080  /* Success */
2081  ReleaseSysCache(proctup);
2082  return req.rows;
2083  }
2084  }
2085 
2086  /* No support function, or it failed, so rely on prorows */
2087  result = procform->prorows;
2088 
2089  ReleaseSysCache(proctup);
2090 
2091  return result;
2092 }
@ T_SupportRequestRows
Definition: nodes.h:562
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(), T_SupportRequestRows, 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 1085 of file plancat.c.

1086 {
1087  int32 tuple_width = 0;
1088  int i;
1089 
1090  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1091  {
1092  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1093  int32 item_width;
1094 
1095  if (att->attisdropped)
1096  continue;
1097 
1098  /* use previously cached data, if any */
1099  if (attr_widths != NULL && attr_widths[i] > 0)
1100  {
1101  tuple_width += attr_widths[i];
1102  continue;
1103  }
1104 
1105  /* This should match set_rel_width() in costsize.c */
1106  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1107  if (item_width <= 0)
1108  {
1109  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1110  Assert(item_width > 0);
1111  }
1112  if (attr_widths != NULL)
1113  attr_widths[i] = item_width;
1114  tuple_width += item_width;
1115  }
1116 
1117  return tuple_width;
1118 }
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3115
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2535
#define RelationGetRelid(relation)
Definition: rel.h:489

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

1172 {
1173  List *result = NIL;
1174  Index varno = rel->relid;
1175  Relation relation;
1176  TupleConstr *constr;
1177 
1178  /*
1179  * We assume the relation has already been safely locked.
1180  */
1181  relation = table_open(relationObjectId, NoLock);
1182 
1183  constr = relation->rd_att->constr;
1184  if (constr != NULL)
1185  {
1186  int num_check = constr->num_check;
1187  int i;
1188 
1189  for (i = 0; i < num_check; i++)
1190  {
1191  Node *cexpr;
1192 
1193  /*
1194  * If this constraint hasn't been fully validated yet, we must
1195  * ignore it here. Also ignore if NO INHERIT and we weren't told
1196  * that that's safe.
1197  */
1198  if (!constr->check[i].ccvalid)
1199  continue;
1200  if (constr->check[i].ccnoinherit && !include_noinherit)
1201  continue;
1202 
1203  cexpr = stringToNode(constr->check[i].ccbin);
1204 
1205  /*
1206  * Run each expression through const-simplification and
1207  * canonicalization. This is not just an optimization, but is
1208  * necessary, because we will be comparing it to
1209  * similarly-processed qual clauses, and may fail to detect valid
1210  * matches without this. This must match the processing done to
1211  * qual clauses in preprocess_expression()! (We can skip the
1212  * stuff involving subqueries, however, since we don't allow any
1213  * in check constraints.)
1214  */
1215  cexpr = eval_const_expressions(root, cexpr);
1216 
1217  cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1218 
1219  /* Fix Vars to have the desired varno */
1220  if (varno != 1)
1221  ChangeVarNodes(cexpr, 1, varno, 0);
1222 
1223  /*
1224  * Finally, convert to implicit-AND format (that is, a List) and
1225  * append the resulting item(s) to our output list.
1226  */
1227  result = list_concat(result,
1228  make_ands_implicit((Expr *) cexpr));
1229  }
1230 
1231  /* Add NOT NULL constraints in expression form, if requested */
1232  if (include_notnull && constr->has_not_null)
1233  {
1234  int natts = relation->rd_att->natts;
1235 
1236  for (i = 1; i <= natts; i++)
1237  {
1238  Form_pg_attribute att = TupleDescAttr(relation->rd_att, i - 1);
1239 
1240  if (att->attnotnull && !att->attisdropped)
1241  {
1242  NullTest *ntest = makeNode(NullTest);
1243 
1244  ntest->arg = (Expr *) makeVar(varno,
1245  i,
1246  att->atttypid,
1247  att->atttypmod,
1248  att->attcollation,
1249  0);
1250  ntest->nulltesttype = IS_NOT_NULL;
1251 
1252  /*
1253  * argisrow=false is correct even for a composite column,
1254  * because attnotnull does not represent a SQL-spec IS NOT
1255  * NULL test in such a case, just IS DISTINCT FROM NULL.
1256  */
1257  ntest->argisrow = false;
1258  ntest->location = -1;
1259  result = lappend(result, ntest);
1260  }
1261  }
1262  }
1263  }
1264 
1265  /*
1266  * Add partitioning constraints, if requested.
1267  */
1268  if (include_partition && relation->rd_rel->relispartition)
1269  {
1270  /* make sure rel->partition_qual is set */
1271  set_baserel_partition_constraint(relation, rel);
1272  result = list_concat(result, rel->partition_qual);
1273  }
1274 
1275  table_close(relation, NoLock);
1276 
1277  return result;
1278 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2150
List * list_concat(List *list1, const List *list2)
Definition: list.c:540
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:720
#define makeNode(_type_)
Definition: nodes.h:621
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2413
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:294
@ IS_NOT_NULL
Definition: primnodes.h:1520
void * stringToNode(const char *str)
Definition: read.c:89
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:574
NullTestType nulltesttype
Definition: primnodes.h:1527
int location
Definition: primnodes.h:1529
bool argisrow
Definition: primnodes.h:1528
Expr * arg
Definition: primnodes.h:1526
List * partition_qual
Definition: pathnodes.h:768
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 1127 of file plancat.c.

1128 {
1129  int32 result;
1130  Relation relation;
1131 
1132  /* As above, assume relation is already locked */
1133  relation = table_open(relid, NoLock);
1134 
1135  result = get_rel_data_width(relation, attr_widths);
1136 
1137  table_close(relation, NoLock);
1138 
1139  return result;
1140 }

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

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

References Assert(), ForeignKeyOptInfo::con_relid, ForeignKeyOptInfo::confkey, ForeignKeyCacheInfo::confkey, ForeignKeyCacheInfo::confrelid, ForeignKeyOptInfo::conkey, ForeignKeyCacheInfo::conkey, ForeignKeyOptInfo::conpfeqop, ForeignKeyCacheInfo::conpfeqop, 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 114 of file plancat.c.

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

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

Referenced by build_simple_rel().

◆ get_relation_statistics()

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

Definition at line 1370 of file plancat.c.

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

1290 {
1291  Form_pg_statistic_ext_data dataForm;
1292  HeapTuple dtup;
1293 
1295  ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1296  if (!HeapTupleIsValid(dtup))
1297  return;
1298 
1299  dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
1300 
1301  /* add one StatisticExtInfo for each kind built */
1302  if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1303  {
1305 
1306  info->statOid = statOid;
1307  info->inherit = dataForm->stxdinherit;
1308  info->rel = rel;
1309  info->kind = STATS_EXT_NDISTINCT;
1310  info->keys = bms_copy(keys);
1311  info->exprs = exprs;
1312 
1313  *stainfos = lappend(*stainfos, info);
1314  }
1315 
1316  if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1317  {
1319 
1320  info->statOid = statOid;
1321  info->inherit = dataForm->stxdinherit;
1322  info->rel = rel;
1323  info->kind = STATS_EXT_DEPENDENCIES;
1324  info->keys = bms_copy(keys);
1325  info->exprs = exprs;
1326 
1327  *stainfos = lappend(*stainfos, info);
1328  }
1329 
1330  if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1331  {
1333 
1334  info->statOid = statOid;
1335  info->inherit = dataForm->stxdinherit;
1336  info->rel = rel;
1337  info->kind = STATS_EXT_MCV;
1338  info->keys = bms_copy(keys);
1339  info->exprs = exprs;
1340 
1341  *stainfos = lappend(*stainfos, info);
1342  }
1343 
1344  if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
1345  {
1347 
1348  info->statOid = statOid;
1349  info->inherit = dataForm->stxdinherit;
1350  info->rel = rel;
1351  info->kind = STATS_EXT_EXPRESSIONS;
1352  info->keys = bms_copy(keys);
1353  info->exprs = exprs;
1354 
1355  *stainfos = lappend(*stainfos, info);
1356  }
1357 
1358  ReleaseSysCache(dtup);
1359 }
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
#define BoolGetDatum(X)
Definition: postgres.h:446
RelOptInfo * rel
Definition: pathnodes.h:939
Bitmapset * keys
Definition: pathnodes.h:941
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, StatisticExtInfo::rel, 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 2139 of file plancat.c.

2140 {
2141  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2142  Relation relation;
2143  TriggerDesc *trigDesc;
2144  bool result = false;
2145 
2146  /* Assume we already have adequate lock */
2147  relation = table_open(rte->relid, NoLock);
2148 
2149  trigDesc = relation->trigdesc;
2150  switch (event)
2151  {
2152  case CMD_INSERT:
2153  if (trigDesc &&
2154  (trigDesc->trig_insert_after_row ||
2155  trigDesc->trig_insert_before_row))
2156  result = true;
2157  break;
2158  case CMD_UPDATE:
2159  if (trigDesc &&
2160  (trigDesc->trig_update_after_row ||
2161  trigDesc->trig_update_before_row))
2162  result = true;
2163  break;
2164  case CMD_DELETE:
2165  if (trigDesc &&
2166  (trigDesc->trig_delete_after_row ||
2167  trigDesc->trig_delete_before_row))
2168  result = true;
2169  break;
2170  /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2171  case CMD_MERGE:
2172  result = false;
2173  break;
2174  default:
2175  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2176  break;
2177  }
2178 
2179  table_close(relation, NoLock);
2180  return result;
2181 }
@ CMD_MERGE
Definition: nodes.h:725
@ CMD_INSERT
Definition: nodes.h:723
@ CMD_DELETE
Definition: nodes.h:724
@ CMD_UPDATE
Definition: nodes.h:722
TriggerDesc * trigdesc
Definition: rel.h:115
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 2184 of file plancat.c.

2185 {
2186  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2187  Relation relation;
2188  TupleDesc tupdesc;
2189  bool result = false;
2190 
2191  /* Assume we already have adequate lock */
2192  relation = table_open(rte->relid, NoLock);
2193 
2194  tupdesc = RelationGetDescr(relation);
2195  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2196 
2197  table_close(relation, NoLock);
2198 
2199  return result;
2200 }
#define RelationGetDescr(relation)
Definition: rel.h:515
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 2107 of file plancat.c.

2108 {
2109  ListCell *ilist;
2110 
2111  foreach(ilist, rel->indexlist)
2112  {
2113  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2114 
2115  /*
2116  * Note: ignore partial indexes, since they don't allow us to conclude
2117  * that all attr values are distinct, *unless* they are marked predOK
2118  * which means we know the index's predicate is satisfied by the
2119  * query. We don't take any interest in expressional indexes either.
2120  * Also, a multicolumn unique index doesn't allow us to conclude that
2121  * just the specified attr is unique.
2122  */
2123  if (index->unique &&
2124  index->nkeycolumns == 1 &&
2125  index->indexkeys[0] == attno &&
2126  (index->indpred == NIL || index->predOK))
2127  return true;
2128  }
2129  return false;
2130 }

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 612 of file plancat.c.

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

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

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

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

1891 {
1892  RegProcedure oprjoin = get_oprjoin(operatorid);
1893  float8 result;
1894 
1895  /*
1896  * if the oprjoin procedure is missing for whatever reason, use a
1897  * selectivity of 0.5
1898  */
1899  if (!oprjoin)
1900  return (Selectivity) 0.5;
1901 
1902  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1903  inputcollid,
1904  PointerGetDatum(root),
1905  ObjectIdGetDatum(operatorid),
1907  Int16GetDatum(jointype),
1908  PointerGetDatum(sjinfo)));
1909 
1910  if (result < 0.0 || result > 1.0)
1911  elog(ERROR, "invalid join selectivity: %f", result);
1912 
1913  return (Selectivity) result;
1914 }
double float8
Definition: c.h:565
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:1562
#define DatumGetFloat8(X)
Definition: postgres.h:758
#define Int16GetDatum(X)
Definition: postgres.h:495

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

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

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

1851 {
1852  RegProcedure oprrest = get_oprrest(operatorid);
1853  float8 result;
1854 
1855  /*
1856  * if the oprrest procedure is missing for whatever reason, use a
1857  * selectivity of 0.5
1858  */
1859  if (!oprrest)
1860  return (Selectivity) 0.5;
1861 
1862  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1863  inputcollid,
1864  PointerGetDatum(root),
1865  ObjectIdGetDatum(operatorid),
1867  Int32GetDatum(varRelid)));
1868 
1869  if (result < 0.0 || result > 1.0)
1870  elog(ERROR, "invalid restriction selectivity: %f", result);
1871 
1872  return (Selectivity) result;
1873 }
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:1538
#define Int32GetDatum(X)
Definition: postgres.h:523

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

2414 {
2415  List *partconstr;
2416 
2417  if (rel->partition_qual) /* already done */
2418  return;
2419 
2420  /*
2421  * Run the partition quals through const-simplification similar to check
2422  * constraints. We skip canonicalize_qual, though, because partition
2423  * quals should be in canonical form already; also, since the qual is in
2424  * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2425  * format and back again.
2426  */
2427  partconstr = RelationGetPartitionQual(relation);
2428  if (partconstr)
2429  {
2430  partconstr = (List *) expression_planner((Expr *) partconstr);
2431  if (rel->relid != 1)
2432  ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2433  rel->partition_qual = partconstr;
2434  }
2435 }
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:276
Expr * expression_planner(Expr *expr)
Definition: planner.c:5882

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

2347 {
2348  PartitionKey partkey = RelationGetPartitionKey(relation);
2349  int partnatts;
2350  int cnt;
2351  List **partexprs;
2352  ListCell *lc;
2353  Index varno = rel->relid;
2354 
2355  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2356 
2357  /* A partitioned table should have a partition key. */
2358  Assert(partkey != NULL);
2359 
2360  partnatts = partkey->partnatts;
2361  partexprs = (List **) palloc(sizeof(List *) * partnatts);
2362  lc = list_head(partkey->partexprs);
2363 
2364  for (cnt = 0; cnt < partnatts; cnt++)
2365  {
2366  Expr *partexpr;
2367  AttrNumber attno = partkey->partattrs[cnt];
2368 
2369  if (attno != InvalidAttrNumber)
2370  {
2371  /* Single column partition key is stored as a Var node. */
2372  Assert(attno > 0);
2373 
2374  partexpr = (Expr *) makeVar(varno, attno,
2375  partkey->parttypid[cnt],
2376  partkey->parttypmod[cnt],
2377  partkey->parttypcoll[cnt], 0);
2378  }
2379  else
2380  {
2381  if (lc == NULL)
2382  elog(ERROR, "wrong number of partition key expressions");
2383 
2384  /* Re-stamp the expression with given varno. */
2385  partexpr = (Expr *) copyObject(lfirst(lc));
2386  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2387  lc = lnext(partkey->partexprs, lc);
2388  }
2389 
2390  /* Base relations have a single expression per key. */
2391  partexprs[cnt] = list_make1(partexpr);
2392  }
2393 
2394  rel->partexprs = partexprs;
2395 
2396  /*
2397  * A base relation does not have nullable partition key expressions, since
2398  * no outer join is involved. We still allocate an array of empty
2399  * expression lists to keep partition key expression handling code simple.
2400  * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2401  */
2402  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2403 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define copyObject(obj)
Definition: nodes.h:689
#define list_make1(x1)
Definition: pg_list.h:206
Oid * parttypcoll
Definition: partcache.h:46
int32 * parttypmod
Definition: partcache.h:42
List * partexprs
Definition: partcache.h:30
AttrNumber * partattrs
Definition: partcache.h:28
List ** partexprs
Definition: pathnodes.h:775
List ** nullable_partexprs
Definition: pathnodes.h:776

References Assert(), ChangeVarNodes(), copyObject, elog, ERROR, InvalidAttrNumber, IS_SIMPLE_REL, lfirst, list_head(), list_make1, lnext(), makeVar(), RelOptInfo::nullable_partexprs, palloc(), palloc0(), PartitionKeyData::partattrs, RelOptInfo::partexprs, 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 2208 of file plancat.c.

2210 {
2211  PartitionDesc partdesc;
2212 
2213  /*
2214  * Create the PartitionDirectory infrastructure if we didn't already.
2215  */
2216  if (root->glob->partition_directory == NULL)
2217  {
2218  root->glob->partition_directory =
2220  }
2221 
2223  relation);
2224  rel->part_scheme = find_partition_scheme(root, relation);
2225  Assert(partdesc != NULL && rel->part_scheme != NULL);
2226  rel->boundinfo = partdesc->boundinfo;
2227  rel->nparts = partdesc->nparts;
2228  set_baserel_partition_key_exprs(relation, rel);
2229  set_baserel_partition_constraint(relation, rel);
2230 }
PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool omit_detached)
Definition: partdesc.c:377
PartitionDesc PartitionDirectoryLookup(PartitionDirectory pdir, Relation rel)
Definition: partdesc.c:410
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation rel)
Definition: plancat.c:2238
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2345
PartitionBoundInfo boundinfo
Definition: partdesc.h:38
PartitionDirectory partition_directory
Definition: pathnodes.h:132
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:765
PartitionScheme part_scheme
Definition: pathnodes.h:761
int nparts
Definition: pathnodes.h:762

References Assert(), RelOptInfo::boundinfo, PartitionDescData::boundinfo, CreatePartitionDirectory(), CurrentMemoryContext, find_partition_scheme(), PlannerInfo::glob, RelOptInfo::nparts, PartitionDescData::nparts, RelOptInfo::part_scheme, PlannerGlobal::partition_directory, 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().