PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
plancat.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/sysattr.h"
#include "access/transam.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/heap.h"
#include "catalog/partition.h"
#include "catalog/pg_am.h"
#include "catalog/pg_statistic_ext.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/plancat.h"
#include "optimizer/predtest.h"
#include "optimizer/prep.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "statistics/statistics.h"
#include "storage/bufmgr.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/rel.h"
#include "utils/snapmgr.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 int32 get_rel_data_width (Relation rel, int32 *attr_widths)
 
static Listget_relation_constraints (PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
 
static Listbuild_index_tlist (PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
 
static Listget_relation_statistics (RelOptInfo *rel, Relation relation)
 
static void set_relation_partition_info (PlannerInfo *root, RelOptInfo *rel, Relation relation)
 
static PartitionScheme find_partition_scheme (PlannerInfo *root, Relation rel)
 
static void set_baserel_partition_key_exprs (Relation relation, RelOptInfo *rel)
 
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_relation_data_width (Oid relid, int32 *attr_widths)
 
bool relation_excluded_by_constraints (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
Listbuild_physical_tlist (PlannerInfo *root, RelOptInfo *rel)
 
Selectivity restriction_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
 
Selectivity join_selectivity (PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
bool has_unique_index (RelOptInfo *rel, AttrNumber attno)
 
bool has_row_triggers (PlannerInfo *root, Index rti, CmdType event)
 

Variables

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION
 
get_relation_info_hook_type get_relation_info_hook = NULL
 

Function Documentation

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

Definition at line 1602 of file plancat.c.

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

Referenced by get_relation_info().

1604 {
1605  List *tlist = NIL;
1606  Index varno = index->rel->relid;
1607  ListCell *indexpr_item;
1608  int i;
1609 
1610  indexpr_item = list_head(index->indexprs);
1611  for (i = 0; i < index->ncolumns; i++)
1612  {
1613  int indexkey = index->indexkeys[i];
1614  Expr *indexvar;
1615 
1616  if (indexkey != 0)
1617  {
1618  /* simple column */
1619  Form_pg_attribute att_tup;
1620 
1621  if (indexkey < 0)
1622  att_tup = SystemAttributeDefinition(indexkey,
1623  heapRelation->rd_rel->relhasoids);
1624  else
1625  att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1626 
1627  indexvar = (Expr *) makeVar(varno,
1628  indexkey,
1629  att_tup->atttypid,
1630  att_tup->atttypmod,
1631  att_tup->attcollation,
1632  0);
1633  }
1634  else
1635  {
1636  /* expression column */
1637  if (indexpr_item == NULL)
1638  elog(ERROR, "wrong number of index expressions");
1639  indexvar = (Expr *) lfirst(indexpr_item);
1640  indexpr_item = lnext(indexpr_item);
1641  }
1642 
1643  tlist = lappend(tlist,
1644  makeTargetEntry(indexvar,
1645  i + 1,
1646  NULL,
1647  false));
1648  }
1649  if (indexpr_item != NULL)
1650  elog(ERROR, "wrong number of index expressions");
1651 
1652  return tlist;
1653 }
#define NIL
Definition: pg_list.h:69
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
Form_pg_class rd_rel
Definition: rel.h:114
RelOptInfo * rel
Definition: relation.h:721
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
int ncolumns
Definition: relation.h:729
#define lnext(lc)
Definition: pg_list.h:105
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
unsigned int Index
Definition: c.h:359
TupleDesc rd_att
Definition: rel.h:115
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
#define lfirst(lc)
Definition: pg_list.h:106
int i
int * indexkeys
Definition: relation.h:730
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List * indexprs
Definition: relation.h:741
List* build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1482 of file plancat.c.

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

Referenced by create_scan_plan().

1483 {
1484  List *tlist = NIL;
1485  Index varno = rel->relid;
1486  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1487  Relation relation;
1488  Query *subquery;
1489  Var *var;
1490  ListCell *l;
1491  int attrno,
1492  numattrs;
1493  List *colvars;
1494 
1495  switch (rte->rtekind)
1496  {
1497  case RTE_RELATION:
1498  /* Assume we already have adequate lock */
1499  relation = heap_open(rte->relid, NoLock);
1500 
1501  numattrs = RelationGetNumberOfAttributes(relation);
1502  for (attrno = 1; attrno <= numattrs; attrno++)
1503  {
1504  Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1505  attrno - 1);
1506 
1507  if (att_tup->attisdropped)
1508  {
1509  /* found a dropped col, so punt */
1510  tlist = NIL;
1511  break;
1512  }
1513 
1514  var = makeVar(varno,
1515  attrno,
1516  att_tup->atttypid,
1517  att_tup->atttypmod,
1518  att_tup->attcollation,
1519  0);
1520 
1521  tlist = lappend(tlist,
1522  makeTargetEntry((Expr *) var,
1523  attrno,
1524  NULL,
1525  false));
1526  }
1527 
1528  heap_close(relation, NoLock);
1529  break;
1530 
1531  case RTE_SUBQUERY:
1532  subquery = rte->subquery;
1533  foreach(l, subquery->targetList)
1534  {
1535  TargetEntry *tle = (TargetEntry *) lfirst(l);
1536 
1537  /*
1538  * A resjunk column of the subquery can be reflected as
1539  * resjunk in the physical tlist; we need not punt.
1540  */
1541  var = makeVarFromTargetEntry(varno, tle);
1542 
1543  tlist = lappend(tlist,
1544  makeTargetEntry((Expr *) var,
1545  tle->resno,
1546  NULL,
1547  tle->resjunk));
1548  }
1549  break;
1550 
1551  case RTE_FUNCTION:
1552  case RTE_TABLEFUNC:
1553  case RTE_VALUES:
1554  case RTE_CTE:
1555  case RTE_NAMEDTUPLESTORE:
1556  /* Not all of these can have dropped cols, but share code anyway */
1557  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1558  NULL, &colvars);
1559  foreach(l, colvars)
1560  {
1561  var = (Var *) lfirst(l);
1562 
1563  /*
1564  * A non-Var in expandRTE's output means a dropped column;
1565  * must punt.
1566  */
1567  if (!IsA(var, Var))
1568  {
1569  tlist = NIL;
1570  break;
1571  }
1572 
1573  tlist = lappend(tlist,
1574  makeTargetEntry((Expr *) var,
1575  var->varattno,
1576  NULL,
1577  false));
1578  }
1579  break;
1580 
1581  default:
1582  /* caller error */
1583  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1584  (int) rte->rtekind);
1585  break;
1586  }
1587 
1588  return tlist;
1589 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:422
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:104
AttrNumber varattno
Definition: primnodes.h:168
#define heap_close(r, l)
Definition: heapam.h:97
Definition: primnodes.h:163
List * targetList
Definition: parsenodes.h:138
bool resjunk
Definition: primnodes.h:1375
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
AttrNumber resno
Definition: primnodes.h:1369
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
unsigned int Index
Definition: c.h:359
TupleDesc rd_att
Definition: rel.h:115
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:945
Query * subquery
Definition: parsenodes.h:968
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
void estimate_rel_size ( Relation  rel,
int32 attr_widths,
BlockNumber pages,
double *  tuples,
double *  allvisfrac 
)

Definition at line 920 of file plancat.c.

References get_rel_data_width(), MAXALIGN, RelationData::rd_rel, RelationGetNumberOfBlocks, RELKIND_FOREIGN_TABLE, RELKIND_INDEX, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_TOASTVALUE, rint(), SizeofHeapTupleHeader, and SizeOfPageHeaderData.

Referenced by get_relation_info(), and hashbuild().

922 {
923  BlockNumber curpages;
924  BlockNumber relpages;
925  double reltuples;
926  BlockNumber relallvisible;
927  double density;
928 
929  switch (rel->rd_rel->relkind)
930  {
931  case RELKIND_RELATION:
932  case RELKIND_INDEX:
933  case RELKIND_MATVIEW:
934  case RELKIND_TOASTVALUE:
935  /* it has storage, ok to call the smgr */
936  curpages = RelationGetNumberOfBlocks(rel);
937 
938  /*
939  * HACK: if the relation has never yet been vacuumed, use a
940  * minimum size estimate of 10 pages. The idea here is to avoid
941  * assuming a newly-created table is really small, even if it
942  * currently is, because that may not be true once some data gets
943  * loaded into it. Once a vacuum or analyze cycle has been done
944  * on it, it's more reasonable to believe the size is somewhat
945  * stable.
946  *
947  * (Note that this is only an issue if the plan gets cached and
948  * used again after the table has been filled. What we're trying
949  * to avoid is using a nestloop-type plan on a table that has
950  * grown substantially since the plan was made. Normally,
951  * autovacuum/autoanalyze will occur once enough inserts have
952  * happened and cause cached-plan invalidation; but that doesn't
953  * happen instantaneously, and it won't happen at all for cases
954  * such as temporary tables.)
955  *
956  * We approximate "never vacuumed" by "has relpages = 0", which
957  * means this will also fire on genuinely empty relations. Not
958  * great, but fortunately that's a seldom-seen case in the real
959  * world, and it shouldn't degrade the quality of the plan too
960  * much anyway to err in this direction.
961  *
962  * There are two exceptions wherein we don't apply this heuristic.
963  * One is if the table has inheritance children. Totally empty
964  * parent tables are quite common, so we should be willing to
965  * believe that they are empty. Also, we don't apply the 10-page
966  * minimum to indexes.
967  */
968  if (curpages < 10 &&
969  rel->rd_rel->relpages == 0 &&
970  !rel->rd_rel->relhassubclass &&
971  rel->rd_rel->relkind != RELKIND_INDEX)
972  curpages = 10;
973 
974  /* report estimated # pages */
975  *pages = curpages;
976  /* quick exit if rel is clearly empty */
977  if (curpages == 0)
978  {
979  *tuples = 0;
980  *allvisfrac = 0;
981  break;
982  }
983  /* coerce values in pg_class to more desirable types */
984  relpages = (BlockNumber) rel->rd_rel->relpages;
985  reltuples = (double) rel->rd_rel->reltuples;
986  relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
987 
988  /*
989  * If it's an index, discount the metapage while estimating the
990  * number of tuples. This is a kluge because it assumes more than
991  * it ought to about index structure. Currently it's OK for
992  * btree, hash, and GIN indexes but suspect for GiST indexes.
993  */
994  if (rel->rd_rel->relkind == RELKIND_INDEX &&
995  relpages > 0)
996  {
997  curpages--;
998  relpages--;
999  }
1000 
1001  /* estimate number of tuples from previous tuple density */
1002  if (relpages > 0)
1003  density = reltuples / (double) relpages;
1004  else
1005  {
1006  /*
1007  * When we have no data because the relation was truncated,
1008  * estimate tuple width from attribute datatypes. We assume
1009  * here that the pages are completely full, which is OK for
1010  * tables (since they've presumably not been VACUUMed yet) but
1011  * is probably an overestimate for indexes. Fortunately
1012  * get_relation_info() can clamp the overestimate to the
1013  * parent table's size.
1014  *
1015  * Note: this code intentionally disregards alignment
1016  * considerations, because (a) that would be gilding the lily
1017  * considering how crude the estimate is, and (b) it creates
1018  * platform dependencies in the default plans which are kind
1019  * of a headache for regression testing.
1020  */
1021  int32 tuple_width;
1022 
1023  tuple_width = get_rel_data_width(rel, attr_widths);
1024  tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1025  tuple_width += sizeof(ItemIdData);
1026  /* note: integer division is intentional here */
1027  density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1028  }
1029  *tuples = rint(density * (double) curpages);
1030 
1031  /*
1032  * We use relallvisible as-is, rather than scaling it up like we
1033  * do for the pages and tuples counts, on the theory that any
1034  * pages added since the last VACUUM are most likely not marked
1035  * all-visible. But costsize.c wants it converted to a fraction.
1036  */
1037  if (relallvisible == 0 || curpages <= 0)
1038  *allvisfrac = 0;
1039  else if ((double) relallvisible >= curpages)
1040  *allvisfrac = 1;
1041  else
1042  *allvisfrac = (double) relallvisible / curpages;
1043  break;
1044  case RELKIND_SEQUENCE:
1045  /* Sequences always have a known size */
1046  *pages = 1;
1047  *tuples = 1;
1048  *allvisfrac = 0;
1049  break;
1050  case RELKIND_FOREIGN_TABLE:
1051  /* Just use whatever's in pg_class */
1052  *pages = rel->rd_rel->relpages;
1053  *tuples = rel->rd_rel->reltuples;
1054  *allvisfrac = 0;
1055  break;
1056  default:
1057  /* else it has no disk storage; probably shouldn't get here? */
1058  *pages = 0;
1059  *tuples = 0;
1060  *allvisfrac = 0;
1061  break;
1062  }
1063 }
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
#define RELKIND_MATVIEW
Definition: pg_class.h:165
uint32 BlockNumber
Definition: block.h:31
#define SizeOfPageHeaderData
Definition: bufpage.h:212
Form_pg_class rd_rel
Definition: rel.h:114
signed int int32
Definition: c.h:246
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1080
struct ItemIdData ItemIdData
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
double rint(double x)
Definition: rint.c:22
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define MAXALIGN(LEN)
Definition: c.h:576
#define RELKIND_INDEX
Definition: pg_class.h:161
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
static PartitionScheme find_partition_scheme ( PlannerInfo root,
Relation  rel 
)
static

Definition at line 1847 of file plancat.c.

References Assert, lappend(), lfirst, palloc(), palloc0(), PlannerInfo::part_schemes, PartitionKeyData::partnatts, PartitionSchemeData::partnatts, PartitionKeyData::partopcintype, PartitionSchemeData::partopcintype, PartitionKeyData::partopfamily, PartitionSchemeData::partopfamily, PartitionKeyData::parttypbyval, PartitionSchemeData::parttypbyval, PartitionKeyData::parttypcoll, PartitionSchemeData::parttypcoll, PartitionKeyData::parttyplen, PartitionSchemeData::parttyplen, RelationGetPartitionKey, PartitionKeyData::strategy, and PartitionSchemeData::strategy.

Referenced by set_relation_partition_info().

1848 {
1849  PartitionKey partkey = RelationGetPartitionKey(relation);
1850  ListCell *lc;
1851  int partnatts;
1852  PartitionScheme part_scheme;
1853 
1854  /* A partitioned table should have a partition key. */
1855  Assert(partkey != NULL);
1856 
1857  partnatts = partkey->partnatts;
1858 
1859  /* Search for a matching partition scheme and return if found one. */
1860  foreach(lc, root->part_schemes)
1861  {
1862  part_scheme = lfirst(lc);
1863 
1864  /* Match partitioning strategy and number of keys. */
1865  if (partkey->strategy != part_scheme->strategy ||
1866  partnatts != part_scheme->partnatts)
1867  continue;
1868 
1869  /* Match the partition key types. */
1870  if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
1871  sizeof(Oid) * partnatts) != 0 ||
1872  memcmp(partkey->partopcintype, part_scheme->partopcintype,
1873  sizeof(Oid) * partnatts) != 0 ||
1874  memcmp(partkey->parttypcoll, part_scheme->parttypcoll,
1875  sizeof(Oid) * partnatts) != 0)
1876  continue;
1877 
1878  /*
1879  * Length and byval information should match when partopcintype
1880  * matches.
1881  */
1882  Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
1883  sizeof(int16) * partnatts) == 0);
1884  Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
1885  sizeof(bool) * partnatts) == 0);
1886 
1887  /* Found matching partition scheme. */
1888  return part_scheme;
1889  }
1890 
1891  /*
1892  * Did not find matching partition scheme. Create one copying relevant
1893  * information from the relcache. We need to copy the contents of the array
1894  * since the relcache entry may not survive after we have closed the
1895  * relation.
1896  */
1897  part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
1898  part_scheme->strategy = partkey->strategy;
1899  part_scheme->partnatts = partkey->partnatts;
1900 
1901  part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
1902  memcpy(part_scheme->partopfamily, partkey->partopfamily,
1903  sizeof(Oid) * partnatts);
1904 
1905  part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
1906  memcpy(part_scheme->partopcintype, partkey->partopcintype,
1907  sizeof(Oid) * partnatts);
1908 
1909  part_scheme->parttypcoll = (Oid *) palloc(sizeof(Oid) * partnatts);
1910  memcpy(part_scheme->parttypcoll, partkey->parttypcoll,
1911  sizeof(Oid) * partnatts);
1912 
1913  part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
1914  memcpy(part_scheme->parttyplen, partkey->parttyplen,
1915  sizeof(int16) * partnatts);
1916 
1917  part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
1918  memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
1919  sizeof(bool) * partnatts);
1920 
1921  /* Add the partitioning scheme to PlannerInfo. */
1922  root->part_schemes = lappend(root->part_schemes, part_scheme);
1923 
1924  return part_scheme;
1925 }
signed short int16
Definition: c.h:245
Oid * partopfamily
Definition: rel.h:61
List * part_schemes
Definition: relation.h:269
char strategy
Definition: rel.h:54
unsigned int Oid
Definition: postgres_ext.h:31
Oid * parttypcoll
Definition: rel.h:74
struct PartitionSchemeData * PartitionScheme
Definition: relation.h:359
int16 * parttyplen
Definition: relation.h:355
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc0(Size size)
Definition: mcxt.c:877
int16 partnatts
Definition: rel.h:55
bool * parttypbyval
Definition: rel.h:72
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
int16 * parttyplen
Definition: rel.h:71
#define RelationGetPartitionKey(relation)
Definition: rel.h:584
void * palloc(Size size)
Definition: mcxt.c:848
Oid * partopcintype
Definition: rel.h:62
static int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)
static

Definition at line 1080 of file plancat.c.

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

Referenced by estimate_rel_size(), and get_relation_data_width().

1081 {
1082  int32 tuple_width = 0;
1083  int i;
1084 
1085  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1086  {
1087  Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1088  int32 item_width;
1089 
1090  if (att->attisdropped)
1091  continue;
1092 
1093  /* use previously cached data, if any */
1094  if (attr_widths != NULL && attr_widths[i] > 0)
1095  {
1096  tuple_width += attr_widths[i];
1097  continue;
1098  }
1099 
1100  /* This should match set_rel_width() in costsize.c */
1101  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1102  if (item_width <= 0)
1103  {
1104  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1105  Assert(item_width > 0);
1106  }
1107  if (attr_widths != NULL)
1108  attr_widths[i] = item_width;
1109  tuple_width += item_width;
1110  }
1111 
1112  return tuple_width;
1113 }
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:422
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
signed int int32
Definition: c.h:246
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
TupleDesc rd_att
Definition: rel.h:115
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2328
#define Assert(condition)
Definition: c.h:681
int i
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:2828
#define RelationGetRelid(relation)
Definition: rel.h:416
static List * get_relation_constraints ( PlannerInfo root,
Oid  relationObjectId,
RelOptInfo rel,
bool  include_notnull 
)
static

Definition at line 1156 of file plancat.c.

References NullTest::arg, NullTest::argisrow, canonicalize_qual(), constrCheck::ccbin, constrCheck::ccvalid, ChangeVarNodes(), tupleConstr::check, tupleDesc::constr, eval_const_expressions(), tupleConstr::has_not_null, heap_close, heap_open(), i, IS_NOT_NULL, lappend(), list_concat(), NullTest::location, make_ands_implicit(), makeNode, makeVar(), tupleDesc::natts, NIL, NoLock, NullTest::nulltesttype, tupleConstr::num_check, RelationData::rd_att, RelationGetPartitionQual(), RelOptInfo::relid, stringToNode(), and TupleDescAttr.

Referenced by relation_excluded_by_constraints().

1159 {
1160  List *result = NIL;
1161  Index varno = rel->relid;
1162  Relation relation;
1163  TupleConstr *constr;
1164  List *pcqual;
1165 
1166  /*
1167  * We assume the relation has already been safely locked.
1168  */
1169  relation = heap_open(relationObjectId, NoLock);
1170 
1171  constr = relation->rd_att->constr;
1172  if (constr != NULL)
1173  {
1174  int num_check = constr->num_check;
1175  int i;
1176 
1177  for (i = 0; i < num_check; i++)
1178  {
1179  Node *cexpr;
1180 
1181  /*
1182  * If this constraint hasn't been fully validated yet, we must
1183  * ignore it here.
1184  */
1185  if (!constr->check[i].ccvalid)
1186  continue;
1187 
1188  cexpr = stringToNode(constr->check[i].ccbin);
1189 
1190  /*
1191  * Run each expression through const-simplification and
1192  * canonicalization. This is not just an optimization, but is
1193  * necessary, because we will be comparing it to
1194  * similarly-processed qual clauses, and may fail to detect valid
1195  * matches without this. This must match the processing done to
1196  * qual clauses in preprocess_expression()! (We can skip the
1197  * stuff involving subqueries, however, since we don't allow any
1198  * in check constraints.)
1199  */
1200  cexpr = eval_const_expressions(root, cexpr);
1201 
1202  cexpr = (Node *) canonicalize_qual((Expr *) cexpr);
1203 
1204  /* Fix Vars to have the desired varno */
1205  if (varno != 1)
1206  ChangeVarNodes(cexpr, 1, varno, 0);
1207 
1208  /*
1209  * Finally, convert to implicit-AND format (that is, a List) and
1210  * append the resulting item(s) to our output list.
1211  */
1212  result = list_concat(result,
1213  make_ands_implicit((Expr *) cexpr));
1214  }
1215 
1216  /* Add NOT NULL constraints in expression form, if requested */
1217  if (include_notnull && constr->has_not_null)
1218  {
1219  int natts = relation->rd_att->natts;
1220 
1221  for (i = 1; i <= natts; i++)
1222  {
1223  Form_pg_attribute att = TupleDescAttr(relation->rd_att, i - 1);
1224 
1225  if (att->attnotnull && !att->attisdropped)
1226  {
1227  NullTest *ntest = makeNode(NullTest);
1228 
1229  ntest->arg = (Expr *) makeVar(varno,
1230  i,
1231  att->atttypid,
1232  att->atttypmod,
1233  att->attcollation,
1234  0);
1235  ntest->nulltesttype = IS_NOT_NULL;
1236 
1237  /*
1238  * argisrow=false is correct even for a composite column,
1239  * because attnotnull does not represent a SQL-spec IS NOT
1240  * NULL test in such a case, just IS DISTINCT FROM NULL.
1241  */
1242  ntest->argisrow = false;
1243  ntest->location = -1;
1244  result = lappend(result, ntest);
1245  }
1246  }
1247  }
1248  }
1249 
1250  /* Append partition predicates, if any */
1251  pcqual = RelationGetPartitionQual(relation);
1252  if (pcqual)
1253  {
1254  /*
1255  * Run each expression through const-simplification and
1256  * canonicalization similar to check constraints.
1257  */
1258  pcqual = (List *) eval_const_expressions(root, (Node *) pcqual);
1259  pcqual = (List *) canonicalize_qual((Expr *) pcqual);
1260 
1261  /* Fix Vars to have the desired varno */
1262  if (varno != 1)
1263  ChangeVarNodes((Node *) pcqual, 1, varno, 0);
1264 
1265  result = list_concat(result, pcqual);
1266  }
1267 
1268  heap_close(relation, NoLock);
1269 
1270  return result;
1271 }
#define NIL
Definition: pg_list.h:69
void * stringToNode(char *str)
Definition: read.c:38
ConstrCheck * check
Definition: tupdesc.h:40
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
char * ccbin
Definition: tupdesc.h:31
Definition: nodes.h:510
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2429
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define heap_close(r, l)
Definition: heapam.h:97
int natts
Definition: tupdesc.h:73
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:378
Expr * arg
Definition: primnodes.h:1180
#define NoLock
Definition: lockdefs.h:34
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Index relid
Definition: relation.h:613
bool has_not_null
Definition: tupdesc.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:1240
Expr * canonicalize_qual(Expr *qual)
Definition: prepqual.c:286
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
unsigned int Index
Definition: c.h:359
TupleDesc rd_att
Definition: rel.h:115
NullTestType nulltesttype
Definition: primnodes.h:1181
#define makeNode(_type_)
Definition: nodes.h:558
TupleConstr * constr
Definition: tupdesc.h:78
int location
Definition: primnodes.h:1183
bool ccvalid
Definition: tupdesc.h:32
int i
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
bool argisrow
Definition: primnodes.h:1182
uint16 num_check
Definition: tupdesc.h:42
Definition: pg_list.h:45
int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1122 of file plancat.c.

References get_rel_data_width(), heap_close, heap_open(), and NoLock.

Referenced by plan_cluster_use_sort(), and set_rel_width().

1123 {
1124  int32 result;
1125  Relation relation;
1126 
1127  /* As above, assume relation is already locked */
1128  relation = heap_open(relid, NoLock);
1129 
1130  result = get_rel_data_width(relation, attr_widths);
1131 
1132  heap_close(relation, NoLock);
1133 
1134  return result;
1135 }
#define heap_close(r, l)
Definition: heapam.h:97
signed int int32
Definition: c.h:246
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1080
#define NoLock
Definition: lockdefs.h:34
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
static void get_relation_foreign_keys ( PlannerInfo root,
RelOptInfo rel,
Relation  relation,
bool  inhparent 
)
static

Definition at line 457 of file plancat.c.

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

Referenced by get_relation_info().

459 {
460  List *rtable = root->parse->rtable;
461  List *cachedfkeys;
462  ListCell *lc;
463 
464  /*
465  * If it's not a baserel, we don't care about its FKs. Also, if the query
466  * references only a single relation, we can skip the lookup since no FKs
467  * could satisfy the requirements below.
468  */
469  if (rel->reloptkind != RELOPT_BASEREL ||
470  list_length(rtable) < 2)
471  return;
472 
473  /*
474  * If it's the parent of an inheritance tree, ignore its FKs. We could
475  * make useful FK-based deductions if we found that all members of the
476  * inheritance tree have equivalent FK constraints, but detecting that
477  * would require code that hasn't been written.
478  */
479  if (inhparent)
480  return;
481 
482  /*
483  * Extract data about relation's FKs from the relcache. Note that this
484  * list belongs to the relcache and might disappear in a cache flush, so
485  * we must not do any further catalog access within this function.
486  */
487  cachedfkeys = RelationGetFKeyList(relation);
488 
489  /*
490  * Figure out which FKs are of interest for this query, and create
491  * ForeignKeyOptInfos for them. We want only FKs that reference some
492  * other RTE of the current query. In queries containing self-joins,
493  * there might be more than one other RTE for a referenced table, and we
494  * should make a ForeignKeyOptInfo for each occurrence.
495  *
496  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
497  * too hard to identify those here, so we might end up making some useless
498  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
499  * them again.
500  */
501  foreach(lc, cachedfkeys)
502  {
503  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
504  Index rti;
505  ListCell *lc2;
506 
507  /* conrelid should always be that of the table we're considering */
508  Assert(cachedfk->conrelid == RelationGetRelid(relation));
509 
510  /* Scan to find other RTEs matching confrelid */
511  rti = 0;
512  foreach(lc2, rtable)
513  {
514  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
515  ForeignKeyOptInfo *info;
516 
517  rti++;
518  /* Ignore if not the correct table */
519  if (rte->rtekind != RTE_RELATION ||
520  rte->relid != cachedfk->confrelid)
521  continue;
522  /* Ignore if it's an inheritance parent; doesn't really match */
523  if (rte->inh)
524  continue;
525  /* Ignore self-referential FKs; we only care about joins */
526  if (rti == rel->relid)
527  continue;
528 
529  /* OK, let's make an entry */
530  info = makeNode(ForeignKeyOptInfo);
531  info->con_relid = rel->relid;
532  info->ref_relid = rti;
533  info->nkeys = cachedfk->nkeys;
534  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
535  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
536  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
537  /* zero out fields to be filled by match_foreign_keys_to_quals */
538  info->nmatched_ec = 0;
539  info->nmatched_rcols = 0;
540  info->nmatched_ri = 0;
541  memset(info->eclass, 0, sizeof(info->eclass));
542  memset(info->rinfos, 0, sizeof(info->rinfos));
543 
544  root->fkey_list = lappend(root->fkey_list, info);
545  }
546  }
547 }
Query * parse
Definition: relation.h:155
RelOptKind reloptkind
Definition: relation.h:582
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: rel.h:243
List * fkey_list
Definition: relation.h:260
List * rtable
Definition: parsenodes.h:135
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: relation.h:787
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: relation.h:794
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: relation.h:785
unsigned int Index
Definition: c.h:359
#define makeNode(_type_)
Definition: nodes.h:558
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: rel.h:245
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:945
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4194
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: rel.h:244
Definition: pg_list.h:45
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: relation.h:786
#define RelationGetRelid(relation)
Definition: rel.h:416
List * rinfos[INDEX_MAX_KEYS]
Definition: relation.h:796
void get_relation_info ( PlannerInfo root,
Oid  relationObjectId,
bool  inhparent,
RelOptInfo rel 
)

Definition at line 106 of file plancat.c.

References _bt_getrootheight(), AccessShareLock, RelOptInfo::allvisfrac, IndexAmRoutine::amcanorder, IndexAmRoutine::amcanorderbyop, IndexOptInfo::amcanorderbyop, IndexAmRoutine::amcanparallel, IndexOptInfo::amcanparallel, IndexAmRoutine::amcostestimate, IndexOptInfo::amcostestimate, IndexAmRoutine::amgetbitmap, IndexAmRoutine::amgettuple, IndexOptInfo::amhasgetbitmap, IndexOptInfo::amhasgettuple, IndexAmRoutine::amoptionalkey, IndexOptInfo::amoptionalkey, IndexAmRoutine::amsearcharray, IndexOptInfo::amsearcharray, IndexAmRoutine::amsearchnulls, IndexOptInfo::amsearchnulls, Assert, RelOptInfo::attr_needed, RelOptInfo::attr_widths, BTLessStrategyNumber, BTREE_AM_OID, build_index_tlist(), IndexOptInfo::canreturn, ChangeVarNodes(), ereport, errcode(), errmsg(), ERROR, estimate_rel_size(), RelOptInfo::fdwroutine, FirstLowInvalidHeapAttributeNumber, get_opfamily_member(), get_ordering_op_properties(), get_relation_foreign_keys(), get_relation_info_hook, get_relation_statistics(), GetFdwRoutineForRelation(), GetForeignServerIdByRelId(), PlannerInfo::glob, heap_close, heap_open(), HeapTupleHeaderGetXmin, IndexOptInfo::hypothetical, i, IgnoreSystemIndexes, IndexOptInfo::immediate, index_can_return(), index_close(), index_open(), IndexOptInfo::indexcollations, IndexIsValid, IndexOptInfo::indexkeys, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, IndexOptInfo::indextlist, INDOPTION_DESC, INDOPTION_NULLS_FIRST, IndexOptInfo::indpred, IndexOptInfo::indrestrictinfo, InvalidOid, IsSystemRelation(), lcons(), lfirst_oid, list_free(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, IndexOptInfo::ncolumns, NIL, NoLock, IndexOptInfo::nulls_first, OidIsValid, IndexOptInfo::opcintype, IndexOptInfo::opfamily, RelOptInfo::pages, IndexOptInfo::pages, palloc(), palloc0(), PlannerInfo::parse, IndexOptInfo::predOK, RelationData::rd_amroutine, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_opcintype, RelationData::rd_opfamily, RelationData::rd_rel, RecoveryInProgress(), IndexOptInfo::rel, RelOptInfo::rel_parallel_workers, IndexOptInfo::relam, RelationGetForm, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNumberOfAttributes, RelationGetNumberOfBlocks, RelationGetParallelWorkers, RelationGetRelid, RelationNeedsWAL, RelOptInfo::relid, RELKIND_FOREIGN_TABLE, RELKIND_PARTITIONED_TABLE, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, Query::resultRelation, IndexOptInfo::reverse_sort, RowExclusiveLock, RelOptInfo::serverid, set_relation_partition_info(), IndexOptInfo::sortopfamily, RelOptInfo::statlist, HeapTupleData::t_data, TransactionIdPrecedes(), TransactionXmin, PlannerGlobal::transientPlan, IndexOptInfo::tree_height, RelOptInfo::tuples, IndexOptInfo::tuples, and IndexOptInfo::unique.

Referenced by build_simple_rel().

108 {
109  Index varno = rel->relid;
110  Relation relation;
111  bool hasindex;
112  List *indexinfos = NIL;
113 
114  /*
115  * We need not lock the relation since it was already locked, either by
116  * the rewriter or when expand_inherited_rtentry() added it to the query's
117  * rangetable.
118  */
119  relation = heap_open(relationObjectId, NoLock);
120 
121  /* Temporary and unlogged relations are inaccessible during recovery. */
122  if (!RelationNeedsWAL(relation) && RecoveryInProgress())
123  ereport(ERROR,
124  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
125  errmsg("cannot access temporary or unlogged relations during recovery")));
126 
128  rel->max_attr = RelationGetNumberOfAttributes(relation);
129  rel->reltablespace = RelationGetForm(relation)->reltablespace;
130 
131  Assert(rel->max_attr >= rel->min_attr);
132  rel->attr_needed = (Relids *)
133  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
134  rel->attr_widths = (int32 *)
135  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
136 
137  /*
138  * Estimate relation size --- unless it's an inheritance parent, in which
139  * case the size will be computed later in set_append_rel_pathlist, and we
140  * must leave it zero for now to avoid bollixing the total_table_pages
141  * calculation.
142  */
143  if (!inhparent)
144  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
145  &rel->pages, &rel->tuples, &rel->allvisfrac);
146 
147  /* Retrieve the parallel_workers reloption, or -1 if not set. */
149 
150  /*
151  * Make list of indexes. Ignore indexes on system catalogs if told to.
152  * Don't bother with indexes for an inheritance parent, either.
153  */
154  if (inhparent ||
155  (IgnoreSystemIndexes && IsSystemRelation(relation)))
156  hasindex = false;
157  else
158  hasindex = relation->rd_rel->relhasindex;
159 
160  if (hasindex)
161  {
162  List *indexoidlist;
163  ListCell *l;
164  LOCKMODE lmode;
165 
166  indexoidlist = RelationGetIndexList(relation);
167 
168  /*
169  * For each index, we get the same type of lock that the executor will
170  * need, and do not release it. This saves a couple of trips to the
171  * shared lock manager while not creating any real loss of
172  * concurrency, because no schema changes could be happening on the
173  * index while we hold lock on the parent rel, and neither lock type
174  * blocks any other kind of index operation.
175  */
176  if (rel->relid == root->parse->resultRelation)
177  lmode = RowExclusiveLock;
178  else
179  lmode = AccessShareLock;
180 
181  foreach(l, indexoidlist)
182  {
183  Oid indexoid = lfirst_oid(l);
184  Relation indexRelation;
186  IndexAmRoutine *amroutine;
187  IndexOptInfo *info;
188  int ncolumns;
189  int i;
190 
191  /*
192  * Extract info from the relation descriptor for the index.
193  */
194  indexRelation = index_open(indexoid, lmode);
195  index = indexRelation->rd_index;
196 
197  /*
198  * Ignore invalid indexes, since they can't safely be used for
199  * queries. Note that this is OK because the data structure we
200  * are constructing is only used by the planner --- the executor
201  * still needs to insert into "invalid" indexes, if they're marked
202  * IndexIsReady.
203  */
204  if (!IndexIsValid(index))
205  {
206  index_close(indexRelation, NoLock);
207  continue;
208  }
209 
210  /*
211  * If the index is valid, but cannot yet be used, ignore it; but
212  * mark the plan we are generating as transient. See
213  * src/backend/access/heap/README.HOT for discussion.
214  */
215  if (index->indcheckxmin &&
218  {
219  root->glob->transientPlan = true;
220  index_close(indexRelation, NoLock);
221  continue;
222  }
223 
224  info = makeNode(IndexOptInfo);
225 
226  info->indexoid = index->indexrelid;
227  info->reltablespace =
228  RelationGetForm(indexRelation)->reltablespace;
229  info->rel = rel;
230  info->ncolumns = ncolumns = index->indnatts;
231  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
232  info->indexcollations = (Oid *) palloc(sizeof(Oid) * ncolumns);
233  info->opfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
234  info->opcintype = (Oid *) palloc(sizeof(Oid) * ncolumns);
235  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
236 
237  for (i = 0; i < ncolumns; i++)
238  {
239  info->indexkeys[i] = index->indkey.values[i];
240  info->indexcollations[i] = indexRelation->rd_indcollation[i];
241  info->opfamily[i] = indexRelation->rd_opfamily[i];
242  info->opcintype[i] = indexRelation->rd_opcintype[i];
243  info->canreturn[i] = index_can_return(indexRelation, i + 1);
244  }
245 
246  info->relam = indexRelation->rd_rel->relam;
247 
248  /* We copy just the fields we need, not all of rd_amroutine */
249  amroutine = indexRelation->rd_amroutine;
250  info->amcanorderbyop = amroutine->amcanorderbyop;
251  info->amoptionalkey = amroutine->amoptionalkey;
252  info->amsearcharray = amroutine->amsearcharray;
253  info->amsearchnulls = amroutine->amsearchnulls;
254  info->amcanparallel = amroutine->amcanparallel;
255  info->amhasgettuple = (amroutine->amgettuple != NULL);
256  info->amhasgetbitmap = (amroutine->amgetbitmap != NULL);
257  info->amcostestimate = amroutine->amcostestimate;
258  Assert(info->amcostestimate != NULL);
259 
260  /*
261  * Fetch the ordering information for the index, if any.
262  */
263  if (info->relam == BTREE_AM_OID)
264  {
265  /*
266  * If it's a btree index, we can use its opfamily OIDs
267  * directly as the sort ordering opfamily OIDs.
268  */
269  Assert(amroutine->amcanorder);
270 
271  info->sortopfamily = info->opfamily;
272  info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
273  info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);
274 
275  for (i = 0; i < ncolumns; i++)
276  {
277  int16 opt = indexRelation->rd_indoption[i];
278 
279  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
280  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
281  }
282  }
283  else if (amroutine->amcanorder)
284  {
285  /*
286  * Otherwise, identify the corresponding btree opfamilies by
287  * trying to map this index's "<" operators into btree. Since
288  * "<" uniquely defines the behavior of a sort order, this is
289  * a sufficient test.
290  *
291  * XXX This method is rather slow and also requires the
292  * undesirable assumption that the other index AM numbers its
293  * strategies the same as btree. It'd be better to have a way
294  * to explicitly declare the corresponding btree opfamily for
295  * each opfamily of the other index type. But given the lack
296  * of current or foreseeable amcanorder index types, it's not
297  * worth expending more effort on now.
298  */
299  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
300  info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
301  info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);
302 
303  for (i = 0; i < ncolumns; i++)
304  {
305  int16 opt = indexRelation->rd_indoption[i];
306  Oid ltopr;
307  Oid btopfamily;
308  Oid btopcintype;
309  int16 btstrategy;
310 
311  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
312  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
313 
314  ltopr = get_opfamily_member(info->opfamily[i],
315  info->opcintype[i],
316  info->opcintype[i],
318  if (OidIsValid(ltopr) &&
320  &btopfamily,
321  &btopcintype,
322  &btstrategy) &&
323  btopcintype == info->opcintype[i] &&
324  btstrategy == BTLessStrategyNumber)
325  {
326  /* Successful mapping */
327  info->sortopfamily[i] = btopfamily;
328  }
329  else
330  {
331  /* Fail ... quietly treat index as unordered */
332  info->sortopfamily = NULL;
333  info->reverse_sort = NULL;
334  info->nulls_first = NULL;
335  break;
336  }
337  }
338  }
339  else
340  {
341  info->sortopfamily = NULL;
342  info->reverse_sort = NULL;
343  info->nulls_first = NULL;
344  }
345 
346  /*
347  * Fetch the index expressions and predicate, if any. We must
348  * modify the copies we obtain from the relcache to have the
349  * correct varno for the parent relation, so that they match up
350  * correctly against qual clauses.
351  */
352  info->indexprs = RelationGetIndexExpressions(indexRelation);
353  info->indpred = RelationGetIndexPredicate(indexRelation);
354  if (info->indexprs && varno != 1)
355  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
356  if (info->indpred && varno != 1)
357  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
358 
359  /* Build targetlist using the completed indexprs data */
360  info->indextlist = build_index_tlist(root, info, relation);
361 
362  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
363  info->predOK = false; /* set later, in indxpath.c */
364  info->unique = index->indisunique;
365  info->immediate = index->indimmediate;
366  info->hypothetical = false;
367 
368  /*
369  * Estimate the index size. If it's not a partial index, we lock
370  * the number-of-tuples estimate to equal the parent table; if it
371  * is partial then we have to use the same methods as we would for
372  * a table, except we can be sure that the index is not larger
373  * than the table.
374  */
375  if (info->indpred == NIL)
376  {
377  info->pages = RelationGetNumberOfBlocks(indexRelation);
378  info->tuples = rel->tuples;
379  }
380  else
381  {
382  double allvisfrac; /* dummy */
383 
384  estimate_rel_size(indexRelation, NULL,
385  &info->pages, &info->tuples, &allvisfrac);
386  if (info->tuples > rel->tuples)
387  info->tuples = rel->tuples;
388  }
389 
390  if (info->relam == BTREE_AM_OID)
391  {
392  /* For btrees, get tree height while we have the index open */
393  info->tree_height = _bt_getrootheight(indexRelation);
394  }
395  else
396  {
397  /* For other index types, just set it to "unknown" for now */
398  info->tree_height = -1;
399  }
400 
401  index_close(indexRelation, NoLock);
402 
403  indexinfos = lcons(info, indexinfos);
404  }
405 
406  list_free(indexoidlist);
407  }
408 
409  rel->indexlist = indexinfos;
410 
411  rel->statlist = get_relation_statistics(rel, relation);
412 
413  /* Grab foreign-table info using the relcache, while we have it */
414  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
415  {
417  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
418  }
419  else
420  {
421  rel->serverid = InvalidOid;
422  rel->fdwroutine = NULL;
423  }
424 
425  /* Collect info about relation's foreign keys, if relevant */
426  get_relation_foreign_keys(root, rel, relation, inhparent);
427 
428  /*
429  * Collect info about relation's partitioning scheme, if any. Only
430  * inheritance parents may be partitioned.
431  */
432  if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
433  set_relation_partition_info(root, rel, relation);
434 
435  heap_close(relation, NoLock);
436 
437  /*
438  * Allow a plugin to editorialize on the info we obtained from the
439  * catalogs. Actions might include altering the assumed relation size,
440  * removing an index, or adding a hypothetical index to the indexlist.
441  */
443  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
444 }
signed short int16
Definition: c.h:245
#define NIL
Definition: pg_list.h:69
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
Query * parse
Definition: relation.h:155
List * statlist
Definition: relation.h:623
int16 * rd_indoption
Definition: rel.h:186
bool predOK
Definition: relation.h:752
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1282
Oid * indexcollations
Definition: relation.h:731
Relids * attr_needed
Definition: relation.h:618
bool IsSystemRelation(Relation relation)
Definition: catalog.c:63
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
amgettuple_function amgettuple
Definition: amapi.h:210
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:435
int LOCKMODE
Definition: lockdefs.h:26
bool amcanorderbyop
Definition: amapi.h:173
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:422
List * indextlist
Definition: relation.h:744
#define RelationGetForm(relation)
Definition: rel.h:410
double tuples
Definition: relation.h:625
Oid reltablespace
Definition: relation.h:614
#define BTREE_AM_OID
Definition: pg_am.h:70
int resultRelation
Definition: parsenodes.h:120
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:510
Oid * sortopfamily
Definition: relation.h:734
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid reltablespace
Definition: relation.h:720
bool IgnoreSystemIndexes
Definition: miscinit.c:74
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
bool hypothetical
Definition: relation.h:755
#define heap_close(r, l)
Definition: heapam.h:97
bool immediate
Definition: relation.h:754
double tuples
Definition: relation.h:725
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:7954
int tree_height
Definition: relation.h:726
#define OidIsValid(objectId)
Definition: c.h:532
bool amoptionalkey
Definition: amapi.h:181
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:181
double allvisfrac
Definition: relation.h:626
signed int int32
Definition: c.h:246
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4776
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
TransactionId TransactionXmin
Definition: snapmgr.c:164
bool unique
Definition: relation.h:753
HeapTupleHeader t_data
Definition: htup.h:67
Definition: type.h:89
BlockNumber pages
Definition: relation.h:724
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:783
Form_pg_index rd_index
Definition: rel.h:159
RelOptInfo * rel
Definition: relation.h:721
bool amoptionalkey
Definition: relation.h:759
amgetbitmap_function amgetbitmap
Definition: amapi.h:211
Oid * rd_indcollation
Definition: rel.h:193
#define ERROR
Definition: elog.h:43
amcostestimate_function amcostestimate
Definition: amapi.h:204
#define NoLock
Definition: lockdefs.h:34
bool amcanorderbyop
Definition: relation.h:758
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4713
PlannerGlobal * glob
Definition: relation.h:157
#define RowExclusiveLock
Definition: lockdefs.h:38
struct FdwRoutine * fdwroutine
Definition: relation.h:636
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition: plancat.c:1824
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:57
Oid * rd_opfamily
Definition: rel.h:182
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:920
int ncolumns
Definition: relation.h:729
#define ereport(elevel, rest)
Definition: elog.h:122
bool amhasgetbitmap
Definition: relation.h:763
bool amcanparallel
Definition: amapi.h:193
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
Index relid
Definition: relation.h:613
Bitmapset * Relids
Definition: relation.h:28
Oid serverid
Definition: relation.h:632
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
bool amsearchnulls
Definition: amapi.h:185
List * indrestrictinfo
Definition: relation.h:746
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
void * palloc0(Size size)
Definition: mcxt.c:877
int rel_parallel_workers
Definition: relation.h:629
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
unsigned int Index
Definition: c.h:359
List * indexlist
Definition: relation.h:622
bool amsearcharray
Definition: amapi.h:183
bool amhasgettuple
Definition: relation.h:762
#define InvalidOid
Definition: postgres_ext.h:36
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:558
BlockNumber pages
Definition: relation.h:624
#define Assert(condition)
Definition: c.h:681
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:457
#define INDOPTION_DESC
Definition: pg_index.h:99
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:308
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:204
bool amsearcharray
Definition: relation.h:760
bool amcanorder
Definition: amapi.h:171
#define RelationNeedsWAL(relation)
Definition: rel.h:505
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4357
Oid * opcintype
Definition: relation.h:733
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
Oid * opfamily
Definition: relation.h:732
AttrNumber max_attr
Definition: relation.h:617
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
void list_free(List *list)
Definition: list.c:1133
int i
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:326
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1602
int * indexkeys
Definition: relation.h:730
Oid indexoid
Definition: relation.h:719
bool * canreturn
Definition: relation.h:737
bool amsearchnulls
Definition: relation.h:761
Oid * rd_opcintype
Definition: rel.h:183
void(* amcostestimate)()
Definition: relation.h:766
bool * nulls_first
Definition: relation.h:736
bool * reverse_sort
Definition: relation.h:735
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:742
int32 * attr_widths
Definition: relation.h:619
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
bool amcanparallel
Definition: relation.h:764
#define lfirst_oid(lc)
Definition: pg_list.h:108
List * indexprs
Definition: relation.h:741
bool transientPlan
Definition: relation.h:125
AttrNumber min_attr
Definition: relation.h:616
static List * get_relation_statistics ( RelOptInfo rel,
Relation  relation 
)
static

Definition at line 1282 of file plancat.c.

References bms_add_member(), bms_copy(), bms_free(), elog, ERROR, GETSTRUCT, i, StatisticExtInfo::keys, StatisticExtInfo::kind, lcons(), lfirst_oid, list_free(), makeNode, NIL, ObjectIdGetDatum, StatisticExtInfo::rel, RelationGetStatExtList(), ReleaseSysCache(), SearchSysCache1(), statext_is_kind_built(), STATEXTOID, StatisticExtInfo::statOid, STATS_EXT_DEPENDENCIES, and STATS_EXT_NDISTINCT.

Referenced by get_relation_info().

1283 {
1284  List *statoidlist;
1285  List *stainfos = NIL;
1286  ListCell *l;
1287 
1288  statoidlist = RelationGetStatExtList(relation);
1289 
1290  foreach(l, statoidlist)
1291  {
1292  Oid statOid = lfirst_oid(l);
1293  Form_pg_statistic_ext staForm;
1294  HeapTuple htup;
1295  Bitmapset *keys = NULL;
1296  int i;
1297 
1298  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1299  if (!htup)
1300  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1301  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1302 
1303  /*
1304  * First, build the array of columns covered. This is ultimately
1305  * wasted if no stats within the object have actually been built, but
1306  * it doesn't seem worth troubling over that case.
1307  */
1308  for (i = 0; i < staForm->stxkeys.dim1; i++)
1309  keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1310 
1311  /* add one StatisticExtInfo for each kind built */
1313  {
1315 
1316  info->statOid = statOid;
1317  info->rel = rel;
1318  info->kind = STATS_EXT_NDISTINCT;
1319  info->keys = bms_copy(keys);
1320 
1321  stainfos = lcons(info, stainfos);
1322  }
1323 
1325  {
1327 
1328  info->statOid = statOid;
1329  info->rel = rel;
1330  info->kind = STATS_EXT_DEPENDENCIES;
1331  info->keys = bms_copy(keys);
1332 
1333  stainfos = lcons(info, stainfos);
1334  }
1335 
1336  ReleaseSysCache(htup);
1337  bms_free(keys);
1338  }
1339 
1340  list_free(statoidlist);
1341 
1342  return stainfos;
1343 }
#define NIL
Definition: pg_list.h:69
#define STATS_EXT_NDISTINCT
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:111
bool statext_is_kind_built(HeapTuple htup, char type)
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
RelOptInfo * rel
Definition: relation.h:811
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
List * lcons(void *datum, List *list)
Definition: list.c:259
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define makeNode(_type_)
Definition: nodes.h:558
#define STATS_EXT_DEPENDENCIES
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4497
Bitmapset * keys
Definition: relation.h:813
void list_free(List *list)
Definition: list.c:1133
int i
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define lfirst_oid(lc)
Definition: pg_list.h:108
bool has_row_triggers ( PlannerInfo root,
Index  rti,
CmdType  event 
)

Definition at line 1778 of file plancat.c.

References CMD_DELETE, CMD_INSERT, CMD_UPDATE, elog, ERROR, heap_close, heap_open(), NoLock, planner_rt_fetch, RangeTblEntry::relid, 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().

1779 {
1780  RangeTblEntry *rte = planner_rt_fetch(rti, root);
1781  Relation relation;
1782  TriggerDesc *trigDesc;
1783  bool result = false;
1784 
1785  /* Assume we already have adequate lock */
1786  relation = heap_open(rte->relid, NoLock);
1787 
1788  trigDesc = relation->trigdesc;
1789  switch (event)
1790  {
1791  case CMD_INSERT:
1792  if (trigDesc &&
1793  (trigDesc->trig_insert_after_row ||
1794  trigDesc->trig_insert_before_row))
1795  result = true;
1796  break;
1797  case CMD_UPDATE:
1798  if (trigDesc &&
1799  (trigDesc->trig_update_after_row ||
1800  trigDesc->trig_update_before_row))
1801  result = true;
1802  break;
1803  case CMD_DELETE:
1804  if (trigDesc &&
1805  (trigDesc->trig_delete_after_row ||
1806  trigDesc->trig_delete_before_row))
1807  result = true;
1808  break;
1809  default:
1810  elog(ERROR, "unrecognized CmdType: %d", (int) event);
1811  break;
1812  }
1813 
1814  heap_close(relation, NoLock);
1815  return result;
1816 }
#define heap_close(r, l)
Definition: heapam.h:97
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:120
bool trig_delete_after_row
Definition: reltrigger.h:66
#define NoLock
Definition: lockdefs.h:34
bool trig_update_before_row
Definition: reltrigger.h:60
bool trig_insert_after_row
Definition: reltrigger.h:56
bool trig_update_after_row
Definition: reltrigger.h:61
bool trig_insert_before_row
Definition: reltrigger.h:55
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define elog
Definition: elog.h:219
bool trig_delete_before_row
Definition: reltrigger.h:65
bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 1746 of file plancat.c.

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

Referenced by examine_variable().

1747 {
1748  ListCell *ilist;
1749 
1750  foreach(ilist, rel->indexlist)
1751  {
1752  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1753 
1754  /*
1755  * Note: ignore partial indexes, since they don't allow us to conclude
1756  * that all attr values are distinct, *unless* they are marked predOK
1757  * which means we know the index's predicate is satisfied by the
1758  * query. We don't take any interest in expressional indexes either.
1759  * Also, a multicolumn unique index doesn't allow us to conclude that
1760  * just the specified attr is unique.
1761  */
1762  if (index->unique &&
1763  index->ncolumns == 1 &&
1764  index->indexkeys[0] == attno &&
1765  (index->indpred == NIL || index->predOK))
1766  return true;
1767  }
1768  return false;
1769 }
#define NIL
Definition: pg_list.h:69
bool predOK
Definition: relation.h:752
bool unique
Definition: relation.h:753
Definition: type.h:89
int ncolumns
Definition: relation.h:729
List * indexlist
Definition: relation.h:622
#define lfirst(lc)
Definition: pg_list.h:106
int * indexkeys
Definition: relation.h:730
List * indpred
Definition: relation.h:742
List* infer_arbiter_indexes ( PlannerInfo root)

Definition at line 570 of file plancat.c.

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, bms_add_member(), bms_equal(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, InferenceElem::expr, FirstLowInvalidHeapAttributeNumber, get_constraint_index(), heap_close, heap_open(), index_close(), index_open(), IndexIsValid, 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(), Query::resultRelation, RowExclusiveLock, rt_fetch, Query::rtable, and Var::varattno.

Referenced by make_modifytable().

571 {
572  OnConflictExpr *onconflict = root->parse->onConflict;
573 
574  /* Iteration state */
575  Relation relation;
576  Oid relationObjectId;
577  Oid indexOidFromConstraint = InvalidOid;
578  List *indexList;
579  ListCell *l;
580 
581  /* Normalized inference attributes and inference expressions: */
582  Bitmapset *inferAttrs = NULL;
583  List *inferElems = NIL;
584 
585  /* Results */
586  List *results = NIL;
587 
588  /*
589  * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
590  * specification or named constraint. ON CONFLICT DO UPDATE statements
591  * must always provide one or the other (but parser ought to have caught
592  * that already).
593  */
594  if (onconflict->arbiterElems == NIL &&
595  onconflict->constraint == InvalidOid)
596  return NIL;
597 
598  /*
599  * We need not lock the relation since it was already locked, either by
600  * the rewriter or when expand_inherited_rtentry() added it to the query's
601  * rangetable.
602  */
603  relationObjectId = rt_fetch(root->parse->resultRelation,
604  root->parse->rtable)->relid;
605 
606  relation = heap_open(relationObjectId, NoLock);
607 
608  /*
609  * Build normalized/BMS representation of plain indexed attributes, as
610  * well as a separate list of expression items. This simplifies matching
611  * the cataloged definition of indexes.
612  */
613  foreach(l, onconflict->arbiterElems)
614  {
615  InferenceElem *elem = (InferenceElem *) lfirst(l);
616  Var *var;
617  int attno;
618 
619  if (!IsA(elem->expr, Var))
620  {
621  /* If not a plain Var, just shove it in inferElems for now */
622  inferElems = lappend(inferElems, elem->expr);
623  continue;
624  }
625 
626  var = (Var *) elem->expr;
627  attno = var->varattno;
628 
629  if (attno == 0)
630  ereport(ERROR,
631  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
632  errmsg("whole row unique index inference specifications are not supported")));
633 
634  inferAttrs = bms_add_member(inferAttrs,
636  }
637 
638  /*
639  * Lookup named constraint's index. This is not immediately returned
640  * because some additional sanity checks are required.
641  */
642  if (onconflict->constraint != InvalidOid)
643  {
644  indexOidFromConstraint = get_constraint_index(onconflict->constraint);
645 
646  if (indexOidFromConstraint == InvalidOid)
647  ereport(ERROR,
648  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
649  errmsg("constraint in ON CONFLICT clause has no associated index")));
650  }
651 
652  /*
653  * Using that representation, iterate through the list of indexes on the
654  * target relation to try and find a match
655  */
656  indexList = RelationGetIndexList(relation);
657 
658  foreach(l, indexList)
659  {
660  Oid indexoid = lfirst_oid(l);
661  Relation idxRel;
662  Form_pg_index idxForm;
663  Bitmapset *indexedAttrs;
664  List *idxExprs;
665  List *predExprs;
666  AttrNumber natt;
667  ListCell *el;
668 
669  /*
670  * Extract info from the relation descriptor for the index. We know
671  * that this is a target, so get lock type it is known will ultimately
672  * be required by the executor.
673  *
674  * Let executor complain about !indimmediate case directly, because
675  * enforcement needs to occur there anyway when an inference clause is
676  * omitted.
677  */
678  idxRel = index_open(indexoid, RowExclusiveLock);
679  idxForm = idxRel->rd_index;
680 
681  if (!IndexIsValid(idxForm))
682  goto next;
683 
684  /*
685  * Note that we do not perform a check against indcheckxmin (like e.g.
686  * get_relation_info()) here to eliminate candidates, because
687  * uniqueness checking only cares about the most recently committed
688  * tuple versions.
689  */
690 
691  /*
692  * Look for match on "ON constraint_name" variant, which may not be
693  * unique constraint. This can only be a constraint name.
694  */
695  if (indexOidFromConstraint == idxForm->indexrelid)
696  {
697  if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
698  ereport(ERROR,
699  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
700  errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
701 
702  results = lappend_oid(results, idxForm->indexrelid);
703  list_free(indexList);
704  index_close(idxRel, NoLock);
705  heap_close(relation, NoLock);
706  return results;
707  }
708  else if (indexOidFromConstraint != InvalidOid)
709  {
710  /* No point in further work for index in named constraint case */
711  goto next;
712  }
713 
714  /*
715  * Only considering conventional inference at this point (not named
716  * constraints), so index under consideration can be immediately
717  * skipped if it's not unique
718  */
719  if (!idxForm->indisunique)
720  goto next;
721 
722  /* Build BMS representation of plain (non expression) index attrs */
723  indexedAttrs = NULL;
724  for (natt = 0; natt < idxForm->indnatts; natt++)
725  {
726  int attno = idxRel->rd_index->indkey.values[natt];
727 
728  if (attno != 0)
729  indexedAttrs = bms_add_member(indexedAttrs,
731  }
732 
733  /* Non-expression attributes (if any) must match */
734  if (!bms_equal(indexedAttrs, inferAttrs))
735  goto next;
736 
737  /* Expression attributes (if any) must match */
738  idxExprs = RelationGetIndexExpressions(idxRel);
739  foreach(el, onconflict->arbiterElems)
740  {
741  InferenceElem *elem = (InferenceElem *) lfirst(el);
742 
743  /*
744  * Ensure that collation/opclass aspects of inference expression
745  * element match. Even though this loop is primarily concerned
746  * with matching expressions, it is a convenient point to check
747  * this for both expressions and ordinary (non-expression)
748  * attributes appearing as inference elements.
749  */
750  if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
751  goto next;
752 
753  /*
754  * Plain Vars don't factor into count of expression elements, and
755  * the question of whether or not they satisfy the index
756  * definition has already been considered (they must).
757  */
758  if (IsA(elem->expr, Var))
759  continue;
760 
761  /*
762  * Might as well avoid redundant check in the rare cases where
763  * infer_collation_opclass_match() is required to do real work.
764  * Otherwise, check that element expression appears in cataloged
765  * index definition.
766  */
767  if (elem->infercollid != InvalidOid ||
768  elem->inferopclass != InvalidOid ||
769  list_member(idxExprs, elem->expr))
770  continue;
771 
772  goto next;
773  }
774 
775  /*
776  * Now that all inference elements were matched, ensure that the
777  * expression elements from inference clause are not missing any
778  * cataloged expressions. This does the right thing when unique
779  * indexes redundantly repeat the same attribute, or if attributes
780  * redundantly appear multiple times within an inference clause.
781  */
782  if (list_difference(idxExprs, inferElems) != NIL)
783  goto next;
784 
785  /*
786  * If it's a partial index, its predicate must be implied by the ON
787  * CONFLICT's WHERE clause.
788  */
789  predExprs = RelationGetIndexPredicate(idxRel);
790 
791  if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, false))
792  goto next;
793 
794  results = lappend_oid(results, idxForm->indexrelid);
795 next:
796  index_close(idxRel, NoLock);
797  }
798 
799  list_free(indexList);
800  heap_close(relation, NoLock);
801 
802  if (results == NIL)
803  ereport(ERROR,
804  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
805  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
806 
807  return results;
808 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Query * parse
Definition: relation.h:155
static int32 next
Definition: blutils.c:210
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
OnConflictExpr * onConflict
Definition: parsenodes.h:142
int resultRelation
Definition: parsenodes.h:120
static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel, List *idxExprs)
Definition: plancat.c:838
int errcode(int sqlerrcode)
Definition: elog.c:575
AttrNumber varattno
Definition: primnodes.h:168
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4776
List * arbiterElems
Definition: primnodes.h:1490
Form_pg_index rd_index
Definition: rel.h:159
List * rtable
Definition: parsenodes.h:135
#define ERROR
Definition: elog.h:43
bool list_member(const List *list, const void *datum)
Definition: list.c:444
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4713
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend(List *list, void *datum)
Definition: list.c:128
OnConflictAction action
Definition: primnodes.h:1487
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
List * list_difference(const List *list1, const List *list2)
Definition: list.c:858
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4357
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
Node * arbiterWhere
Definition: primnodes.h:1492
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
Oid get_constraint_index(Oid constraintId)
Definition: pg_depend.c:626
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define lfirst_oid(lc)
Definition: pg_list.h:108
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:131
static bool infer_collation_opclass_match ( InferenceElem elem,
Relation  idxRel,
List idxExprs 
)
static

Definition at line 838 of file plancat.c.

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

Referenced by infer_arbiter_indexes().

840 {
841  AttrNumber natt;
842  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
843  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
844  int nplain = 0; /* # plain attrs observed */
845 
846  /*
847  * If inference specification element lacks collation/opclass, then no
848  * need to check for exact match.
849  */
850  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
851  return true;
852 
853  /*
854  * Lookup opfamily and input type, for matching indexes
855  */
856  if (elem->inferopclass)
857  {
858  inferopfamily = get_opclass_family(elem->inferopclass);
859  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
860  }
861 
862  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
863  {
864  Oid opfamily = idxRel->rd_opfamily[natt - 1];
865  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
866  Oid collation = idxRel->rd_indcollation[natt - 1];
867  int attno = idxRel->rd_index->indkey.values[natt - 1];
868 
869  if (attno != 0)
870  nplain++;
871 
872  if (elem->inferopclass != InvalidOid &&
873  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
874  {
875  /* Attribute needed to match opclass, but didn't */
876  continue;
877  }
878 
879  if (elem->infercollid != InvalidOid &&
880  elem->infercollid != collation)
881  {
882  /* Attribute needed to match collation, but didn't */
883  continue;
884  }
885 
886  /* If one matching index att found, good enough -- return true */
887  if (IsA(elem->expr, Var))
888  {
889  if (((Var *) elem->expr)->varattno == attno)
890  return true;
891  }
892  else if (attno == 0)
893  {
894  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
895 
896  /*
897  * Note that unlike routines like match_index_to_operand() we
898  * don't need to care about RelabelType. Neither the index
899  * definition nor the inference clause should contain them.
900  */
901  if (equal(elem->expr, nattExpr))
902  return true;
903  }
904  }
905 
906  return false;
907 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2972
Definition: nodes.h:510
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
int natts
Definition: tupdesc.h:73
Form_pg_index rd_index
Definition: rel.h:159
Oid * rd_indcollation
Definition: rel.h:193
void * list_nth(const List *list, int n)
Definition: list.c:410
Oid * rd_opfamily
Definition: rel.h:182
TupleDesc rd_att
Definition: rel.h:115
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1047
Oid * rd_opcintype
Definition: rel.h:183
int16 AttrNumber
Definition: attnum.h:21
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1069
Selectivity join_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 1702 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1708 {
1709  RegProcedure oprjoin = get_oprjoin(operatorid);
1710  float8 result;
1711 
1712  /*
1713  * if the oprjoin procedure is missing for whatever reason, use a
1714  * selectivity of 0.5
1715  */
1716  if (!oprjoin)
1717  return (Selectivity) 0.5;
1718 
1719  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1720  inputcollid,
1721  PointerGetDatum(root),
1722  ObjectIdGetDatum(operatorid),
1723  PointerGetDatum(args),
1724  Int16GetDatum(jointype),
1725  PointerGetDatum(sjinfo)));
1726 
1727  if (result < 0.0 || result > 1.0)
1728  elog(ERROR, "invalid join selectivity: %f", result);
1729 
1730  return (Selectivity) result;
1731 }
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1385
#define PointerGetDatum(X)
Definition: postgres.h:562
regproc RegProcedure
Definition: c.h:389
#define Int16GetDatum(X)
Definition: postgres.h:457
double Selectivity
Definition: nodes.h:640
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:375
#define DatumGetFloat8(X)
Definition: postgres.h:734
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1420
#define elog
Definition: elog.h:219
bool relation_excluded_by_constraints ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)

Definition at line 1357 of file plancat.c.

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

Referenced by set_append_rel_size(), and set_rel_size().

1359 {
1360  List *safe_restrictions;
1361  List *constraint_pred;
1362  List *safe_constraints;
1363  ListCell *lc;
1364 
1365  /* As of now, constraint exclusion works only with simple relations. */
1366  Assert(IS_SIMPLE_REL(rel));
1367 
1368  /*
1369  * Regardless of the setting of constraint_exclusion, detect
1370  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1371  * reduce "anything AND FALSE" to just "FALSE", any such case should
1372  * result in exactly one baserestrictinfo entry. This doesn't fire very
1373  * often, but it seems cheap enough to be worth doing anyway. (Without
1374  * this, we'd miss some optimizations that 9.5 and earlier found via much
1375  * more roundabout methods.)
1376  */
1377  if (list_length(rel->baserestrictinfo) == 1)
1378  {
1380  Expr *clause = rinfo->clause;
1381 
1382  if (clause && IsA(clause, Const) &&
1383  (((Const *) clause)->constisnull ||
1384  !DatumGetBool(((Const *) clause)->constvalue)))
1385  return true;
1386  }
1387 
1388  /* Skip further tests if constraint exclusion is disabled for the rel */
1391  !(rel->reloptkind == RELOPT_OTHER_MEMBER_REL ||
1392  (root->hasInheritedTarget &&
1393  rel->reloptkind == RELOPT_BASEREL &&
1394  rel->relid == root->parse->resultRelation))))
1395  return false;
1396 
1397  /*
1398  * Check for self-contradictory restriction clauses. We dare not make
1399  * deductions with non-immutable functions, but any immutable clauses that
1400  * are self-contradictory allow us to conclude the scan is unnecessary.
1401  *
1402  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1403  * expecting to see any in its predicate argument.
1404  */
1405  safe_restrictions = NIL;
1406  foreach(lc, rel->baserestrictinfo)
1407  {
1408  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1409 
1410  if (!contain_mutable_functions((Node *) rinfo->clause))
1411  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1412  }
1413 
1414  if (predicate_refuted_by(safe_restrictions, safe_restrictions, false))
1415  return true;
1416 
1417  /* Only plain relations have constraints */
1418  if (rte->rtekind != RTE_RELATION || rte->inh)
1419  return false;
1420 
1421  /*
1422  * OK to fetch the constraint expressions. Include "col IS NOT NULL"
1423  * expressions for attnotnull columns, in case we can refute those.
1424  */
1425  constraint_pred = get_relation_constraints(root, rte->relid, rel, true);
1426 
1427  /*
1428  * We do not currently enforce that CHECK constraints contain only
1429  * immutable functions, so it's necessary to check here. We daren't draw
1430  * conclusions from plan-time evaluation of non-immutable functions. Since
1431  * they're ANDed, we can just ignore any mutable constraints in the list,
1432  * and reason about the rest.
1433  */
1434  safe_constraints = NIL;
1435  foreach(lc, constraint_pred)
1436  {
1437  Node *pred = (Node *) lfirst(lc);
1438 
1439  if (!contain_mutable_functions(pred))
1440  safe_constraints = lappend(safe_constraints, pred);
1441  }
1442 
1443  /*
1444  * The constraints are effectively ANDed together, so we can just try to
1445  * refute the entire collection at once. This may allow us to make proofs
1446  * that would fail if we took them individually.
1447  *
1448  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1449  * an obvious optimization. Some of the clauses might be OR clauses that
1450  * have volatile and nonvolatile subclauses, and it's OK to make
1451  * deductions with the nonvolatile parts.
1452  */
1453  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1454  return true;
1455 
1456  return false;
1457 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
Query * parse
Definition: relation.h:155
RelOptKind reloptkind
Definition: relation.h:582
List * baserestrictinfo
Definition: relation.h:645
int constraint_exclusion
Definition: plancat.c:54
int resultRelation
Definition: parsenodes.h:120
Definition: nodes.h:510
#define IS_SIMPLE_REL(rel)
Definition: relation.h:561
#define linitial(l)
Definition: pg_list.h:111
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:197
#define DatumGetBool(X)
Definition: postgres.h:399
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1835
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
bool hasInheritedTarget
Definition: relation.h:300
static int list_length(const List *l)
Definition: pg_list.h:89
RTEKind rtekind
Definition: parsenodes.h:945
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:878
Definition: pg_list.h:45
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
Definition: plancat.c:1156
Selectivity restriction_selectivity ( PlannerInfo root,
Oid  operatorid,
List args,
Oid  inputcollid,
int  varRelid 
)

Definition at line 1665 of file plancat.c.

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

Referenced by clause_selectivity(), and rowcomparesel().

1670 {
1671  RegProcedure oprrest = get_oprrest(operatorid);
1672  float8 result;
1673 
1674  /*
1675  * if the oprrest procedure is missing for whatever reason, use a
1676  * selectivity of 0.5
1677  */
1678  if (!oprrest)
1679  return (Selectivity) 0.5;
1680 
1681  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1682  inputcollid,
1683  PointerGetDatum(root),
1684  ObjectIdGetDatum(operatorid),
1685  PointerGetDatum(args),
1686  Int32GetDatum(varRelid)));
1687 
1688  if (result < 0.0 || result > 1.0)
1689  elog(ERROR, "invalid restriction selectivity: %f", result);
1690 
1691  return (Selectivity) result;
1692 }
#define PointerGetDatum(X)
Definition: postgres.h:562
regproc RegProcedure
Definition: c.h:389
double Selectivity
Definition: nodes.h:640
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:375
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1361
#define DatumGetFloat8(X)
Definition: postgres.h:734
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1390
#define Int32GetDatum(X)
Definition: postgres.h:485
#define elog
Definition: elog.h:219
static void set_baserel_partition_key_exprs ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 1935 of file plancat.c.

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

Referenced by set_relation_partition_info().

1937 {
1938  PartitionKey partkey = RelationGetPartitionKey(relation);
1939  int partnatts;
1940  int cnt;
1941  List **partexprs;
1942  ListCell *lc;
1943  Index varno = rel->relid;
1944 
1945  Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
1946 
1947  /* A partitioned table should have a partition key. */
1948  Assert(partkey != NULL);
1949 
1950  partnatts = partkey->partnatts;
1951  partexprs = (List **) palloc(sizeof(List *) * partnatts);
1952  lc = list_head(partkey->partexprs);
1953 
1954  for (cnt = 0; cnt < partnatts; cnt++)
1955  {
1956  Expr *partexpr;
1957  AttrNumber attno = partkey->partattrs[cnt];
1958 
1959  if (attno != InvalidAttrNumber)
1960  {
1961  /* Single column partition key is stored as a Var node. */
1962  Assert(attno > 0);
1963 
1964  partexpr = (Expr *) makeVar(varno, attno,
1965  partkey->parttypid[cnt],
1966  partkey->parttypmod[cnt],
1967  partkey->parttypcoll[cnt], 0);
1968  }
1969  else
1970  {
1971  if (lc == NULL)
1972  elog(ERROR, "wrong number of partition key expressions");
1973 
1974  /* Re-stamp the expression with given varno. */
1975  partexpr = (Expr *) copyObject(lfirst(lc));
1976  ChangeVarNodes((Node *) partexpr, 1, varno, 0);
1977  lc = lnext(lc);
1978  }
1979 
1980  partexprs[cnt] = list_make1(partexpr);
1981  }
1982 
1983  rel->partexprs = partexprs;
1984 
1985  /*
1986  * A base relation can not have nullable partition key expressions. We
1987  * still allocate array of empty expressions lists to keep partition key
1988  * expression handling code simple. See build_joinrel_partition_info() and
1989  * match_expr_to_partition_keys().
1990  */
1991  rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
1992 }
Definition: nodes.h:510
List * partexprs
Definition: rel.h:58
List ** nullable_partexprs
Definition: relation.h:663
#define IS_SIMPLE_REL(rel)
Definition: relation.h:561
#define list_make1(x1)
Definition: pg_list.h:139
Oid * parttypcoll
Definition: rel.h:74
List ** partexprs
Definition: relation.h:662
#define ERROR
Definition: elog.h:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Oid * parttypid
Definition: rel.h:69
Index relid
Definition: relation.h:613
void * palloc0(Size size)
Definition: mcxt.c:877
AttrNumber * partattrs
Definition: rel.h:56
int16 partnatts
Definition: rel.h:55
unsigned int Index
Definition: c.h:359
int32 * parttypmod
Definition: rel.h:70
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
#define RelationGetPartitionKey(relation)
Definition: rel.h:584
#define InvalidAttrNumber
Definition: attnum.h:23
void * palloc(Size size)
Definition: mcxt.c:848
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:623
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
static void set_relation_partition_info ( PlannerInfo root,
RelOptInfo rel,
Relation  relation 
)
static

Definition at line 1824 of file plancat.c.

References Assert, PartitionDescData::boundinfo, RelOptInfo::boundinfo, find_partition_scheme(), PartitionDescData::nparts, RelOptInfo::nparts, RelOptInfo::part_scheme, partition_bounds_copy(), RelationData::rd_rel, RelationGetPartitionDesc, RelationGetPartitionKey, RELKIND_PARTITIONED_TABLE, and set_baserel_partition_key_exprs().

Referenced by get_relation_info().

1826 {
1827  PartitionDesc partdesc;
1828  PartitionKey partkey;
1829 
1830  Assert(relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE);
1831 
1832  partdesc = RelationGetPartitionDesc(relation);
1833  partkey = RelationGetPartitionKey(relation);
1834  rel->part_scheme = find_partition_scheme(root, relation);
1835  Assert(partdesc != NULL && rel->part_scheme != NULL);
1836  rel->boundinfo = partition_bounds_copy(partdesc->boundinfo, partkey);
1837  rel->nparts = partdesc->nparts;
1838  set_baserel_partition_key_exprs(relation, rel);
1839 }
Form_pg_class rd_rel
Definition: rel.h:114
PartitionBoundInfo boundinfo
Definition: partition.h:37
int nparts
Definition: relation.h:658
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
struct PartitionBoundInfoData * boundinfo
Definition: relation.h:659
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation rel)
Definition: plancat.c:1847
#define Assert(condition)
Definition: c.h:681
#define RelationGetPartitionKey(relation)
Definition: rel.h:584
PartitionScheme part_scheme
Definition: relation.h:657
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:1935
PartitionBoundInfo partition_bounds_copy(PartitionBoundInfo src, PartitionKey key)
Definition: partition.c:709
#define RelationGetPartitionDesc(relation)
Definition: rel.h:632

Variable Documentation

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION

Definition at line 54 of file plancat.c.

Referenced by relation_excluded_by_constraints().

get_relation_info_hook_type get_relation_info_hook = NULL

Definition at line 57 of file plancat.c.

Referenced by get_relation_info().