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

Go to the source code of this file.

Functions

static void get_relation_foreign_keys (PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
 
static bool infer_collation_opclass_match (InferenceElem *elem, Relation idxRel, List *idxExprs)
 
static Listget_relation_constraints (PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
 
static Listbuild_index_tlist (PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
 
static Listget_relation_statistics (RelOptInfo *rel, Relation relation)
 
static void set_relation_partition_info (PlannerInfo *root, RelOptInfo *rel, Relation relation)
 
static PartitionScheme find_partition_scheme (PlannerInfo *root, Relation relation)
 
static void set_baserel_partition_key_exprs (Relation relation, RelOptInfo *rel)
 
static void set_baserel_partition_constraint (Relation relation, RelOptInfo *rel)
 
void get_relation_info (PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
 
Listinfer_arbiter_indexes (PlannerInfo *root)
 
void estimate_rel_size (Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
 
int32 get_rel_data_width (Relation rel, int32 *attr_widths)
 
int32 get_relation_data_width (Oid relid, int32 *attr_widths)
 
static void get_relation_statistics_worker (List **stainfos, RelOptInfo *rel, Oid statOid, bool inh, Bitmapset *keys, List *exprs)
 
bool relation_excluded_by_constraints (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
Listbuild_physical_tlist (PlannerInfo *root, RelOptInfo *rel)
 
Selectivity restriction_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
 
Selectivity join_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity function_selectivity (PlannerInfo *root, Oid funcid, List *args, Oid inputcollid, bool is_join, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
void add_function_cost (PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
 
double get_function_rows (PlannerInfo *root, Oid funcid, Node *node)
 
bool has_unique_index (RelOptInfo *rel, AttrNumber attno)
 
bool has_row_triggers (PlannerInfo *root, Index rti, CmdType event)
 
bool has_stored_generated_columns (PlannerInfo *root, Index rti)
 
Bitmapsetget_dependent_generated_columns (PlannerInfo *root, Index rti, Bitmapset *target_cols)
 

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

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

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

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

◆ build_index_tlist()

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

Definition at line 1859 of file plancat.c.

1861 {
1862  List *tlist = NIL;
1863  Index varno = index->rel->relid;
1864  ListCell *indexpr_item;
1865  int i;
1866 
1867  indexpr_item = list_head(index->indexprs);
1868  for (i = 0; i < index->ncolumns; i++)
1869  {
1870  int indexkey = index->indexkeys[i];
1871  Expr *indexvar;
1872 
1873  if (indexkey != 0)
1874  {
1875  /* simple column */
1876  const FormData_pg_attribute *att_tup;
1877 
1878  if (indexkey < 0)
1879  att_tup = SystemAttributeDefinition(indexkey);
1880  else
1881  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1882 
1883  indexvar = (Expr *) makeVar(varno,
1884  indexkey,
1885  att_tup->atttypid,
1886  att_tup->atttypmod,
1887  att_tup->attcollation,
1888  0);
1889  }
1890  else
1891  {
1892  /* expression column */
1893  if (indexpr_item == NULL)
1894  elog(ERROR, "wrong number of index expressions");
1895  indexvar = (Expr *) lfirst(indexpr_item);
1896  indexpr_item = lnext(index->indexprs, indexpr_item);
1897  }
1898 
1899  tlist = lappend(tlist,
1900  makeTargetEntry(indexvar,
1901  i + 1,
1902  NULL,
1903  false));
1904  }
1905  if (indexpr_item != NULL)
1906  elog(ERROR, "wrong number of index expressions");
1907 
1908  return tlist;
1909 }
unsigned int Index
Definition: c.h:603
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:240
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:339
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:241
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
FormData_pg_attribute
Definition: pg_attribute.h:193
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
Definition: pg_list.h:54
TupleDesc rd_att
Definition: rel.h:112
Definition: type.h:95
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

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

Referenced by get_relation_info().

◆ build_physical_tlist()

List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1738 of file plancat.c.

1739 {
1740  List *tlist = NIL;
1741  Index varno = rel->relid;
1742  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1743  Relation relation;
1744  Query *subquery;
1745  Var *var;
1746  ListCell *l;
1747  int attrno,
1748  numattrs;
1749  List *colvars;
1750 
1751  switch (rte->rtekind)
1752  {
1753  case RTE_RELATION:
1754  /* Assume we already have adequate lock */
1755  relation = table_open(rte->relid, NoLock);
1756 
1757  numattrs = RelationGetNumberOfAttributes(relation);
1758  for (attrno = 1; attrno <= numattrs; attrno++)
1759  {
1760  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1761  attrno - 1);
1762 
1763  if (att_tup->attisdropped || att_tup->atthasmissing)
1764  {
1765  /* found a dropped or missing col, so punt */
1766  tlist = NIL;
1767  break;
1768  }
1769 
1770  var = makeVar(varno,
1771  attrno,
1772  att_tup->atttypid,
1773  att_tup->atttypmod,
1774  att_tup->attcollation,
1775  0);
1776 
1777  tlist = lappend(tlist,
1778  makeTargetEntry((Expr *) var,
1779  attrno,
1780  NULL,
1781  false));
1782  }
1783 
1784  table_close(relation, NoLock);
1785  break;
1786 
1787  case RTE_SUBQUERY:
1788  subquery = rte->subquery;
1789  foreach(l, subquery->targetList)
1790  {
1791  TargetEntry *tle = (TargetEntry *) lfirst(l);
1792 
1793  /*
1794  * A resjunk column of the subquery can be reflected as
1795  * resjunk in the physical tlist; we need not punt.
1796  */
1797  var = makeVarFromTargetEntry(varno, tle);
1798 
1799  tlist = lappend(tlist,
1800  makeTargetEntry((Expr *) var,
1801  tle->resno,
1802  NULL,
1803  tle->resjunk));
1804  }
1805  break;
1806 
1807  case RTE_FUNCTION:
1808  case RTE_TABLEFUNC:
1809  case RTE_VALUES:
1810  case RTE_CTE:
1811  case RTE_NAMEDTUPLESTORE:
1812  case RTE_RESULT:
1813  /* Not all of these can have dropped cols, but share code anyway */
1814  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1815  NULL, &colvars);
1816  foreach(l, colvars)
1817  {
1818  var = (Var *) lfirst(l);
1819 
1820  /*
1821  * A non-Var in expandRTE's output means a dropped column;
1822  * must punt.
1823  */
1824  if (!IsA(var, Var))
1825  {
1826  tlist = NIL;
1827  break;
1828  }
1829 
1830  tlist = lappend(tlist,
1831  makeTargetEntry((Expr *) var,
1832  var->varattno,
1833  NULL,
1834  false));
1835  }
1836  break;
1837 
1838  default:
1839  /* caller error */
1840  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1841  (int) rte->rtekind);
1842  break;
1843  }
1844 
1845  return tlist;
1846 }
#define NoLock
Definition: lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:106
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_CTE
Definition: parsenodes.h:1012
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1013
@ RTE_VALUES
Definition: parsenodes.h:1011
@ RTE_SUBQUERY
Definition: parsenodes.h:1007
@ RTE_RESULT
Definition: parsenodes.h:1014
@ RTE_FUNCTION
Definition: parsenodes.h:1009
@ RTE_TABLEFUNC
Definition: parsenodes.h:1010
@ RTE_RELATION
Definition: parsenodes.h:1006
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:555
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:510
List * targetList
Definition: parsenodes.h:181
Query * subquery
Definition: parsenodes.h:1073
RTEKind rtekind
Definition: parsenodes.h:1025
Index relid
Definition: pathnodes.h:903
AttrNumber resno
Definition: primnodes.h:1924
Definition: primnodes.h:234
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

Referenced by create_scan_plan().

◆ estimate_rel_size()

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

Definition at line 1032 of file plancat.c.

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

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

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

◆ find_partition_scheme()

static PartitionScheme find_partition_scheme ( PlannerInfo root,
Relation  relation 
)
static

Definition at line 2369 of file plancat.c.

2370 {
2371  PartitionKey partkey = RelationGetPartitionKey(relation);
2372  ListCell *lc;
2373  int partnatts,
2374  i;
2375  PartitionScheme part_scheme;
2376 
2377  /* A partitioned table should have a partition key. */
2378  Assert(partkey != NULL);
2379 
2380  partnatts = partkey->partnatts;
2381 
2382  /* Search for a matching partition scheme and return if found one. */
2383  foreach(lc, root->part_schemes)
2384  {
2385  part_scheme = lfirst(lc);
2386 
2387  /* Match partitioning strategy and number of keys. */
2388  if (partkey->strategy != part_scheme->strategy ||
2389  partnatts != part_scheme->partnatts)
2390  continue;
2391 
2392  /* Match partition key type properties. */
2393  if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2394  sizeof(Oid) * partnatts) != 0 ||
2395  memcmp(partkey->partopcintype, part_scheme->partopcintype,
2396  sizeof(Oid) * partnatts) != 0 ||
2397  memcmp(partkey->partcollation, part_scheme->partcollation,
2398  sizeof(Oid) * partnatts) != 0)
2399  continue;
2400 
2401  /*
2402  * Length and byval information should match when partopcintype
2403  * matches.
2404  */
2405  Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2406  sizeof(int16) * partnatts) == 0);
2407  Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2408  sizeof(bool) * partnatts) == 0);
2409 
2410  /*
2411  * If partopfamily and partopcintype matched, must have the same
2412  * partition comparison functions. Note that we cannot reliably
2413  * Assert the equality of function structs themselves for they might
2414  * be different across PartitionKey's, so just Assert for the function
2415  * OIDs.
2416  */
2417 #ifdef USE_ASSERT_CHECKING
2418  for (i = 0; i < partkey->partnatts; i++)
2419  Assert(partkey->partsupfunc[i].fn_oid ==
2420  part_scheme->partsupfunc[i].fn_oid);
2421 #endif
2422 
2423  /* Found matching partition scheme. */
2424  return part_scheme;
2425  }
2426 
2427  /*
2428  * Did not find matching partition scheme. Create one copying relevant
2429  * information from the relcache. We need to copy the contents of the
2430  * array since the relcache entry may not survive after we have closed the
2431  * relation.
2432  */
2433  part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
2434  part_scheme->strategy = partkey->strategy;
2435  part_scheme->partnatts = partkey->partnatts;
2436 
2437  part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
2438  memcpy(part_scheme->partopfamily, partkey->partopfamily,
2439  sizeof(Oid) * partnatts);
2440 
2441  part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
2442  memcpy(part_scheme->partopcintype, partkey->partopcintype,
2443  sizeof(Oid) * partnatts);
2444 
2445  part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
2446  memcpy(part_scheme->partcollation, partkey->partcollation,
2447  sizeof(Oid) * partnatts);
2448 
2449  part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
2450  memcpy(part_scheme->parttyplen, partkey->parttyplen,
2451  sizeof(int16) * partnatts);
2452 
2453  part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
2454  memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2455  sizeof(bool) * partnatts);
2456 
2457  part_scheme->partsupfunc = (FmgrInfo *)
2458  palloc(sizeof(FmgrInfo) * partnatts);
2459  for (i = 0; i < partnatts; i++)
2460  fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2462 
2463  /* Add the partitioning scheme to PlannerInfo. */
2464  root->part_schemes = lappend(root->part_schemes, part_scheme);
2465 
2466  return part_scheme;
2467 }
signed short int16
Definition: c.h:482
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:580
Assert(fmt[strlen(fmt) - 1] !='\n')
void * palloc0(Size size)
Definition: mcxt.c:1232
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void * palloc(Size size)
Definition: mcxt.c:1201
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:54
struct PartitionSchemeData * PartitionScheme
Definition: pathnodes.h:589
unsigned int Oid
Definition: postgres_ext.h:31
Definition: fmgr.h:57
Oid fn_oid
Definition: fmgr.h:59
Oid * partcollation
Definition: partcache.h:39
Oid * partopfamily
Definition: partcache.h:34
bool * parttypbyval
Definition: partcache.h:45
PartitionStrategy strategy
Definition: partcache.h:27
int16 * parttyplen
Definition: partcache.h:44
FmgrInfo * partsupfunc
Definition: partcache.h:36
Oid * partopcintype
Definition: partcache.h:35
struct FmgrInfo * partsupfunc
Definition: pathnodes.h:586

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

Referenced by set_relation_partition_info().

◆ function_selectivity()

Selectivity function_selectivity ( PlannerInfo root,
Oid  funcid,
List args,
Oid  inputcollid,
bool  is_join,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 2001 of file plancat.c.

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

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

Referenced by clause_selectivity_ext().

◆ get_dependent_generated_columns()

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

Definition at line 2291 of file plancat.c.

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

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

Referenced by get_rel_all_updated_cols().

◆ get_function_rows()

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

Definition at line 2124 of file plancat.c.

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

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

Referenced by expression_returns_set_rows().

◆ get_rel_data_width()

int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)

Definition at line 1157 of file plancat.c.

1158 {
1159  int64 tuple_width = 0;
1160  int i;
1161 
1162  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1163  {
1164  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1165  int32 item_width;
1166 
1167  if (att->attisdropped)
1168  continue;
1169 
1170  /* use previously cached data, if any */
1171  if (attr_widths != NULL && attr_widths[i] > 0)
1172  {
1173  tuple_width += attr_widths[i];
1174  continue;
1175  }
1176 
1177  /* This should match set_rel_width() in costsize.c */
1178  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1179  if (item_width <= 0)
1180  {
1181  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1182  Assert(item_width > 0);
1183  }
1184  if (attr_widths != NULL)
1185  attr_widths[i] = item_width;
1186  tuple_width += item_width;
1187  }
1188 
1189  return clamp_width_est(tuple_width);
1190 }
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:232
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3113
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2533
#define RelationGetRelid(relation)
Definition: rel.h:504

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

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

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

1244 {
1245  List *result = NIL;
1246  Index varno = rel->relid;
1247  Relation relation;
1248  TupleConstr *constr;
1249 
1250  /*
1251  * We assume the relation has already been safely locked.
1252  */
1253  relation = table_open(relationObjectId, NoLock);
1254 
1255  constr = relation->rd_att->constr;
1256  if (constr != NULL)
1257  {
1258  int num_check = constr->num_check;
1259  int i;
1260 
1261  for (i = 0; i < num_check; i++)
1262  {
1263  Node *cexpr;
1264 
1265  /*
1266  * If this constraint hasn't been fully validated yet, we must
1267  * ignore it here. Also ignore if NO INHERIT and we weren't told
1268  * that that's safe.
1269  */
1270  if (!constr->check[i].ccvalid)
1271  continue;
1272  if (constr->check[i].ccnoinherit && !include_noinherit)
1273  continue;
1274 
1275  cexpr = stringToNode(constr->check[i].ccbin);
1276 
1277  /*
1278  * Run each expression through const-simplification and
1279  * canonicalization. This is not just an optimization, but is
1280  * necessary, because we will be comparing it to
1281  * similarly-processed qual clauses, and may fail to detect valid
1282  * matches without this. This must match the processing done to
1283  * qual clauses in preprocess_expression()! (We can skip the
1284  * stuff involving subqueries, however, since we don't allow any
1285  * in check constraints.)
1286  */
1287  cexpr = eval_const_expressions(root, cexpr);
1288 
1289  cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1290 
1291  /* Fix Vars to have the desired varno */
1292  if (varno != 1)
1293  ChangeVarNodes(cexpr, 1, varno, 0);
1294 
1295  /*
1296  * Finally, convert to implicit-AND format (that is, a List) and
1297  * append the resulting item(s) to our output list.
1298  */
1299  result = list_concat(result,
1300  make_ands_implicit((Expr *) cexpr));
1301  }
1302 
1303  /* Add NOT NULL constraints in expression form, if requested */
1304  if (include_notnull && constr->has_not_null)
1305  {
1306  int natts = relation->rd_att->natts;
1307 
1308  for (i = 1; i <= natts; i++)
1309  {
1310  Form_pg_attribute att = TupleDescAttr(relation->rd_att, i - 1);
1311 
1312  if (att->attnotnull && !att->attisdropped)
1313  {
1314  NullTest *ntest = makeNode(NullTest);
1315 
1316  ntest->arg = (Expr *) makeVar(varno,
1317  i,
1318  att->atttypid,
1319  att->atttypmod,
1320  att->attcollation,
1321  0);
1322  ntest->nulltesttype = IS_NOT_NULL;
1323 
1324  /*
1325  * argisrow=false is correct even for a composite column,
1326  * because attnotnull does not represent a SQL-spec IS NOT
1327  * NULL test in such a case, just IS DISTINCT FROM NULL.
1328  */
1329  ntest->argisrow = false;
1330  ntest->location = -1;
1331  result = lappend(result, ntest);
1332  }
1333  }
1334  }
1335  }
1336 
1337  /*
1338  * Add partitioning constraints, if requested.
1339  */
1340  if (include_partition && relation->rd_rel->relispartition)
1341  {
1342  /* make sure rel->partition_qual is set */
1343  set_baserel_partition_constraint(relation, rel);
1344  result = list_concat(result, rel->partition_qual);
1345  }
1346 
1347  table_close(relation, NoLock);
1348 
1349  return result;
1350 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2237
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:722
#define makeNode(_type_)
Definition: nodes.h:155
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2544
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:294
@ IS_NOT_NULL
Definition: primnodes.h:1694
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:670
bool ccnoinherit
Definition: tupdesc.h:33
bool ccvalid
Definition: tupdesc.h:32
char * ccbin
Definition: tupdesc.h:31
NullTestType nulltesttype
Definition: primnodes.h:1701
int location
Definition: primnodes.h:1704
Expr * arg
Definition: primnodes.h:1700
List * partition_qual
Definition: pathnodes.h:1008
bool has_not_null
Definition: tupdesc.h:44
ConstrCheck * check
Definition: tupdesc.h:40
uint16 num_check
Definition: tupdesc.h:43

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

Referenced by relation_excluded_by_constraints().

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1199 of file plancat.c.

1200 {
1201  int32 result;
1202  Relation relation;
1203 
1204  /* As above, assume relation is already locked */
1205  relation = table_open(relid, NoLock);
1206 
1207  result = get_rel_data_width(relation, attr_widths);
1208 
1209  table_close(relation, NoLock);
1210 
1211  return result;
1212 }

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

◆ get_relation_foreign_keys()

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

Definition at line 569 of file plancat.c.

571 {
572  List *rtable = root->parse->rtable;
573  List *cachedfkeys;
574  ListCell *lc;
575 
576  /*
577  * If it's not a baserel, we don't care about its FKs. Also, if the query
578  * references only a single relation, we can skip the lookup since no FKs
579  * could satisfy the requirements below.
580  */
581  if (rel->reloptkind != RELOPT_BASEREL ||
582  list_length(rtable) < 2)
583  return;
584 
585  /*
586  * If it's the parent of an inheritance tree, ignore its FKs. We could
587  * make useful FK-based deductions if we found that all members of the
588  * inheritance tree have equivalent FK constraints, but detecting that
589  * would require code that hasn't been written.
590  */
591  if (inhparent)
592  return;
593 
594  /*
595  * Extract data about relation's FKs from the relcache. Note that this
596  * list belongs to the relcache and might disappear in a cache flush, so
597  * we must not do any further catalog access within this function.
598  */
599  cachedfkeys = RelationGetFKeyList(relation);
600 
601  /*
602  * Figure out which FKs are of interest for this query, and create
603  * ForeignKeyOptInfos for them. We want only FKs that reference some
604  * other RTE of the current query. In queries containing self-joins,
605  * there might be more than one other RTE for a referenced table, and we
606  * should make a ForeignKeyOptInfo for each occurrence.
607  *
608  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
609  * too hard to identify those here, so we might end up making some useless
610  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
611  * them again.
612  */
613  foreach(lc, cachedfkeys)
614  {
615  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
616  Index rti;
617  ListCell *lc2;
618 
619  /* conrelid should always be that of the table we're considering */
620  Assert(cachedfk->conrelid == RelationGetRelid(relation));
621 
622  /* Scan to find other RTEs matching confrelid */
623  rti = 0;
624  foreach(lc2, rtable)
625  {
626  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
627  ForeignKeyOptInfo *info;
628 
629  rti++;
630  /* Ignore if not the correct table */
631  if (rte->rtekind != RTE_RELATION ||
632  rte->relid != cachedfk->confrelid)
633  continue;
634  /* Ignore if it's an inheritance parent; doesn't really match */
635  if (rte->inh)
636  continue;
637  /* Ignore self-referential FKs; we only care about joins */
638  if (rti == rel->relid)
639  continue;
640 
641  /* OK, let's make an entry */
642  info = makeNode(ForeignKeyOptInfo);
643  info->con_relid = rel->relid;
644  info->ref_relid = rti;
645  info->nkeys = cachedfk->nkeys;
646  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
647  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
648  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
649  /* zero out fields to be filled by match_foreign_keys_to_quals */
650  info->nmatched_ec = 0;
651  info->nconst_ec = 0;
652  info->nmatched_rcols = 0;
653  info->nmatched_ri = 0;
654  memset(info->eclass, 0, sizeof(info->eclass));
655  memset(info->fk_eclass_member, 0, sizeof(info->fk_eclass_member));
656  memset(info->rinfos, 0, sizeof(info->rinfos));
657 
658  root->fkey_list = lappend(root->fkey_list, info);
659  }
660  }
661 }
@ RELOPT_BASEREL
Definition: pathnodes.h:812
static int list_length(const List *l)
Definition: pg_list.h:152
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4646
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1237
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:1241
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1239
List * fkey_list
Definition: pathnodes.h:379
Query * parse
Definition: pathnodes.h:199
List * rtable
Definition: parsenodes.h:167
RelOptKind reloptkind
Definition: pathnodes.h:850

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

Referenced by get_relation_info().

◆ get_relation_info()

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

Definition at line 117 of file plancat.c.

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

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

Referenced by build_simple_rel().

◆ get_relation_statistics()

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

Definition at line 1442 of file plancat.c.

1443 {
1444  Index varno = rel->relid;
1445  List *statoidlist;
1446  List *stainfos = NIL;
1447  ListCell *l;
1448 
1449  statoidlist = RelationGetStatExtList(relation);
1450 
1451  foreach(l, statoidlist)
1452  {
1453  Oid statOid = lfirst_oid(l);
1454  Form_pg_statistic_ext staForm;
1455  HeapTuple htup;
1456  Bitmapset *keys = NULL;
1457  List *exprs = NIL;
1458  int i;
1459 
1460  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1461  if (!HeapTupleIsValid(htup))
1462  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1463  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1464 
1465  /*
1466  * First, build the array of columns covered. This is ultimately
1467  * wasted if no stats within the object have actually been built, but
1468  * it doesn't seem worth troubling over that case.
1469  */
1470  for (i = 0; i < staForm->stxkeys.dim1; i++)
1471  keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1472 
1473  /*
1474  * Preprocess expressions (if any). We read the expressions, run them
1475  * through eval_const_expressions, and fix the varnos.
1476  *
1477  * XXX We don't know yet if there are any data for this stats object,
1478  * with either stxdinherit value. But it's reasonable to assume there
1479  * is at least one of those, possibly both. So it's better to process
1480  * keys and expressions here.
1481  */
1482  {
1483  bool isnull;
1484  Datum datum;
1485 
1486  /* decode expression (if any) */
1487  datum = SysCacheGetAttr(STATEXTOID, htup,
1488  Anum_pg_statistic_ext_stxexprs, &isnull);
1489 
1490  if (!isnull)
1491  {
1492  char *exprsString;
1493 
1494  exprsString = TextDatumGetCString(datum);
1495  exprs = (List *) stringToNode(exprsString);
1496  pfree(exprsString);
1497 
1498  /*
1499  * Run the expressions through eval_const_expressions. This is
1500  * not just an optimization, but is necessary, because the
1501  * planner will be comparing them to similarly-processed qual
1502  * clauses, and may fail to detect valid matches without this.
1503  * We must not use canonicalize_qual, however, since these
1504  * aren't qual expressions.
1505  */
1506  exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
1507 
1508  /* May as well fix opfuncids too */
1509  fix_opfuncids((Node *) exprs);
1510 
1511  /*
1512  * Modify the copies we obtain from the relcache to have the
1513  * correct varno for the parent relation, so that they match
1514  * up correctly against qual clauses.
1515  */
1516  if (varno != 1)
1517  ChangeVarNodes((Node *) exprs, 1, varno, 0);
1518  }
1519  }
1520 
1521  /* extract statistics for possible values of stxdinherit flag */
1522 
1523  get_relation_statistics_worker(&stainfos, rel, statOid, true, keys, exprs);
1524 
1525  get_relation_statistics_worker(&stainfos, rel, statOid, false, keys, exprs);
1526 
1527  ReleaseSysCache(htup);
1528  bms_free(keys);
1529  }
1530 
1531  list_free(statoidlist);
1532 
1533  return stainfos;
1534 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:252
#define TextDatumGetCString(d)
Definition: builtins.h:98
void pfree(void *pointer)
Definition: mcxt.c:1431
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1748
FormData_pg_statistic_ext * Form_pg_statistic_ext
static void get_relation_statistics_worker(List **stainfos, RelOptInfo *rel, Oid statOid, bool inh, Bitmapset *keys, List *exprs)
Definition: plancat.c:1359
uintptr_t Datum
Definition: postgres.h:64
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4896
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:480

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

Referenced by get_relation_info().

◆ get_relation_statistics_worker()

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

Definition at line 1359 of file plancat.c.

1362 {
1363  Form_pg_statistic_ext_data dataForm;
1364  HeapTuple dtup;
1365 
1366  dtup = SearchSysCache2(STATEXTDATASTXOID,
1367  ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1368  if (!HeapTupleIsValid(dtup))
1369  return;
1370 
1371  dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
1372 
1373  /* add one StatisticExtInfo for each kind built */
1374  if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1375  {
1377 
1378  info->statOid = statOid;
1379  info->inherit = dataForm->stxdinherit;
1380  info->rel = rel;
1381  info->kind = STATS_EXT_NDISTINCT;
1382  info->keys = bms_copy(keys);
1383  info->exprs = exprs;
1384 
1385  *stainfos = lappend(*stainfos, info);
1386  }
1387 
1388  if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1389  {
1391 
1392  info->statOid = statOid;
1393  info->inherit = dataForm->stxdinherit;
1394  info->rel = rel;
1395  info->kind = STATS_EXT_DEPENDENCIES;
1396  info->keys = bms_copy(keys);
1397  info->exprs = exprs;
1398 
1399  *stainfos = lappend(*stainfos, info);
1400  }
1401 
1402  if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1403  {
1405 
1406  info->statOid = statOid;
1407  info->inherit = dataForm->stxdinherit;
1408  info->rel = rel;
1409  info->kind = STATS_EXT_MCV;
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_EXPRESSIONS))
1417  {
1419 
1420  info->statOid = statOid;
1421  info->inherit = dataForm->stxdinherit;
1422  info->rel = rel;
1423  info->kind = STATS_EXT_EXPRESSIONS;
1424  info->keys = bms_copy(keys);
1425  info->exprs = exprs;
1426 
1427  *stainfos = lappend(*stainfos, info);
1428  }
1429 
1430  ReleaseSysCache(dtup);
1431 }
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:135
bool statext_is_kind_built(HeapTuple htup, char type)
FormData_pg_statistic_ext_data * Form_pg_statistic_ext_data
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
Bitmapset * keys
Definition: pathnodes.h:1270
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:230

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

Referenced by get_relation_statistics().

◆ has_row_triggers()

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

Definition at line 2214 of file plancat.c.

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

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

Referenced by make_modifytable().

◆ has_stored_generated_columns()

bool has_stored_generated_columns ( PlannerInfo root,
Index  rti 
)

Definition at line 2264 of file plancat.c.

2265 {
2266  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2267  Relation relation;
2268  TupleDesc tupdesc;
2269  bool result = false;
2270 
2271  /* Assume we already have adequate lock */
2272  relation = table_open(rte->relid, NoLock);
2273 
2274  tupdesc = RelationGetDescr(relation);
2275  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2276 
2277  table_close(relation, NoLock);
2278 
2279  return result;
2280 }

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

Referenced by make_modifytable().

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2182 of file plancat.c.

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

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 684 of file plancat.c.

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

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

Referenced by make_modifytable().

◆ infer_collation_opclass_match()

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

Definition at line 950 of file plancat.c.

952 {
953  AttrNumber natt;
954  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
955  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
956  int nplain = 0; /* # plain attrs observed */
957 
958  /*
959  * If inference specification element lacks collation/opclass, then no
960  * need to check for exact match.
961  */
962  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
963  return true;
964 
965  /*
966  * Lookup opfamily and input type, for matching indexes
967  */
968  if (elem->inferopclass)
969  {
970  inferopfamily = get_opclass_family(elem->inferopclass);
971  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
972  }
973 
974  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
975  {
976  Oid opfamily = idxRel->rd_opfamily[natt - 1];
977  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
978  Oid collation = idxRel->rd_indcollation[natt - 1];
979  int attno = idxRel->rd_index->indkey.values[natt - 1];
980 
981  if (attno != 0)
982  nplain++;
983 
984  if (elem->inferopclass != InvalidOid &&
985  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
986  {
987  /* Attribute needed to match opclass, but didn't */
988  continue;
989  }
990 
991  if (elem->infercollid != InvalidOid &&
992  elem->infercollid != collation)
993  {
994  /* Attribute needed to match collation, but didn't */
995  continue;
996  }
997 
998  /* If one matching index att found, good enough -- return true */
999  if (IsA(elem->expr, Var))
1000  {
1001  if (((Var *) elem->expr)->varattno == attno)
1002  return true;
1003  }
1004  else if (attno == 0)
1005  {
1006  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
1007 
1008  /*
1009  * Note that unlike routines like match_index_to_operand() we
1010  * don't need to care about RelabelType. Neither the index
1011  * definition nor the inference clause should contain them.
1012  */
1013  if (equal(elem->expr, nattExpr))
1014  return true;
1015  }
1016  }
1017 
1018  return false;
1019 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1189
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1167
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299

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

Referenced by infer_arbiter_indexes().

◆ join_selectivity()

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

Definition at line 1960 of file plancat.c.

1966 {
1967  RegProcedure oprjoin = get_oprjoin(operatorid);
1968  float8 result;
1969 
1970  /*
1971  * if the oprjoin procedure is missing for whatever reason, use a
1972  * selectivity of 0.5
1973  */
1974  if (!oprjoin)
1975  return (Selectivity) 0.5;
1976 
1977  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1978  inputcollid,
1979  PointerGetDatum(root),
1980  ObjectIdGetDatum(operatorid),
1982  Int16GetDatum(jointype),
1983  PointerGetDatum(sjinfo)));
1984 
1985  if (result < 0.0 || result > 1.0)
1986  elog(ERROR, "invalid join selectivity: %f", result);
1987 
1988  return (Selectivity) result;
1989 }
double float8
Definition: c.h:619
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1453
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1558
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:172
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:494

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

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

◆ relation_excluded_by_constraints()

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

Definition at line 1548 of file plancat.c.

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

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

Referenced by set_append_rel_size(), and set_rel_size().

◆ restriction_selectivity()

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

Definition at line 1921 of file plancat.c.

1926 {
1927  RegProcedure oprrest = get_oprrest(operatorid);
1928  float8 result;
1929 
1930  /*
1931  * if the oprrest procedure is missing for whatever reason, use a
1932  * selectivity of 0.5
1933  */
1934  if (!oprrest)
1935  return (Selectivity) 0.5;
1936 
1937  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1938  inputcollid,
1939  PointerGetDatum(root),
1940  ObjectIdGetDatum(operatorid),
1942  Int32GetDatum(varRelid)));
1943 
1944  if (result < 0.0 || result > 1.0)
1945  elog(ERROR, "invalid restriction selectivity: %f", result);
1946 
1947  return (Selectivity) result;
1948 }
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1442
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1534
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212

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

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

◆ set_baserel_partition_constraint()

static void set_baserel_partition_constraint ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2544 of file plancat.c.

2545 {
2546  List *partconstr;
2547 
2548  if (rel->partition_qual) /* already done */
2549  return;
2550 
2551  /*
2552  * Run the partition quals through const-simplification similar to check
2553  * constraints. We skip canonicalize_qual, though, because partition
2554  * quals should be in canonical form already; also, since the qual is in
2555  * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2556  * format and back again.
2557  */
2558  partconstr = RelationGetPartitionQual(relation);
2559  if (partconstr)
2560  {
2561  partconstr = (List *) expression_planner((Expr *) partconstr);
2562  if (rel->relid != 1)
2563  ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2564  rel->partition_qual = partconstr;
2565  }
2566 }
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:280
Expr * expression_planner(Expr *expr)
Definition: planner.c:6407

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

Referenced by get_relation_constraints(), and set_relation_partition_info().

◆ set_baserel_partition_key_exprs()

static void set_baserel_partition_key_exprs ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2476 of file plancat.c.

2478 {
2479  PartitionKey partkey = RelationGetPartitionKey(relation);
2480  int partnatts;
2481  int cnt;
2482  List **partexprs;
2483  ListCell *lc;
2484  Index varno = rel->relid;
2485 
2486  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2487 
2488  /* A partitioned table should have a partition key. */
2489  Assert(partkey != NULL);
2490 
2491  partnatts = partkey->partnatts;
2492  partexprs = (List **) palloc(sizeof(List *) * partnatts);
2493  lc = list_head(partkey->partexprs);
2494 
2495  for (cnt = 0; cnt < partnatts; cnt++)
2496  {
2497  Expr *partexpr;
2498  AttrNumber attno = partkey->partattrs[cnt];
2499 
2500  if (attno != InvalidAttrNumber)
2501  {
2502  /* Single column partition key is stored as a Var node. */
2503  Assert(attno > 0);
2504 
2505  partexpr = (Expr *) makeVar(varno, attno,
2506  partkey->parttypid[cnt],
2507  partkey->parttypmod[cnt],
2508  partkey->parttypcoll[cnt], 0);
2509  }
2510  else
2511  {
2512  if (lc == NULL)
2513  elog(ERROR, "wrong number of partition key expressions");
2514 
2515  /* Re-stamp the expression with given varno. */
2516  partexpr = (Expr *) copyObject(lfirst(lc));
2517  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2518  lc = lnext(partkey->partexprs, lc);
2519  }
2520 
2521  /* Base relations have a single expression per key. */
2522  partexprs[cnt] = list_make1(partexpr);
2523  }
2524 
2525  rel->partexprs = partexprs;
2526 
2527  /*
2528  * A base relation does not have nullable partition key expressions, since
2529  * no outer join is involved. We still allocate an array of empty
2530  * expression lists to keep partition key expression handling code simple.
2531  * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2532  */
2533  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2534 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define copyObject(obj)
Definition: nodes.h:223
#define list_make1(x1)
Definition: pg_list.h:212
Oid * parttypcoll
Definition: partcache.h:47
int32 * parttypmod
Definition: partcache.h:43
List * partexprs
Definition: partcache.h:31
AttrNumber * partattrs
Definition: partcache.h:29

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

Referenced by set_relation_partition_info().

◆ set_relation_partition_info()

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

Definition at line 2339 of file plancat.c.

2341 {
2342  PartitionDesc partdesc;
2343 
2344  /*
2345  * Create the PartitionDirectory infrastructure if we didn't already.
2346  */
2347  if (root->glob->partition_directory == NULL)
2348  {
2349  root->glob->partition_directory =
2351  }
2352 
2353  partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
2354  relation);
2355  rel->part_scheme = find_partition_scheme(root, relation);
2356  Assert(partdesc != NULL && rel->part_scheme != NULL);
2357  rel->boundinfo = partdesc->boundinfo;
2358  rel->nparts = partdesc->nparts;
2359  set_baserel_partition_key_exprs(relation, rel);
2360  set_baserel_partition_constraint(relation, rel);
2361 }
PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool omit_detached)
Definition: partdesc.c:383
PartitionDesc PartitionDirectoryLookup(PartitionDirectory pdir, Relation rel)
Definition: partdesc.c:416
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation relation)
Definition: plancat.c:2369
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2476
PartitionBoundInfo boundinfo
Definition: partdesc.h:38

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

Referenced by get_relation_info().

Variable Documentation

◆ constraint_exclusion

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION

Definition at line 58 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ get_relation_info_hook

get_relation_info_hook_type get_relation_info_hook = NULL

Definition at line 61 of file plancat.c.

Referenced by get_relation_info().