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/index.h"
#include "catalog/pg_am.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_statistic_ext.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)
 
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 1976 of file plancat.c.

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

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

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

◆ build_index_tlist()

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

Definition at line 1772 of file plancat.c.

References elog, ERROR, FormData_pg_attribute, i, IndexOptInfo::indexkeys, IndexOptInfo::indexprs, lappend(), lfirst, list_head(), lnext(), makeTargetEntry(), makeVar(), IndexOptInfo::ncolumns, NIL, RelationData::rd_att, IndexOptInfo::rel, RelOptInfo::relid, SystemAttributeDefinition(), and TupleDescAttr.

Referenced by get_relation_info().

1774 {
1775  List *tlist = NIL;
1776  Index varno = index->rel->relid;
1777  ListCell *indexpr_item;
1778  int i;
1779 
1780  indexpr_item = list_head(index->indexprs);
1781  for (i = 0; i < index->ncolumns; i++)
1782  {
1783  int indexkey = index->indexkeys[i];
1784  Expr *indexvar;
1785 
1786  if (indexkey != 0)
1787  {
1788  /* simple column */
1789  const FormData_pg_attribute *att_tup;
1790 
1791  if (indexkey < 0)
1792  att_tup = SystemAttributeDefinition(indexkey);
1793  else
1794  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1795 
1796  indexvar = (Expr *) makeVar(varno,
1797  indexkey,
1798  att_tup->atttypid,
1799  att_tup->atttypmod,
1800  att_tup->attcollation,
1801  0);
1802  }
1803  else
1804  {
1805  /* expression column */
1806  if (indexpr_item == NULL)
1807  elog(ERROR, "wrong number of index expressions");
1808  indexvar = (Expr *) lfirst(indexpr_item);
1809  indexpr_item = lnext(index->indexprs, indexpr_item);
1810  }
1811 
1812  tlist = lappend(tlist,
1813  makeTargetEntry(indexvar,
1814  i + 1,
1815  NULL,
1816  false));
1817  }
1818  if (indexpr_item != NULL)
1819  elog(ERROR, "wrong number of index expressions");
1820 
1821  return tlist;
1822 }
#define NIL
Definition: pg_list.h:65
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:250
RelOptInfo * rel
Definition: pathnodes.h:832
#define ERROR
Definition: elog.h:46
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
unsigned int Index
Definition: c.h:549
TupleDesc rd_att
Definition: rel.h:111
FormData_pg_attribute
Definition: pg_attribute.h:187
#define lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:232
int i
int * indexkeys
Definition: pathnodes.h:842
Definition: pg_list.h:50
List * indexprs
Definition: pathnodes.h:855

◆ build_physical_tlist()

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1651 of file plancat.c.

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

Referenced by create_scan_plan().

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

◆ estimate_rel_size()

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

Definition at line 968 of file plancat.c.

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

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

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

◆ find_partition_scheme()

static PartitionScheme find_partition_scheme ( PlannerInfo root,
Relation  rel 
)
static

Definition at line 2222 of file plancat.c.

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

Referenced by set_relation_partition_info().

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

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

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

Referenced by clause_selectivity_ext().

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

◆ get_function_rows()

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

Definition at line 2037 of file plancat.c.

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

Referenced by expression_returns_set_rows().

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

◆ get_rel_data_width()

int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)

Definition at line 1106 of file plancat.c.

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

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

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

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

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

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

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1148 of file plancat.c.

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

1149 {
1150  int32 result;
1151  Relation relation;
1152 
1153  /* As above, assume relation is already locked */
1154  relation = table_open(relid, NoLock);
1155 
1156  result = get_rel_data_width(relation, attr_widths);
1157 
1158  table_close(relation, NoLock);
1159 
1160  return result;
1161 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
signed int int32
Definition: c.h:429
#define NoLock
Definition: lockdefs.h:34
int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1106
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ get_relation_foreign_keys()

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

Definition at line 505 of file plancat.c.

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

Referenced by get_relation_info().

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

◆ get_relation_info()

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

Definition at line 114 of file plancat.c.

References _bt_getrootheight(), RelOptInfo::allvisfrac, IndexOptInfo::amcanmarkpos, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanorderbyop, IndexOptInfo::amcanorderbyop, IndexAmRoutine::amcanparallel, IndexOptInfo::amcanparallel, IndexAmRoutine::amcostestimate, IndexOptInfo::amcostestimate, AMFLAG_HAS_TID_RANGE, RelOptInfo::amflags, IndexAmRoutine::amgetbitmap, IndexAmRoutine::amgettuple, IndexOptInfo::amhasgetbitmap, IndexOptInfo::amhasgettuple, IndexAmRoutine::ammarkpos, IndexAmRoutine::amoptionalkey, IndexOptInfo::amoptionalkey, IndexAmRoutine::amrestrpos, IndexAmRoutine::amsearcharray, IndexOptInfo::amsearcharray, IndexAmRoutine::amsearchnulls, IndexOptInfo::amsearchnulls, Assert, RelOptInfo::attr_needed, RelOptInfo::attr_widths, BTLessStrategyNumber, build_index_tlist(), IndexOptInfo::canreturn, ChangeVarNodes(), ereport, errcode(), errmsg(), ERROR, estimate_rel_size(), RelOptInfo::fdwroutine, FirstLowInvalidHeapAttributeNumber, get_opfamily_member(), get_ordering_op_properties(), get_relation_foreign_keys(), get_relation_info_hook, get_relation_statistics(), GetFdwRoutineForRelation(), GetForeignServerIdByRelId(), PlannerInfo::glob, HeapTupleHeaderGetXmin, IndexOptInfo::hypothetical, i, IgnoreSystemIndexes, IndexOptInfo::immediate, index_can_return(), index_check_collation_versions(), 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, RelationData::rd_version_checked, 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().

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

◆ get_relation_statistics()

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

Definition at line 1310 of file plancat.c.

References bms_add_member(), bms_copy(), bms_free(), ChangeVarNodes(), elog, ERROR, eval_const_expressions(), StatisticExtInfo::exprs, fix_opfuncids(), GETSTRUCT, HeapTupleIsValid, i, StatisticExtInfo::keys, StatisticExtInfo::kind, lappend(), lfirst_oid, list_free(), makeNode, NIL, ObjectIdGetDatum, pfree(), StatisticExtInfo::rel, RelationGetStatExtList(), ReleaseSysCache(), RelOptInfo::relid, SearchSysCache1(), statext_is_kind_built(), STATEXTDATASTXOID, STATEXTOID, StatisticExtInfo::statOid, stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

Referenced by get_relation_info().

1311 {
1312  Index varno = rel->relid;
1313  List *statoidlist;
1314  List *stainfos = NIL;
1315  ListCell *l;
1316 
1317  statoidlist = RelationGetStatExtList(relation);
1318 
1319  foreach(l, statoidlist)
1320  {
1321  Oid statOid = lfirst_oid(l);
1322  Form_pg_statistic_ext staForm;
1323  HeapTuple htup;
1324  HeapTuple dtup;
1325  Bitmapset *keys = NULL;
1326  List *exprs = NIL;
1327  int i;
1328 
1329  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1330  if (!HeapTupleIsValid(htup))
1331  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1332  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1333 
1335  if (!HeapTupleIsValid(dtup))
1336  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1337 
1338  /*
1339  * First, build the array of columns covered. This is ultimately
1340  * wasted if no stats within the object have actually been built, but
1341  * it doesn't seem worth troubling over that case.
1342  */
1343  for (i = 0; i < staForm->stxkeys.dim1; i++)
1344  keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1345 
1346  /*
1347  * Preprocess expressions (if any). We read the expressions, run them
1348  * through eval_const_expressions, and fix the varnos.
1349  */
1350  {
1351  bool isnull;
1352  Datum datum;
1353 
1354  /* decode expression (if any) */
1355  datum = SysCacheGetAttr(STATEXTOID, htup,
1356  Anum_pg_statistic_ext_stxexprs, &isnull);
1357 
1358  if (!isnull)
1359  {
1360  char *exprsString;
1361 
1362  exprsString = TextDatumGetCString(datum);
1363  exprs = (List *) stringToNode(exprsString);
1364  pfree(exprsString);
1365 
1366  /*
1367  * Run the expressions through eval_const_expressions. This is
1368  * not just an optimization, but is necessary, because the
1369  * planner will be comparing them to similarly-processed qual
1370  * clauses, and may fail to detect valid matches without this.
1371  * We must not use canonicalize_qual, however, since these
1372  * aren't qual expressions.
1373  */
1374  exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
1375 
1376  /* May as well fix opfuncids too */
1377  fix_opfuncids((Node *) exprs);
1378 
1379  /*
1380  * Modify the copies we obtain from the relcache to have the
1381  * correct varno for the parent relation, so that they match
1382  * up correctly against qual clauses.
1383  */
1384  if (varno != 1)
1385  ChangeVarNodes((Node *) exprs, 1, varno, 0);
1386  }
1387  }
1388 
1389  /* add one StatisticExtInfo for each kind built */
1390  if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1391  {
1393 
1394  info->statOid = statOid;
1395  info->rel = rel;
1396  info->kind = STATS_EXT_NDISTINCT;
1397  info->keys = bms_copy(keys);
1398  info->exprs = exprs;
1399 
1400  stainfos = lappend(stainfos, info);
1401  }
1402 
1403  if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1404  {
1406 
1407  info->statOid = statOid;
1408  info->rel = rel;
1409  info->kind = STATS_EXT_DEPENDENCIES;
1410  info->keys = bms_copy(keys);
1411  info->exprs = exprs;
1412 
1413  stainfos = lappend(stainfos, info);
1414  }
1415 
1416  if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1417  {
1419 
1420  info->statOid = statOid;
1421  info->rel = rel;
1422  info->kind = STATS_EXT_MCV;
1423  info->keys = bms_copy(keys);
1424  info->exprs = exprs;
1425 
1426  stainfos = lappend(stainfos, info);
1427  }
1428 
1429  if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
1430  {
1432 
1433  info->statOid = statOid;
1434  info->rel = rel;
1435  info->kind = STATS_EXT_EXPRESSIONS;
1436  info->keys = bms_copy(keys);
1437  info->exprs = exprs;
1438 
1439  stainfos = lappend(stainfos, info);
1440  }
1441 
1442  ReleaseSysCache(htup);
1443  ReleaseSysCache(dtup);
1444  bms_free(keys);
1445  }
1446 
1447  list_free(statoidlist);
1448 
1449  return stainfos;
1450 }
#define NIL
Definition: pg_list.h:65
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:539
void * stringToNode(const char *str)
Definition: read.c:89
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2090
bool statext_is_kind_built(HeapTuple htup, char type)
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
RelOptInfo * rel
Definition: pathnodes.h:929
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
unsigned int Index
Definition: c.h:549
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define makeNode(_type_)
Definition: nodes.h:587
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4670
Bitmapset * keys
Definition: pathnodes.h:931
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
int i
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
Definition: pg_list.h:50
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ has_row_triggers()

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

Definition at line 2127 of file plancat.c.

References CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ERROR, NoLock, planner_rt_fetch, RangeTblEntry::relid, table_close(), table_open(), TriggerDesc::trig_delete_after_row, TriggerDesc::trig_delete_before_row, TriggerDesc::trig_insert_after_row, TriggerDesc::trig_insert_before_row, TriggerDesc::trig_update_after_row, TriggerDesc::trig_update_before_row, and RelationData::trigdesc.

Referenced by make_modifytable().

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

◆ has_stored_generated_columns()

bool has_stored_generated_columns ( PlannerInfo root,
Index  rti 
)

Definition at line 2168 of file plancat.c.

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

Referenced by make_modifytable().

2169 {
2170  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2171  Relation relation;
2172  TupleDesc tupdesc;
2173  bool result = false;
2174 
2175  /* Assume we already have adequate lock */
2176  relation = table_open(rte->relid, NoLock);
2177 
2178  tupdesc = RelationGetDescr(relation);
2179  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2180 
2181  table_close(relation, NoLock);
2182 
2183  return result;
2184 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define RelationGetDescr(relation)
Definition: rel.h:483
bool has_generated_stored
Definition: tupdesc.h:45
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
#define NoLock
Definition: lockdefs.h:34
TupleConstr * constr
Definition: tupdesc.h:85
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2095 of file plancat.c.

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

Referenced by examine_variable().

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

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 620 of file plancat.c.

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, bms_add_member(), bms_equal(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, InferenceElem::expr, FirstLowInvalidHeapAttributeNumber, get_constraint_index(), index_close(), index_open(), infer_collation_opclass_match(), InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, IsA, lappend(), lappend_oid(), lfirst, lfirst_oid, list_difference(), list_free(), list_member(), next, NIL, NoLock, Query::onConflict, ONCONFLICT_UPDATE, PlannerInfo::parse, predicate_implied_by(), RelationData::rd_index, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RangeTblEntry::relid, RangeTblEntry::rellockmode, Query::resultRelation, rt_fetch, Query::rtable, table_close(), table_open(), and Var::varattno.

Referenced by make_modifytable().

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

◆ infer_collation_opclass_match()

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

Definition at line 886 of file plancat.c.

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

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

◆ join_selectivity()

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

Definition at line 1873 of file plancat.c.

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

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

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

◆ relation_excluded_by_constraints()

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

Definition at line 1464 of file plancat.c.

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

Referenced by set_append_rel_size(), and set_rel_size().

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

◆ restriction_selectivity()

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

Definition at line 1834 of file plancat.c.

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

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

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

◆ set_baserel_partition_constraint()

static void set_baserel_partition_constraint ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2397 of file plancat.c.

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

Referenced by get_relation_constraints(), and set_relation_partition_info().

2398 {
2399  List *partconstr;
2400 
2401  if (rel->partition_qual) /* already done */
2402  return;
2403 
2404  /*
2405  * Run the partition quals through const-simplification similar to check
2406  * constraints. We skip canonicalize_qual, though, because partition
2407  * quals should be in canonical form already; also, since the qual is in
2408  * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2409  * format and back again.
2410  */
2411  partconstr = RelationGetPartitionQual(relation);
2412  if (partconstr)
2413  {
2414  partconstr = (List *) expression_planner((Expr *) partconstr);
2415  if (rel->relid != 1)
2416  ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2417  rel->partition_qual = partconstr;
2418  }
2419 }
Expr * expression_planner(Expr *expr)
Definition: planner.c:5653
Definition: nodes.h:539
Index relid
Definition: pathnodes.h:704
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:276
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
List * partition_qual
Definition: pathnodes.h:762
Definition: pg_list.h:50

◆ set_baserel_partition_key_exprs()

static void set_baserel_partition_key_exprs ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2329 of file plancat.c.

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

Referenced by set_relation_partition_info().

2331 {
2332  PartitionKey partkey = RelationGetPartitionKey(relation);
2333  int partnatts;
2334  int cnt;
2335  List **partexprs;
2336  ListCell *lc;
2337  Index varno = rel->relid;
2338 
2339  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2340 
2341  /* A partitioned table should have a partition key. */
2342  Assert(partkey != NULL);
2343 
2344  partnatts = partkey->partnatts;
2345  partexprs = (List **) palloc(sizeof(List *) * partnatts);
2346  lc = list_head(partkey->partexprs);
2347 
2348  for (cnt = 0; cnt < partnatts; cnt++)
2349  {
2350  Expr *partexpr;
2351  AttrNumber attno = partkey->partattrs[cnt];
2352 
2353  if (attno != InvalidAttrNumber)
2354  {
2355  /* Single column partition key is stored as a Var node. */
2356  Assert(attno > 0);
2357 
2358  partexpr = (Expr *) makeVar(varno, attno,
2359  partkey->parttypid[cnt],
2360  partkey->parttypmod[cnt],
2361  partkey->parttypcoll[cnt], 0);
2362  }
2363  else
2364  {
2365  if (lc == NULL)
2366  elog(ERROR, "wrong number of partition key expressions");
2367 
2368  /* Re-stamp the expression with given varno. */
2369  partexpr = (Expr *) copyObject(lfirst(lc));
2370  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2371  lc = lnext(partkey->partexprs, lc);
2372  }
2373 
2374  /* Base relations have a single expression per key. */
2375  partexprs[cnt] = list_make1(partexpr);
2376  }
2377 
2378  rel->partexprs = partexprs;
2379 
2380  /*
2381  * A base relation does not have nullable partition key expressions, since
2382  * no outer join is involved. We still allocate an array of empty
2383  * expression lists to keep partition key expression handling code simple.
2384  * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2385  */
2386  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2387 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
Definition: nodes.h:539
List * partexprs
Definition: partcache.h:30
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
List ** nullable_partexprs
Definition: pathnodes.h:767
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:649
#define list_make1(x1)
Definition: pg_list.h:206
Oid * parttypcoll
Definition: partcache.h:46
List ** partexprs
Definition: pathnodes.h:766
#define ERROR
Definition: elog.h:46
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Index relid
Definition: pathnodes.h:704
void * palloc0(Size size)
Definition: mcxt.c:1093
AttrNumber * partattrs
Definition: partcache.h:28
unsigned int Index
Definition: c.h:549
int32 * parttypmod
Definition: partcache.h:42
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define InvalidAttrNumber
Definition: attnum.h:23
void * palloc(Size size)
Definition: mcxt.c:1062
#define elog(elevel,...)
Definition: elog.h:232
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:610
#define copyObject(obj)
Definition: nodes.h:655
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21

◆ set_relation_partition_info()

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

Definition at line 2192 of file plancat.c.

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

Referenced by get_relation_info().

2194 {
2195  PartitionDesc partdesc;
2196 
2197  /*
2198  * Create the PartitionDirectory infrastructure if we didn't already.
2199  */
2200  if (root->glob->partition_directory == NULL)
2201  {
2202  root->glob->partition_directory =
2204  }
2205 
2207  relation);
2208  rel->part_scheme = find_partition_scheme(root, relation);
2209  Assert(partdesc != NULL && rel->part_scheme != NULL);
2210  rel->boundinfo = partdesc->boundinfo;
2211  rel->nparts = partdesc->nparts;
2212  set_baserel_partition_key_exprs(relation, rel);
2213  set_baserel_partition_constraint(relation, rel);
2214 }
PartitionBoundInfo boundinfo
Definition: partdesc.h:30
PlannerGlobal * glob
Definition: pathnodes.h:163
int nparts
Definition: pathnodes.h:756
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool include_detached)
Definition: partdesc.c:287
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:759
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2397
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation rel)
Definition: plancat.c:2222
#define Assert(condition)
Definition: c.h:804
PartitionScheme part_scheme
Definition: pathnodes.h:755
PartitionDesc PartitionDirectoryLookup(PartitionDirectory pdir, Relation rel)
Definition: partdesc.c:320
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2329
PartitionDirectory partition_directory
Definition: pathnodes.h:131

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