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

2045 {
2046  HeapTuple proctup;
2047  Form_pg_proc procform;
2048 
2049  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2050  if (!HeapTupleIsValid(proctup))
2051  elog(ERROR, "cache lookup failed for function %u", funcid);
2052  procform = (Form_pg_proc) GETSTRUCT(proctup);
2053 
2054  if (OidIsValid(procform->prosupport))
2055  {
2056  SupportRequestCost req;
2057  SupportRequestCost *sresult;
2058 
2059  req.type = T_SupportRequestCost;
2060  req.root = root;
2061  req.funcid = funcid;
2062  req.node = node;
2063 
2064  /* Initialize cost fields so that support function doesn't have to */
2065  req.startup = 0;
2066  req.per_tuple = 0;
2067 
2068  sresult = (SupportRequestCost *)
2069  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2070  PointerGetDatum(&req)));
2071 
2072  if (sresult == &req)
2073  {
2074  /* Success, so accumulate support function's estimate into *cost */
2075  cost->startup += req.startup;
2076  cost->per_tuple += req.per_tuple;
2077  ReleaseSysCache(proctup);
2078  return;
2079  }
2080  }
2081 
2082  /* No support function, or it failed, so rely on procost */
2083  cost->per_tuple += procform->procost * cpu_operator_cost;
2084 
2085  ReleaseSysCache(proctup);
2086 }
#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:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ PROCOID
Definition: syscache.h:79

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

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

◆ build_index_tlist()

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

Definition at line 1839 of file plancat.c.

1841 {
1842  List *tlist = NIL;
1843  Index varno = index->rel->relid;
1844  ListCell *indexpr_item;
1845  int i;
1846 
1847  indexpr_item = list_head(index->indexprs);
1848  for (i = 0; i < index->ncolumns; i++)
1849  {
1850  int indexkey = index->indexkeys[i];
1851  Expr *indexvar;
1852 
1853  if (indexkey != 0)
1854  {
1855  /* simple column */
1856  const FormData_pg_attribute *att_tup;
1857 
1858  if (indexkey < 0)
1859  att_tup = SystemAttributeDefinition(indexkey);
1860  else
1861  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1862 
1863  indexvar = (Expr *) makeVar(varno,
1864  indexkey,
1865  att_tup->atttypid,
1866  att_tup->atttypmod,
1867  att_tup->attcollation,
1868  0);
1869  }
1870  else
1871  {
1872  /* expression column */
1873  if (indexpr_item == NULL)
1874  elog(ERROR, "wrong number of index expressions");
1875  indexvar = (Expr *) lfirst(indexpr_item);
1876  indexpr_item = lnext(index->indexprs, indexpr_item);
1877  }
1878 
1879  tlist = lappend(tlist,
1880  makeTargetEntry(indexvar,
1881  i + 1,
1882  NULL,
1883  false));
1884  }
1885  if (indexpr_item != NULL)
1886  elog(ERROR, "wrong number of index expressions");
1887 
1888  return tlist;
1889 }
unsigned int Index
Definition: c.h:603
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:239
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:338
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c: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 1718 of file plancat.c.

1719 {
1720  List *tlist = NIL;
1721  Index varno = rel->relid;
1722  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1723  Relation relation;
1724  Query *subquery;
1725  Var *var;
1726  ListCell *l;
1727  int attrno,
1728  numattrs;
1729  List *colvars;
1730 
1731  switch (rte->rtekind)
1732  {
1733  case RTE_RELATION:
1734  /* Assume we already have adequate lock */
1735  relation = table_open(rte->relid, NoLock);
1736 
1737  numattrs = RelationGetNumberOfAttributes(relation);
1738  for (attrno = 1; attrno <= numattrs; attrno++)
1739  {
1740  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1741  attrno - 1);
1742 
1743  if (att_tup->attisdropped || att_tup->atthasmissing)
1744  {
1745  /* found a dropped or missing col, so punt */
1746  tlist = NIL;
1747  break;
1748  }
1749 
1750  var = makeVar(varno,
1751  attrno,
1752  att_tup->atttypid,
1753  att_tup->atttypmod,
1754  att_tup->attcollation,
1755  0);
1756 
1757  tlist = lappend(tlist,
1758  makeTargetEntry((Expr *) var,
1759  attrno,
1760  NULL,
1761  false));
1762  }
1763 
1764  table_close(relation, NoLock);
1765  break;
1766 
1767  case RTE_SUBQUERY:
1768  subquery = rte->subquery;
1769  foreach(l, subquery->targetList)
1770  {
1771  TargetEntry *tle = (TargetEntry *) lfirst(l);
1772 
1773  /*
1774  * A resjunk column of the subquery can be reflected as
1775  * resjunk in the physical tlist; we need not punt.
1776  */
1777  var = makeVarFromTargetEntry(varno, tle);
1778 
1779  tlist = lappend(tlist,
1780  makeTargetEntry((Expr *) var,
1781  tle->resno,
1782  NULL,
1783  tle->resjunk));
1784  }
1785  break;
1786 
1787  case RTE_FUNCTION:
1788  case RTE_TABLEFUNC:
1789  case RTE_VALUES:
1790  case RTE_CTE:
1791  case RTE_NAMEDTUPLESTORE:
1792  case RTE_RESULT:
1793  /* Not all of these can have dropped cols, but share code anyway */
1794  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1795  NULL, &colvars);
1796  foreach(l, colvars)
1797  {
1798  var = (Var *) lfirst(l);
1799 
1800  /*
1801  * A non-Var in expandRTE's output means a dropped column;
1802  * must punt.
1803  */
1804  if (!IsA(var, Var))
1805  {
1806  tlist = NIL;
1807  break;
1808  }
1809 
1810  tlist = lappend(tlist,
1811  makeTargetEntry((Expr *) var,
1812  var->varattno,
1813  NULL,
1814  false));
1815  }
1816  break;
1817 
1818  default:
1819  /* caller error */
1820  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1821  (int) rte->rtekind);
1822  break;
1823  }
1824 
1825  return tlist;
1826 }
#define NoLock
Definition: lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:106
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_CTE
Definition: parsenodes.h:1019
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1020
@ RTE_VALUES
Definition: parsenodes.h:1018
@ RTE_SUBQUERY
Definition: parsenodes.h:1014
@ RTE_RESULT
Definition: parsenodes.h:1021
@ RTE_FUNCTION
Definition: parsenodes.h:1016
@ RTE_TABLEFUNC
Definition: parsenodes.h:1017
@ RTE_RELATION
Definition: parsenodes.h:1013
#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:188
Query * subquery
Definition: parsenodes.h:1080
RTEKind rtekind
Definition: parsenodes.h:1032
Index relid
Definition: pathnodes.h:903
AttrNumber resno
Definition: primnodes.h:1897
Definition: primnodes.h:226
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 1013 of file plancat.c.

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

2350 {
2351  PartitionKey partkey = RelationGetPartitionKey(relation);
2352  ListCell *lc;
2353  int partnatts,
2354  i;
2355  PartitionScheme part_scheme;
2356 
2357  /* A partitioned table should have a partition key. */
2358  Assert(partkey != NULL);
2359 
2360  partnatts = partkey->partnatts;
2361 
2362  /* Search for a matching partition scheme and return if found one. */
2363  foreach(lc, root->part_schemes)
2364  {
2365  part_scheme = lfirst(lc);
2366 
2367  /* Match partitioning strategy and number of keys. */
2368  if (partkey->strategy != part_scheme->strategy ||
2369  partnatts != part_scheme->partnatts)
2370  continue;
2371 
2372  /* Match partition key type properties. */
2373  if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2374  sizeof(Oid) * partnatts) != 0 ||
2375  memcmp(partkey->partopcintype, part_scheme->partopcintype,
2376  sizeof(Oid) * partnatts) != 0 ||
2377  memcmp(partkey->partcollation, part_scheme->partcollation,
2378  sizeof(Oid) * partnatts) != 0)
2379  continue;
2380 
2381  /*
2382  * Length and byval information should match when partopcintype
2383  * matches.
2384  */
2385  Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2386  sizeof(int16) * partnatts) == 0);
2387  Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2388  sizeof(bool) * partnatts) == 0);
2389 
2390  /*
2391  * If partopfamily and partopcintype matched, must have the same
2392  * partition comparison functions. Note that we cannot reliably
2393  * Assert the equality of function structs themselves for they might
2394  * be different across PartitionKey's, so just Assert for the function
2395  * OIDs.
2396  */
2397 #ifdef USE_ASSERT_CHECKING
2398  for (i = 0; i < partkey->partnatts; i++)
2399  Assert(partkey->partsupfunc[i].fn_oid ==
2400  part_scheme->partsupfunc[i].fn_oid);
2401 #endif
2402 
2403  /* Found matching partition scheme. */
2404  return part_scheme;
2405  }
2406 
2407  /*
2408  * Did not find matching partition scheme. Create one copying relevant
2409  * information from the relcache. We need to copy the contents of the
2410  * array since the relcache entry may not survive after we have closed the
2411  * relation.
2412  */
2413  part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
2414  part_scheme->strategy = partkey->strategy;
2415  part_scheme->partnatts = partkey->partnatts;
2416 
2417  part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
2418  memcpy(part_scheme->partopfamily, partkey->partopfamily,
2419  sizeof(Oid) * partnatts);
2420 
2421  part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
2422  memcpy(part_scheme->partopcintype, partkey->partopcintype,
2423  sizeof(Oid) * partnatts);
2424 
2425  part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
2426  memcpy(part_scheme->partcollation, partkey->partcollation,
2427  sizeof(Oid) * partnatts);
2428 
2429  part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
2430  memcpy(part_scheme->parttyplen, partkey->parttyplen,
2431  sizeof(int16) * partnatts);
2432 
2433  part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
2434  memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2435  sizeof(bool) * partnatts);
2436 
2437  part_scheme->partsupfunc = (FmgrInfo *)
2438  palloc(sizeof(FmgrInfo) * partnatts);
2439  for (i = 0; i < partnatts; i++)
2440  fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2442 
2443  /* Add the partitioning scheme to PlannerInfo. */
2444  root->part_schemes = lappend(root->part_schemes, part_scheme);
2445 
2446  return part_scheme;
2447 }
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:1257
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void * palloc(Size size)
Definition: mcxt.c:1226
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 1981 of file plancat.c.

1989 {
1990  RegProcedure prosupport = get_func_support(funcid);
1992  SupportRequestSelectivity *sresult;
1993 
1994  /*
1995  * If no support function is provided, use our historical default
1996  * estimate, 0.3333333. This seems a pretty unprincipled choice, but
1997  * Postgres has been using that estimate for function calls since 1992.
1998  * The hoariness of this behavior suggests that we should not be in too
1999  * much hurry to use another value.
2000  */
2001  if (!prosupport)
2002  return (Selectivity) 0.3333333;
2003 
2004  req.type = T_SupportRequestSelectivity;
2005  req.root = root;
2006  req.funcid = funcid;
2007  req.args = args;
2008  req.inputcollid = inputcollid;
2009  req.is_join = is_join;
2010  req.varRelid = varRelid;
2011  req.jointype = jointype;
2012  req.sjinfo = sjinfo;
2013  req.selectivity = -1; /* to catch failure to set the value */
2014 
2015  sresult = (SupportRequestSelectivity *)
2016  DatumGetPointer(OidFunctionCall1(prosupport,
2017  PointerGetDatum(&req)));
2018 
2019  /* If support function fails, use default */
2020  if (sresult != &req)
2021  return (Selectivity) 0.3333333;
2022 
2023  if (req.selectivity < 0.0 || req.selectivity > 1.0)
2024  elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2025 
2026  return (Selectivity) req.selectivity;
2027 }
regproc RegProcedure
Definition: c.h:639
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1862
double Selectivity
Definition: nodes.h:261
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 2271 of file plancat.c.

2273 {
2274  Bitmapset *dependentCols = NULL;
2275  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2276  Relation relation;
2277  TupleDesc tupdesc;
2278  TupleConstr *constr;
2279 
2280  /* Assume we already have adequate lock */
2281  relation = table_open(rte->relid, NoLock);
2282 
2283  tupdesc = RelationGetDescr(relation);
2284  constr = tupdesc->constr;
2285 
2286  if (constr && constr->has_generated_stored)
2287  {
2288  for (int i = 0; i < constr->num_defval; i++)
2289  {
2290  AttrDefault *defval = &constr->defval[i];
2291  Node *expr;
2292  Bitmapset *attrs_used = NULL;
2293 
2294  /* skip if not generated column */
2295  if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
2296  continue;
2297 
2298  /* identify columns this generated column depends on */
2299  expr = stringToNode(defval->adbin);
2300  pull_varattnos(expr, 1, &attrs_used);
2301 
2302  if (bms_overlap(target_cols, attrs_used))
2303  dependentCols = bms_add_member(dependentCols,
2305  }
2306  }
2307 
2308  table_close(relation, NoLock);
2309 
2310  return dependentCols;
2311 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:527
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 2104 of file plancat.c.

2105 {
2106  HeapTuple proctup;
2107  Form_pg_proc procform;
2108  double result;
2109 
2110  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2111  if (!HeapTupleIsValid(proctup))
2112  elog(ERROR, "cache lookup failed for function %u", funcid);
2113  procform = (Form_pg_proc) GETSTRUCT(proctup);
2114 
2115  Assert(procform->proretset); /* else caller error */
2116 
2117  if (OidIsValid(procform->prosupport))
2118  {
2119  SupportRequestRows req;
2120  SupportRequestRows *sresult;
2121 
2122  req.type = T_SupportRequestRows;
2123  req.root = root;
2124  req.funcid = funcid;
2125  req.node = node;
2126 
2127  req.rows = 0; /* just for sanity */
2128 
2129  sresult = (SupportRequestRows *)
2130  DatumGetPointer(OidFunctionCall1(procform->prosupport,
2131  PointerGetDatum(&req)));
2132 
2133  if (sresult == &req)
2134  {
2135  /* Success */
2136  ReleaseSysCache(proctup);
2137  return req.rows;
2138  }
2139  }
2140 
2141  /* No support function, or it failed, so rely on prorows */
2142  result = procform->prorows;
2143 
2144  ReleaseSysCache(proctup);
2145 
2146  return result;
2147 }
struct PlannerInfo * root
Definition: supportnodes.h:163

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

Referenced by expression_returns_set_rows().

◆ get_rel_data_width()

int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)

Definition at line 1138 of file plancat.c.

1139 {
1140  int32 tuple_width = 0;
1141  int i;
1142 
1143  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1144  {
1145  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1146  int32 item_width;
1147 
1148  if (att->attisdropped)
1149  continue;
1150 
1151  /* use previously cached data, if any */
1152  if (attr_widths != NULL && attr_widths[i] > 0)
1153  {
1154  tuple_width += attr_widths[i];
1155  continue;
1156  }
1157 
1158  /* This should match set_rel_width() in costsize.c */
1159  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1160  if (item_width <= 0)
1161  {
1162  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1163  Assert(item_width > 0);
1164  }
1165  if (attr_widths != NULL)
1166  attr_widths[i] = item_width;
1167  tuple_width += item_width;
1168  }
1169 
1170  return tuple_width;
1171 }
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3140
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2560
#define RelationGetRelid(relation)
Definition: rel.h:504

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

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

◆ get_relation_constraints()

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

Definition at line 1220 of file plancat.c.

1225 {
1226  List *result = NIL;
1227  Index varno = rel->relid;
1228  Relation relation;
1229  TupleConstr *constr;
1230 
1231  /*
1232  * We assume the relation has already been safely locked.
1233  */
1234  relation = table_open(relationObjectId, NoLock);
1235 
1236  constr = relation->rd_att->constr;
1237  if (constr != NULL)
1238  {
1239  int num_check = constr->num_check;
1240  int i;
1241 
1242  for (i = 0; i < num_check; i++)
1243  {
1244  Node *cexpr;
1245 
1246  /*
1247  * If this constraint hasn't been fully validated yet, we must
1248  * ignore it here. Also ignore if NO INHERIT and we weren't told
1249  * that that's safe.
1250  */
1251  if (!constr->check[i].ccvalid)
1252  continue;
1253  if (constr->check[i].ccnoinherit && !include_noinherit)
1254  continue;
1255 
1256  cexpr = stringToNode(constr->check[i].ccbin);
1257 
1258  /*
1259  * Run each expression through const-simplification and
1260  * canonicalization. This is not just an optimization, but is
1261  * necessary, because we will be comparing it to
1262  * similarly-processed qual clauses, and may fail to detect valid
1263  * matches without this. This must match the processing done to
1264  * qual clauses in preprocess_expression()! (We can skip the
1265  * stuff involving subqueries, however, since we don't allow any
1266  * in check constraints.)
1267  */
1268  cexpr = eval_const_expressions(root, cexpr);
1269 
1270  cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1271 
1272  /* Fix Vars to have the desired varno */
1273  if (varno != 1)
1274  ChangeVarNodes(cexpr, 1, varno, 0);
1275 
1276  /*
1277  * Finally, convert to implicit-AND format (that is, a List) and
1278  * append the resulting item(s) to our output list.
1279  */
1280  result = list_concat(result,
1281  make_ands_implicit((Expr *) cexpr));
1282  }
1283 
1284  /* Add NOT NULL constraints in expression form, if requested */
1285  if (include_notnull && constr->has_not_null)
1286  {
1287  int natts = relation->rd_att->natts;
1288 
1289  for (i = 1; i <= natts; i++)
1290  {
1291  Form_pg_attribute att = TupleDescAttr(relation->rd_att, i - 1);
1292 
1293  if (att->attnotnull && !att->attisdropped)
1294  {
1295  NullTest *ntest = makeNode(NullTest);
1296 
1297  ntest->arg = (Expr *) makeVar(varno,
1298  i,
1299  att->atttypid,
1300  att->atttypmod,
1301  att->attcollation,
1302  0);
1303  ntest->nulltesttype = IS_NOT_NULL;
1304 
1305  /*
1306  * argisrow=false is correct even for a composite column,
1307  * because attnotnull does not represent a SQL-spec IS NOT
1308  * NULL test in such a case, just IS DISTINCT FROM NULL.
1309  */
1310  ntest->argisrow = false;
1311  ntest->location = -1;
1312  result = lappend(result, ntest);
1313  }
1314  }
1315  }
1316  }
1317 
1318  /*
1319  * Add partitioning constraints, if requested.
1320  */
1321  if (include_partition && relation->rd_rel->relispartition)
1322  {
1323  /* make sure rel->partition_qual is set */
1324  set_baserel_partition_constraint(relation, rel);
1325  result = list_concat(result, rel->partition_qual);
1326  }
1327 
1328  table_close(relation, NoLock);
1329 
1330  return result;
1331 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2171
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:722
#define makeNode(_type_)
Definition: nodes.h:176
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2524
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:294
@ IS_NOT_NULL
Definition: primnodes.h:1686
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:1693
int location
Definition: primnodes.h:1696
Expr * arg
Definition: primnodes.h:1692
List * partition_qual
Definition: pathnodes.h:1006
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 1180 of file plancat.c.

1181 {
1182  int32 result;
1183  Relation relation;
1184 
1185  /* As above, assume relation is already locked */
1186  relation = table_open(relid, NoLock);
1187 
1188  result = get_rel_data_width(relation, attr_widths);
1189 
1190  table_close(relation, NoLock);
1191 
1192  return result;
1193 }

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

552 {
553  List *rtable = root->parse->rtable;
554  List *cachedfkeys;
555  ListCell *lc;
556 
557  /*
558  * If it's not a baserel, we don't care about its FKs. Also, if the query
559  * references only a single relation, we can skip the lookup since no FKs
560  * could satisfy the requirements below.
561  */
562  if (rel->reloptkind != RELOPT_BASEREL ||
563  list_length(rtable) < 2)
564  return;
565 
566  /*
567  * If it's the parent of an inheritance tree, ignore its FKs. We could
568  * make useful FK-based deductions if we found that all members of the
569  * inheritance tree have equivalent FK constraints, but detecting that
570  * would require code that hasn't been written.
571  */
572  if (inhparent)
573  return;
574 
575  /*
576  * Extract data about relation's FKs from the relcache. Note that this
577  * list belongs to the relcache and might disappear in a cache flush, so
578  * we must not do any further catalog access within this function.
579  */
580  cachedfkeys = RelationGetFKeyList(relation);
581 
582  /*
583  * Figure out which FKs are of interest for this query, and create
584  * ForeignKeyOptInfos for them. We want only FKs that reference some
585  * other RTE of the current query. In queries containing self-joins,
586  * there might be more than one other RTE for a referenced table, and we
587  * should make a ForeignKeyOptInfo for each occurrence.
588  *
589  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
590  * too hard to identify those here, so we might end up making some useless
591  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
592  * them again.
593  */
594  foreach(lc, cachedfkeys)
595  {
596  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
597  Index rti;
598  ListCell *lc2;
599 
600  /* conrelid should always be that of the table we're considering */
601  Assert(cachedfk->conrelid == RelationGetRelid(relation));
602 
603  /* Scan to find other RTEs matching confrelid */
604  rti = 0;
605  foreach(lc2, rtable)
606  {
607  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
608  ForeignKeyOptInfo *info;
609 
610  rti++;
611  /* Ignore if not the correct table */
612  if (rte->rtekind != RTE_RELATION ||
613  rte->relid != cachedfk->confrelid)
614  continue;
615  /* Ignore if it's an inheritance parent; doesn't really match */
616  if (rte->inh)
617  continue;
618  /* Ignore self-referential FKs; we only care about joins */
619  if (rti == rel->relid)
620  continue;
621 
622  /* OK, let's make an entry */
623  info = makeNode(ForeignKeyOptInfo);
624  info->con_relid = rel->relid;
625  info->ref_relid = rti;
626  info->nkeys = cachedfk->nkeys;
627  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
628  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
629  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
630  /* zero out fields to be filled by match_foreign_keys_to_quals */
631  info->nmatched_ec = 0;
632  info->nconst_ec = 0;
633  info->nmatched_rcols = 0;
634  info->nmatched_ri = 0;
635  memset(info->eclass, 0, sizeof(info->eclass));
636  memset(info->fk_eclass_member, 0, sizeof(info->fk_eclass_member));
637  memset(info->rinfos, 0, sizeof(info->rinfos));
638 
639  root->fkey_list = lappend(root->fkey_list, info);
640  }
641  }
642 }
@ 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:4631
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1235
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:1239
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1237
List * fkey_list
Definition: pathnodes.h:379
Query * parse
Definition: pathnodes.h:199
List * rtable
Definition: parsenodes.h:174
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  /*
167  * Estimate relation size --- unless it's an inheritance parent, in which
168  * case the size we want is not the rel's own size but the size of its
169  * inheritance tree. That will be computed in set_append_rel_size().
170  */
171  if (!inhparent)
172  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
173  &rel->pages, &rel->tuples, &rel->allvisfrac);
174 
175  /* Retrieve the parallel_workers reloption, or -1 if not set. */
177 
178  /*
179  * Make list of indexes. Ignore indexes on system catalogs if told to.
180  * Don't bother with indexes from traditional inheritance parents. For
181  * partitioned tables, we need a list of at least unique indexes as these
182  * serve as unique proofs for certain planner optimizations. However,
183  * let's not discriminate here and just record all partitioned indexes
184  * whether they're unique indexes or not.
185  */
186  if ((inhparent && relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
187  || (IgnoreSystemIndexes && IsSystemRelation(relation)))
188  hasindex = false;
189  else
190  hasindex = relation->rd_rel->relhasindex;
191 
192  if (hasindex)
193  {
194  List *indexoidlist;
195  LOCKMODE lmode;
196  ListCell *l;
197 
198  indexoidlist = RelationGetIndexList(relation);
199 
200  /*
201  * For each index, we get the same type of lock that the executor will
202  * need, and do not release it. This saves a couple of trips to the
203  * shared lock manager while not creating any real loss of
204  * concurrency, because no schema changes could be happening on the
205  * index while we hold lock on the parent rel, and no lock type used
206  * for queries blocks any other kind of index operation.
207  */
208  lmode = root->simple_rte_array[varno]->rellockmode;
209 
210  foreach(l, indexoidlist)
211  {
212  Oid indexoid = lfirst_oid(l);
213  Relation indexRelation;
215  IndexAmRoutine *amroutine;
216  IndexOptInfo *info;
217  int ncolumns,
218  nkeycolumns;
219  int i;
220 
221  /*
222  * Extract info from the relation descriptor for the index.
223  */
224  indexRelation = index_open(indexoid, lmode);
225  index = indexRelation->rd_index;
226 
227  /*
228  * Ignore invalid indexes, since they can't safely be used for
229  * queries. Note that this is OK because the data structure we
230  * are constructing is only used by the planner --- the executor
231  * still needs to insert into "invalid" indexes, if they're marked
232  * indisready.
233  */
234  if (!index->indisvalid)
235  {
236  index_close(indexRelation, NoLock);
237  continue;
238  }
239 
240  /*
241  * If the index is valid, but cannot yet be used, ignore it; but
242  * mark the plan we are generating as transient. See
243  * src/backend/access/heap/README.HOT for discussion.
244  */
245  if (index->indcheckxmin &&
248  {
249  root->glob->transientPlan = true;
250  index_close(indexRelation, NoLock);
251  continue;
252  }
253 
254  info = makeNode(IndexOptInfo);
255 
256  info->indexoid = index->indexrelid;
257  info->reltablespace =
258  RelationGetForm(indexRelation)->reltablespace;
259  info->rel = rel;
260  info->ncolumns = ncolumns = index->indnatts;
261  info->nkeycolumns = nkeycolumns = index->indnkeyatts;
262 
263  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
264  info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
265  info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
266  info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
267  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
268 
269  for (i = 0; i < ncolumns; i++)
270  {
271  info->indexkeys[i] = index->indkey.values[i];
272  info->canreturn[i] = index_can_return(indexRelation, i + 1);
273  }
274 
275  for (i = 0; i < nkeycolumns; i++)
276  {
277  info->opfamily[i] = indexRelation->rd_opfamily[i];
278  info->opcintype[i] = indexRelation->rd_opcintype[i];
279  info->indexcollations[i] = indexRelation->rd_indcollation[i];
280  }
281 
282  info->relam = indexRelation->rd_rel->relam;
283 
284  /*
285  * We don't have an AM for partitioned indexes, so we'll just
286  * NULLify the AM related fields for those.
287  */
288  if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
289  {
290  /* We copy just the fields we need, not all of rd_indam */
291  amroutine = indexRelation->rd_indam;
292  info->amcanorderbyop = amroutine->amcanorderbyop;
293  info->amoptionalkey = amroutine->amoptionalkey;
294  info->amsearcharray = amroutine->amsearcharray;
295  info->amsearchnulls = amroutine->amsearchnulls;
296  info->amcanparallel = amroutine->amcanparallel;
297  info->amhasgettuple = (amroutine->amgettuple != NULL);
298  info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
299  relation->rd_tableam->scan_bitmap_next_block != NULL;
300  info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
301  amroutine->amrestrpos != NULL);
302  info->amcostestimate = amroutine->amcostestimate;
303  Assert(info->amcostestimate != NULL);
304 
305  /* Fetch index opclass options */
306  info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
307 
308  /*
309  * Fetch the ordering information for the index, if any.
310  */
311  if (info->relam == BTREE_AM_OID)
312  {
313  /*
314  * If it's a btree index, we can use its opfamily OIDs
315  * directly as the sort ordering opfamily OIDs.
316  */
317  Assert(amroutine->amcanorder);
318 
319  info->sortopfamily = info->opfamily;
320  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
321  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
322 
323  for (i = 0; i < nkeycolumns; i++)
324  {
325  int16 opt = indexRelation->rd_indoption[i];
326 
327  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
328  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
329  }
330  }
331  else if (amroutine->amcanorder)
332  {
333  /*
334  * Otherwise, identify the corresponding btree opfamilies
335  * by trying to map this index's "<" operators into btree.
336  * Since "<" uniquely defines the behavior of a sort
337  * order, this is a sufficient test.
338  *
339  * XXX This method is rather slow and also requires the
340  * undesirable assumption that the other index AM numbers
341  * its strategies the same as btree. It'd be better to
342  * have a way to explicitly declare the corresponding
343  * btree opfamily for each opfamily of the other index
344  * type. But given the lack of current or foreseeable
345  * amcanorder index types, it's not worth expending more
346  * effort on now.
347  */
348  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
349  info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
350  info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
351 
352  for (i = 0; i < nkeycolumns; i++)
353  {
354  int16 opt = indexRelation->rd_indoption[i];
355  Oid ltopr;
356  Oid btopfamily;
357  Oid btopcintype;
358  int16 btstrategy;
359 
360  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
361  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
362 
363  ltopr = get_opfamily_member(info->opfamily[i],
364  info->opcintype[i],
365  info->opcintype[i],
367  if (OidIsValid(ltopr) &&
369  &btopfamily,
370  &btopcintype,
371  &btstrategy) &&
372  btopcintype == info->opcintype[i] &&
373  btstrategy == BTLessStrategyNumber)
374  {
375  /* Successful mapping */
376  info->sortopfamily[i] = btopfamily;
377  }
378  else
379  {
380  /* Fail ... quietly treat index as unordered */
381  info->sortopfamily = NULL;
382  info->reverse_sort = NULL;
383  info->nulls_first = NULL;
384  break;
385  }
386  }
387  }
388  else
389  {
390  info->sortopfamily = NULL;
391  info->reverse_sort = NULL;
392  info->nulls_first = NULL;
393  }
394  }
395  else
396  {
397  info->amcanorderbyop = false;
398  info->amoptionalkey = false;
399  info->amsearcharray = false;
400  info->amsearchnulls = false;
401  info->amcanparallel = false;
402  info->amhasgettuple = false;
403  info->amhasgetbitmap = false;
404  info->amcanmarkpos = false;
405  info->amcostestimate = NULL;
406 
407  info->sortopfamily = NULL;
408  info->reverse_sort = NULL;
409  info->nulls_first = NULL;
410  }
411 
412  /*
413  * Fetch the index expressions and predicate, if any. We must
414  * modify the copies we obtain from the relcache to have the
415  * correct varno for the parent relation, so that they match up
416  * correctly against qual clauses.
417  */
418  info->indexprs = RelationGetIndexExpressions(indexRelation);
419  info->indpred = RelationGetIndexPredicate(indexRelation);
420  if (info->indexprs && varno != 1)
421  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
422  if (info->indpred && varno != 1)
423  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
424 
425  /* Build targetlist using the completed indexprs data */
426  info->indextlist = build_index_tlist(root, info, relation);
427 
428  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
429  info->predOK = false; /* set later, in indxpath.c */
430  info->unique = index->indisunique;
431  info->immediate = index->indimmediate;
432  info->hypothetical = false;
433 
434  /*
435  * Estimate the index size. If it's not a partial index, we lock
436  * the number-of-tuples estimate to equal the parent table; if it
437  * is partial then we have to use the same methods as we would for
438  * a table, except we can be sure that the index is not larger
439  * than the table. We must ignore partitioned indexes here as
440  * there are not physical indexes.
441  */
442  if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
443  {
444  if (info->indpred == NIL)
445  {
446  info->pages = RelationGetNumberOfBlocks(indexRelation);
447  info->tuples = rel->tuples;
448  }
449  else
450  {
451  double allvisfrac; /* dummy */
452 
453  estimate_rel_size(indexRelation, NULL,
454  &info->pages, &info->tuples, &allvisfrac);
455  if (info->tuples > rel->tuples)
456  info->tuples = rel->tuples;
457  }
458 
459  if (info->relam == BTREE_AM_OID)
460  {
461  /*
462  * For btrees, get tree height while we have the index
463  * open
464  */
465  info->tree_height = _bt_getrootheight(indexRelation);
466  }
467  else
468  {
469  /* For other index types, just set it to "unknown" for now */
470  info->tree_height = -1;
471  }
472  }
473  else
474  {
475  /* Zero these out for partitioned indexes */
476  info->pages = 0;
477  info->tuples = 0.0;
478  info->tree_height = -1;
479  }
480 
481  index_close(indexRelation, NoLock);
482 
483  /*
484  * We've historically used lcons() here. It'd make more sense to
485  * use lappend(), but that causes the planner to change behavior
486  * in cases where two indexes seem equally attractive. For now,
487  * stick with lcons() --- few tables should have so many indexes
488  * that the O(N^2) behavior of lcons() is really a problem.
489  */
490  indexinfos = lcons(info, indexinfos);
491  }
492 
493  list_free(indexoidlist);
494  }
495 
496  rel->indexlist = indexinfos;
497 
498  rel->statlist = get_relation_statistics(rel, relation);
499 
500  /* Grab foreign-table info using the relcache, while we have it */
501  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
502  {
504  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
505  }
506  else
507  {
508  rel->serverid = InvalidOid;
509  rel->fdwroutine = NULL;
510  }
511 
512  /* Collect info about relation's foreign keys, if relevant */
513  get_relation_foreign_keys(root, rel, relation, inhparent);
514 
515  /* Collect info about functions implemented by the rel's table AM. */
516  if (relation->rd_tableam &&
517  relation->rd_tableam->scan_set_tidrange != NULL &&
518  relation->rd_tableam->scan_getnextslot_tidrange != NULL)
520 
521  /*
522  * Collect info about relation's partitioning scheme, if any. Only
523  * inheritance parents may be partitioned.
524  */
525  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
526  set_relation_partition_info(root, rel, relation);
527 
528  table_close(relation, NoLock);
529 
530  /*
531  * Allow a plugin to editorialize on the info we obtained from the
532  * catalogs. Actions might include altering the assumed relation size,
533  * removing an index, or adding a hypothetical index to the indexlist.
534  */
536  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
537 }
bool IsSystemRelation(Relation relation)
Definition: catalog.c:75
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ereport(elevel,...)
Definition: elog.h:149
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:429
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:342
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:309
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:739
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void list_free(List *list)
Definition: list.c:1545
List * lcons(void *datum, List *list)
Definition: list.c:494
int LOCKMODE
Definition: lockdefs.h:26
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:206
bool IgnoreSystemIndexes
Definition: miscinit.c:80
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:675
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:1013
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:550
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:1839
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1423
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:2319
#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:618
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4740
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5109
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition: relcache.c:5874
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4996
TransactionId TransactionXmin
Definition: snapmgr.c:104
#define BTLessStrategyNumber
Definition: stratnum.h:29
HeapTupleHeader t_data
Definition: htup.h:68
amrestrpos_function amrestrpos
Definition: amapi.h:279
amcostestimate_function amcostestimate
Definition: amapi.h:267
bool amcanorderbyop
Definition: amapi.h:222
bool amoptionalkey
Definition: amapi.h:230
amgettuple_function amgettuple
Definition: amapi.h:275
amgetbitmap_function amgetbitmap
Definition: amapi.h:276
bool amsearcharray
Definition: amapi.h:232
ammarkpos_function ammarkpos
Definition: amapi.h:278
bool amcanparallel
Definition: amapi.h:242
bool amcanorder
Definition: amapi.h:220
bool amsearchnulls
Definition: amapi.h:234
bool amcanparallel
Definition: pathnodes.h:1183
bool amoptionalkey
Definition: pathnodes.h:1176
Oid reltablespace
Definition: pathnodes.h:1098
bool amcanmarkpos
Definition: pathnodes.h:1185
List * indrestrictinfo
Definition: pathnodes.h:1160
void(* amcostestimate)() pg_node_attr(read_write_ignore)
Definition: pathnodes.h:1188
bool amhasgettuple
Definition: pathnodes.h:1180
bool amcanorderbyop
Definition: pathnodes.h:1175
bool hypothetical
Definition: pathnodes.h:1169
List * indpred
Definition: pathnodes.h:1150
Cardinality tuples
Definition: pathnodes.h:1108
bool amsearcharray
Definition: pathnodes.h:1177
BlockNumber pages
Definition: pathnodes.h:1106
bool amsearchnulls
Definition: pathnodes.h:1178
bool amhasgetbitmap
Definition: pathnodes.h:1182
List * indextlist
Definition: pathnodes.h:1153
bool immediate
Definition: pathnodes.h:1167
bool transientPlan
Definition: pathnodes.h:147
PlannerGlobal * glob
Definition: pathnodes.h:202
uint32 amflags
Definition: pathnodes.h:937
List * statlist
Definition: pathnodes.h:925
Cardinality tuples
Definition: pathnodes.h:928
BlockNumber pages
Definition: pathnodes.h:927
List * indexlist
Definition: pathnodes.h:923
Oid reltablespace
Definition: pathnodes.h:905
Oid serverid
Definition: pathnodes.h:943
int rel_parallel_workers
Definition: pathnodes.h:935
AttrNumber max_attr
Definition: pathnodes.h:911
double allvisfrac
Definition: pathnodes.h:929
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
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
bool RecoveryInProgress(void)
Definition: xlog.c:5948

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

Referenced by build_simple_rel().

◆ get_relation_statistics()

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

Definition at line 1423 of file plancat.c.

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

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

Referenced by get_relation_info().

◆ get_relation_statistics_worker()

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

Definition at line 1340 of file plancat.c.

1343 {
1344  Form_pg_statistic_ext_data dataForm;
1345  HeapTuple dtup;
1346 
1348  ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1349  if (!HeapTupleIsValid(dtup))
1350  return;
1351 
1352  dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
1353 
1354  /* add one StatisticExtInfo for each kind built */
1355  if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1356  {
1358 
1359  info->statOid = statOid;
1360  info->inherit = dataForm->stxdinherit;
1361  info->rel = rel;
1362  info->kind = STATS_EXT_NDISTINCT;
1363  info->keys = bms_copy(keys);
1364  info->exprs = exprs;
1365 
1366  *stainfos = lappend(*stainfos, info);
1367  }
1368 
1369  if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1370  {
1372 
1373  info->statOid = statOid;
1374  info->inherit = dataForm->stxdinherit;
1375  info->rel = rel;
1376  info->kind = STATS_EXT_DEPENDENCIES;
1377  info->keys = bms_copy(keys);
1378  info->exprs = exprs;
1379 
1380  *stainfos = lappend(*stainfos, info);
1381  }
1382 
1383  if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1384  {
1386 
1387  info->statOid = statOid;
1388  info->inherit = dataForm->stxdinherit;
1389  info->rel = rel;
1390  info->kind = STATS_EXT_MCV;
1391  info->keys = bms_copy(keys);
1392  info->exprs = exprs;
1393 
1394  *stainfos = lappend(*stainfos, info);
1395  }
1396 
1397  if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
1398  {
1400 
1401  info->statOid = statOid;
1402  info->inherit = dataForm->stxdinherit;
1403  info->rel = rel;
1404  info->kind = STATS_EXT_EXPRESSIONS;
1405  info->keys = bms_copy(keys);
1406  info->exprs = exprs;
1407 
1408  *stainfos = lappend(*stainfos, info);
1409  }
1410 
1411  ReleaseSysCache(dtup);
1412 }
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:80
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:1268
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:831
@ STATEXTDATASTXOID
Definition: syscache.h:94

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

Referenced by get_relation_statistics().

◆ has_row_triggers()

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

Definition at line 2194 of file plancat.c.

2195 {
2196  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2197  Relation relation;
2198  TriggerDesc *trigDesc;
2199  bool result = false;
2200 
2201  /* Assume we already have adequate lock */
2202  relation = table_open(rte->relid, NoLock);
2203 
2204  trigDesc = relation->trigdesc;
2205  switch (event)
2206  {
2207  case CMD_INSERT:
2208  if (trigDesc &&
2209  (trigDesc->trig_insert_after_row ||
2210  trigDesc->trig_insert_before_row))
2211  result = true;
2212  break;
2213  case CMD_UPDATE:
2214  if (trigDesc &&
2215  (trigDesc->trig_update_after_row ||
2216  trigDesc->trig_update_before_row))
2217  result = true;
2218  break;
2219  case CMD_DELETE:
2220  if (trigDesc &&
2221  (trigDesc->trig_delete_after_row ||
2222  trigDesc->trig_delete_before_row))
2223  result = true;
2224  break;
2225  /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2226  case CMD_MERGE:
2227  result = false;
2228  break;
2229  default:
2230  elog(ERROR, "unrecognized CmdType: %d", (int) event);
2231  break;
2232  }
2233 
2234  table_close(relation, NoLock);
2235  return result;
2236 }
@ CMD_MERGE
Definition: nodes.h:280
@ CMD_INSERT
Definition: nodes.h:278
@ CMD_DELETE
Definition: nodes.h:279
@ CMD_UPDATE
Definition: nodes.h:277
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 2244 of file plancat.c.

2245 {
2246  RangeTblEntry *rte = planner_rt_fetch(rti, root);
2247  Relation relation;
2248  TupleDesc tupdesc;
2249  bool result = false;
2250 
2251  /* Assume we already have adequate lock */
2252  relation = table_open(rte->relid, NoLock);
2253 
2254  tupdesc = RelationGetDescr(relation);
2255  result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2256 
2257  table_close(relation, NoLock);
2258 
2259  return result;
2260 }

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

2163 {
2164  ListCell *ilist;
2165 
2166  foreach(ilist, rel->indexlist)
2167  {
2168  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2169 
2170  /*
2171  * Note: ignore partial indexes, since they don't allow us to conclude
2172  * that all attr values are distinct, *unless* they are marked predOK
2173  * which means we know the index's predicate is satisfied by the
2174  * query. We don't take any interest in expressional indexes either.
2175  * Also, a multicolumn unique index doesn't allow us to conclude that
2176  * just the specified attr is unique.
2177  */
2178  if (index->unique &&
2179  index->nkeycolumns == 1 &&
2180  index->indexkeys[0] == attno &&
2181  (index->indpred == NIL || index->predOK))
2182  return true;
2183  }
2184  return false;
2185 }

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 665 of file plancat.c.

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

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

933 {
934  AttrNumber natt;
935  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
936  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
937  int nplain = 0; /* # plain attrs observed */
938 
939  /*
940  * If inference specification element lacks collation/opclass, then no
941  * need to check for exact match.
942  */
943  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
944  return true;
945 
946  /*
947  * Lookup opfamily and input type, for matching indexes
948  */
949  if (elem->inferopclass)
950  {
951  inferopfamily = get_opclass_family(elem->inferopclass);
952  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
953  }
954 
955  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
956  {
957  Oid opfamily = idxRel->rd_opfamily[natt - 1];
958  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
959  Oid collation = idxRel->rd_indcollation[natt - 1];
960  int attno = idxRel->rd_index->indkey.values[natt - 1];
961 
962  if (attno != 0)
963  nplain++;
964 
965  if (elem->inferopclass != InvalidOid &&
966  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
967  {
968  /* Attribute needed to match opclass, but didn't */
969  continue;
970  }
971 
972  if (elem->infercollid != InvalidOid &&
973  elem->infercollid != collation)
974  {
975  /* Attribute needed to match collation, but didn't */
976  continue;
977  }
978 
979  /* If one matching index att found, good enough -- return true */
980  if (IsA(elem->expr, Var))
981  {
982  if (((Var *) elem->expr)->varattno == attno)
983  return true;
984  }
985  else if (attno == 0)
986  {
987  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
988 
989  /*
990  * Note that unlike routines like match_index_to_operand() we
991  * don't need to care about RelabelType. Neither the index
992  * definition nor the inference clause should contain them.
993  */
994  if (equal(elem->expr, nattExpr))
995  return true;
996  }
997  }
998 
999  return false;
1000 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1216
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1194
static void * list_nth(const List *list, int n)
Definition: pg_list.h: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 1940 of file plancat.c.

1946 {
1947  RegProcedure oprjoin = get_oprjoin(operatorid);
1948  float8 result;
1949 
1950  /*
1951  * if the oprjoin procedure is missing for whatever reason, use a
1952  * selectivity of 0.5
1953  */
1954  if (!oprjoin)
1955  return (Selectivity) 0.5;
1956 
1957  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1958  inputcollid,
1959  PointerGetDatum(root),
1960  ObjectIdGetDatum(operatorid),
1962  Int16GetDatum(jointype),
1963  PointerGetDatum(sjinfo)));
1964 
1965  if (result < 0.0 || result > 1.0)
1966  elog(ERROR, "invalid join selectivity: %f", result);
1967 
1968  return (Selectivity) result;
1969 }
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:1436
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1585
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 1529 of file plancat.c.

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

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

Referenced by set_append_rel_size(), and set_rel_size().

◆ restriction_selectivity()

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

Definition at line 1901 of file plancat.c.

1906 {
1907  RegProcedure oprrest = get_oprrest(operatorid);
1908  float8 result;
1909 
1910  /*
1911  * if the oprrest procedure is missing for whatever reason, use a
1912  * selectivity of 0.5
1913  */
1914  if (!oprrest)
1915  return (Selectivity) 0.5;
1916 
1917  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1918  inputcollid,
1919  PointerGetDatum(root),
1920  ObjectIdGetDatum(operatorid),
1922  Int32GetDatum(varRelid)));
1923 
1924  if (result < 0.0 || result > 1.0)
1925  elog(ERROR, "invalid restriction selectivity: %f", result);
1926 
1927  return (Selectivity) result;
1928 }
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1425
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1561
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 2524 of file plancat.c.

2525 {
2526  List *partconstr;
2527 
2528  if (rel->partition_qual) /* already done */
2529  return;
2530 
2531  /*
2532  * Run the partition quals through const-simplification similar to check
2533  * constraints. We skip canonicalize_qual, though, because partition
2534  * quals should be in canonical form already; also, since the qual is in
2535  * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2536  * format and back again.
2537  */
2538  partconstr = RelationGetPartitionQual(relation);
2539  if (partconstr)
2540  {
2541  partconstr = (List *) expression_planner((Expr *) partconstr);
2542  if (rel->relid != 1)
2543  ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2544  rel->partition_qual = partconstr;
2545  }
2546 }
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:280
Expr * expression_planner(Expr *expr)
Definition: planner.c:6488

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

2458 {
2459  PartitionKey partkey = RelationGetPartitionKey(relation);
2460  int partnatts;
2461  int cnt;
2462  List **partexprs;
2463  ListCell *lc;
2464  Index varno = rel->relid;
2465 
2466  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2467 
2468  /* A partitioned table should have a partition key. */
2469  Assert(partkey != NULL);
2470 
2471  partnatts = partkey->partnatts;
2472  partexprs = (List **) palloc(sizeof(List *) * partnatts);
2473  lc = list_head(partkey->partexprs);
2474 
2475  for (cnt = 0; cnt < partnatts; cnt++)
2476  {
2477  Expr *partexpr;
2478  AttrNumber attno = partkey->partattrs[cnt];
2479 
2480  if (attno != InvalidAttrNumber)
2481  {
2482  /* Single column partition key is stored as a Var node. */
2483  Assert(attno > 0);
2484 
2485  partexpr = (Expr *) makeVar(varno, attno,
2486  partkey->parttypid[cnt],
2487  partkey->parttypmod[cnt],
2488  partkey->parttypcoll[cnt], 0);
2489  }
2490  else
2491  {
2492  if (lc == NULL)
2493  elog(ERROR, "wrong number of partition key expressions");
2494 
2495  /* Re-stamp the expression with given varno. */
2496  partexpr = (Expr *) copyObject(lfirst(lc));
2497  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2498  lc = lnext(partkey->partexprs, lc);
2499  }
2500 
2501  /* Base relations have a single expression per key. */
2502  partexprs[cnt] = list_make1(partexpr);
2503  }
2504 
2505  rel->partexprs = partexprs;
2506 
2507  /*
2508  * A base relation does not have nullable partition key expressions, since
2509  * no outer join is involved. We still allocate an array of empty
2510  * expression lists to keep partition key expression handling code simple.
2511  * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2512  */
2513  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2514 }
#define InvalidAttrNumber
Definition: attnum.h:23
#define copyObject(obj)
Definition: nodes.h:244
#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 2319 of file plancat.c.

2321 {
2322  PartitionDesc partdesc;
2323 
2324  /*
2325  * Create the PartitionDirectory infrastructure if we didn't already.
2326  */
2327  if (root->glob->partition_directory == NULL)
2328  {
2329  root->glob->partition_directory =
2331  }
2332 
2333  partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
2334  relation);
2335  rel->part_scheme = find_partition_scheme(root, relation);
2336  Assert(partdesc != NULL && rel->part_scheme != NULL);
2337  rel->boundinfo = partdesc->boundinfo;
2338  rel->nparts = partdesc->nparts;
2339  set_baserel_partition_key_exprs(relation, rel);
2340  set_baserel_partition_constraint(relation, rel);
2341 }
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:2349
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2456
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().