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

Go to the source code of this file.

Functions

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

Variables

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION
 
get_relation_info_hook_type get_relation_info_hook = NULL
 

Function Documentation

◆ add_function_cost()

void add_function_cost ( PlannerInfo root,
Oid  funcid,
Node node,
QualCost cost 
)

Definition at line 2111 of file plancat.c.

2113{
2114 HeapTuple proctup;
2115 Form_pg_proc procform;
2116
2117 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2118 if (!HeapTupleIsValid(proctup))
2119 elog(ERROR, "cache lookup failed for function %u", funcid);
2120 procform = (Form_pg_proc) GETSTRUCT(proctup);
2121
2122 if (OidIsValid(procform->prosupport))
2123 {
2125 SupportRequestCost *sresult;
2126
2127 req.type = T_SupportRequestCost;
2128 req.root = root;
2129 req.funcid = funcid;
2130 req.node = node;
2131
2132 /* Initialize cost fields so that support function doesn't have to */
2133 req.startup = 0;
2134 req.per_tuple = 0;
2135
2136 sresult = (SupportRequestCost *)
2137 DatumGetPointer(OidFunctionCall1(procform->prosupport,
2138 PointerGetDatum(&req)));
2139
2140 if (sresult == &req)
2141 {
2142 /* Success, so accumulate support function's estimate into *cost */
2143 cost->startup += req.startup;
2144 cost->per_tuple += req.per_tuple;
2145 ReleaseSysCache(proctup);
2146 return;
2147 }
2148 }
2149
2150 /* No support function, or it failed, so rely on procost */
2151 cost->per_tuple += procform->procost * cpu_operator_cost;
2152
2153 ReleaseSysCache(proctup);
2154}
#define OidIsValid(objectId)
Definition: c.h:746
double cpu_operator_cost
Definition: costsize.c:134
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
tree ctl root
Definition: radixtree.h:1857
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47
struct PlannerInfo * root
Definition: supportnodes.h:136
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

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

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

◆ build_index_tlist()

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

Definition at line 1907 of file plancat.c.

1909{
1910 List *tlist = NIL;
1911 Index varno = index->rel->relid;
1912 ListCell *indexpr_item;
1913 int i;
1914
1915 indexpr_item = list_head(index->indexprs);
1916 for (i = 0; i < index->ncolumns; i++)
1917 {
1918 int indexkey = index->indexkeys[i];
1919 Expr *indexvar;
1920
1921 if (indexkey != 0)
1922 {
1923 /* simple column */
1924 const FormData_pg_attribute *att_tup;
1925
1926 if (indexkey < 0)
1927 att_tup = SystemAttributeDefinition(indexkey);
1928 else
1929 att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
1930
1931 indexvar = (Expr *) makeVar(varno,
1932 indexkey,
1933 att_tup->atttypid,
1934 att_tup->atttypmod,
1935 att_tup->attcollation,
1936 0);
1937 }
1938 else
1939 {
1940 /* expression column */
1941 if (indexpr_item == NULL)
1942 elog(ERROR, "wrong number of index expressions");
1943 indexvar = (Expr *) lfirst(indexpr_item);
1944 indexpr_item = lnext(index->indexprs, indexpr_item);
1945 }
1946
1947 tlist = lappend(tlist,
1948 makeTargetEntry(indexvar,
1949 i + 1,
1950 NULL,
1951 false));
1952 }
1953 if (indexpr_item != NULL)
1954 elog(ERROR, "wrong number of index expressions");
1955
1956 return tlist;
1957}
unsigned int Index
Definition: c.h:585
const FormData_pg_attribute * SystemAttributeDefinition(AttrNumber attno)
Definition: heap.c:236
int i
Definition: isn.c:77
List * lappend(List *list, void *datum)
Definition: list.c:339
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:289
FormData_pg_attribute
Definition: pg_attribute.h:186
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
Definition: pg_list.h:54
TupleDesc rd_att
Definition: rel.h:112
Definition: type.h:96
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160

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

Referenced by get_relation_info().

◆ build_physical_tlist()

List * build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 1786 of file plancat.c.

1787{
1788 List *tlist = NIL;
1789 Index varno = rel->relid;
1790 RangeTblEntry *rte = planner_rt_fetch(varno, root);
1791 Relation relation;
1792 Query *subquery;
1793 Var *var;
1794 ListCell *l;
1795 int attrno,
1796 numattrs;
1797 List *colvars;
1798
1799 switch (rte->rtekind)
1800 {
1801 case RTE_RELATION:
1802 /* Assume we already have adequate lock */
1803 relation = table_open(rte->relid, NoLock);
1804
1805 numattrs = RelationGetNumberOfAttributes(relation);
1806 for (attrno = 1; attrno <= numattrs; attrno++)
1807 {
1808 Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
1809 attrno - 1);
1810
1811 if (att_tup->attisdropped || att_tup->atthasmissing)
1812 {
1813 /* found a dropped or missing col, so punt */
1814 tlist = NIL;
1815 break;
1816 }
1817
1818 var = makeVar(varno,
1819 attrno,
1820 att_tup->atttypid,
1821 att_tup->atttypmod,
1822 att_tup->attcollation,
1823 0);
1824
1825 tlist = lappend(tlist,
1826 makeTargetEntry((Expr *) var,
1827 attrno,
1828 NULL,
1829 false));
1830 }
1831
1832 table_close(relation, NoLock);
1833 break;
1834
1835 case RTE_SUBQUERY:
1836 subquery = rte->subquery;
1837 foreach(l, subquery->targetList)
1838 {
1839 TargetEntry *tle = (TargetEntry *) lfirst(l);
1840
1841 /*
1842 * A resjunk column of the subquery can be reflected as
1843 * resjunk in the physical tlist; we need not punt.
1844 */
1845 var = makeVarFromTargetEntry(varno, tle);
1846
1847 tlist = lappend(tlist,
1848 makeTargetEntry((Expr *) var,
1849 tle->resno,
1850 NULL,
1851 tle->resjunk));
1852 }
1853 break;
1854
1855 case RTE_FUNCTION:
1856 case RTE_TABLEFUNC:
1857 case RTE_VALUES:
1858 case RTE_CTE:
1860 case RTE_RESULT:
1861 /* Not all of these can have dropped cols, but share code anyway */
1862 expandRTE(rte, varno, 0, VAR_RETURNING_DEFAULT, -1,
1863 true /* include dropped */ , NULL, &colvars);
1864 foreach(l, colvars)
1865 {
1866 var = (Var *) lfirst(l);
1867
1868 /*
1869 * A non-Var in expandRTE's output means a dropped column;
1870 * must punt.
1871 */
1872 if (!IsA(var, Var))
1873 {
1874 tlist = NIL;
1875 break;
1876 }
1877
1878 tlist = lappend(tlist,
1879 makeTargetEntry((Expr *) var,
1880 var->varattno,
1881 NULL,
1882 false));
1883 }
1884 break;
1885
1886 default:
1887 /* caller error */
1888 elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1889 (int) rte->rtekind);
1890 break;
1891 }
1892
1893 return tlist;
1894}
#define NoLock
Definition: lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:107
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, VarReturningType returning_type, int location, bool include_dropped, List **colnames, List **colvars)
@ RTE_CTE
Definition: parsenodes.h:1032
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1033
@ RTE_VALUES
Definition: parsenodes.h:1031
@ RTE_SUBQUERY
Definition: parsenodes.h:1027
@ RTE_RESULT
Definition: parsenodes.h:1034
@ RTE_FUNCTION
Definition: parsenodes.h:1029
@ RTE_TABLEFUNC
Definition: parsenodes.h:1030
@ RTE_RELATION
Definition: parsenodes.h:1026
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:597
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
@ VAR_RETURNING_DEFAULT
Definition: primnodes.h:256
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:522
List * targetList
Definition: parsenodes.h:193
Query * subquery
Definition: parsenodes.h:1118
RTEKind rtekind
Definition: parsenodes.h:1061
Index relid
Definition: pathnodes.h:945
AttrNumber resno
Definition: primnodes.h:2221
Definition: primnodes.h:262
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

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

Referenced by create_scan_plan().

◆ estimate_rel_size()

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

Definition at line 1069 of file plancat.c.

1071{
1072 BlockNumber curpages;
1073 BlockNumber relpages;
1074 double reltuples;
1075 BlockNumber relallvisible;
1076 double density;
1077
1078 if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
1079 {
1080 table_relation_estimate_size(rel, attr_widths, pages, tuples,
1081 allvisfrac);
1082 }
1083 else if (rel->rd_rel->relkind == RELKIND_INDEX)
1084 {
1085 /*
1086 * XXX: It'd probably be good to move this into a callback, individual
1087 * index types e.g. know if they have a metapage.
1088 */
1089
1090 /* it has storage, ok to call the smgr */
1091 curpages = RelationGetNumberOfBlocks(rel);
1092
1093 /* report estimated # pages */
1094 *pages = curpages;
1095 /* quick exit if rel is clearly empty */
1096 if (curpages == 0)
1097 {
1098 *tuples = 0;
1099 *allvisfrac = 0;
1100 return;
1101 }
1102
1103 /* coerce values in pg_class to more desirable types */
1104 relpages = (BlockNumber) rel->rd_rel->relpages;
1105 reltuples = (double) rel->rd_rel->reltuples;
1106 relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
1107
1108 /*
1109 * Discount the metapage while estimating the number of tuples. This
1110 * is a kluge because it assumes more than it ought to about index
1111 * structure. Currently it's OK for btree, hash, and GIN indexes but
1112 * suspect for GiST indexes.
1113 */
1114 if (relpages > 0)
1115 {
1116 curpages--;
1117 relpages--;
1118 }
1119
1120 /* estimate number of tuples from previous tuple density */
1121 if (reltuples >= 0 && relpages > 0)
1122 density = reltuples / (double) relpages;
1123 else
1124 {
1125 /*
1126 * If we have no data because the relation was never vacuumed,
1127 * estimate tuple width from attribute datatypes. We assume here
1128 * that the pages are completely full, which is OK for tables
1129 * (since they've presumably not been VACUUMed yet) but is
1130 * probably an overestimate for indexes. Fortunately
1131 * get_relation_info() can clamp the overestimate to the parent
1132 * table's size.
1133 *
1134 * Note: this code intentionally disregards alignment
1135 * considerations, because (a) that would be gilding the lily
1136 * considering how crude the estimate is, and (b) it creates
1137 * platform dependencies in the default plans which are kind of a
1138 * headache for regression testing.
1139 *
1140 * XXX: Should this logic be more index specific?
1141 */
1142 int32 tuple_width;
1143
1144 tuple_width = get_rel_data_width(rel, attr_widths);
1145 tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1146 tuple_width += sizeof(ItemIdData);
1147 /* note: integer division is intentional here */
1148 density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1149 }
1150 *tuples = rint(density * (double) curpages);
1151
1152 /*
1153 * We use relallvisible as-is, rather than scaling it up like we do
1154 * for the pages and tuples counts, on the theory that any pages added
1155 * since the last VACUUM are most likely not marked all-visible. But
1156 * costsize.c wants it converted to a fraction.
1157 */
1158 if (relallvisible == 0 || curpages <= 0)
1159 *allvisfrac = 0;
1160 else if ((double) relallvisible >= curpages)
1161 *allvisfrac = 1;
1162 else
1163 *allvisfrac = (double) relallvisible / curpages;
1164 }
1165 else
1166 {
1167 /*
1168 * Just use whatever's in pg_class. This covers foreign tables,
1169 * sequences, and also relkinds without storage (shouldn't get here?);
1170 * see initializations in AddNewRelationTuple(). Note that FDW must
1171 * cope if reltuples is -1!
1172 */
1173 *pages = rel->rd_rel->relpages;
1174 *tuples = rel->rd_rel->reltuples;
1175 *allvisfrac = 0;
1176 }
1177}
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:280
#define SizeOfPageHeaderData
Definition: bufpage.h:217
#define MAXALIGN(LEN)
Definition: c.h:782
int32_t int32
Definition: c.h:498
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
struct ItemIdData ItemIdData
int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1194
Form_pg_class rd_rel
Definition: rel.h:111
static void table_relation_estimate_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: tableam.h:1897

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

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

◆ find_partition_scheme()

static PartitionScheme find_partition_scheme ( PlannerInfo root,
Relation  relation 
)
static

Definition at line 2417 of file plancat.c.

2418{
2419 PartitionKey partkey = RelationGetPartitionKey(relation);
2420 ListCell *lc;
2421 int partnatts,
2422 i;
2423 PartitionScheme part_scheme;
2424
2425 /* A partitioned table should have a partition key. */
2426 Assert(partkey != NULL);
2427
2428 partnatts = partkey->partnatts;
2429
2430 /* Search for a matching partition scheme and return if found one. */
2431 foreach(lc, root->part_schemes)
2432 {
2433 part_scheme = lfirst(lc);
2434
2435 /* Match partitioning strategy and number of keys. */
2436 if (partkey->strategy != part_scheme->strategy ||
2437 partnatts != part_scheme->partnatts)
2438 continue;
2439
2440 /* Match partition key type properties. */
2441 if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2442 sizeof(Oid) * partnatts) != 0 ||
2443 memcmp(partkey->partopcintype, part_scheme->partopcintype,
2444 sizeof(Oid) * partnatts) != 0 ||
2445 memcmp(partkey->partcollation, part_scheme->partcollation,
2446 sizeof(Oid) * partnatts) != 0)
2447 continue;
2448
2449 /*
2450 * Length and byval information should match when partopcintype
2451 * matches.
2452 */
2453 Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2454 sizeof(int16) * partnatts) == 0);
2455 Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2456 sizeof(bool) * partnatts) == 0);
2457
2458 /*
2459 * If partopfamily and partopcintype matched, must have the same
2460 * partition comparison functions. Note that we cannot reliably
2461 * Assert the equality of function structs themselves for they might
2462 * be different across PartitionKey's, so just Assert for the function
2463 * OIDs.
2464 */
2465#ifdef USE_ASSERT_CHECKING
2466 for (i = 0; i < partkey->partnatts; i++)
2467 Assert(partkey->partsupfunc[i].fn_oid ==
2468 part_scheme->partsupfunc[i].fn_oid);
2469#endif
2470
2471 /* Found matching partition scheme. */
2472 return part_scheme;
2473 }
2474
2475 /*
2476 * Did not find matching partition scheme. Create one copying relevant
2477 * information from the relcache. We need to copy the contents of the
2478 * array since the relcache entry may not survive after we have closed the
2479 * relation.
2480 */
2481 part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
2482 part_scheme->strategy = partkey->strategy;
2483 part_scheme->partnatts = partkey->partnatts;
2484
2485 part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
2486 memcpy(part_scheme->partopfamily, partkey->partopfamily,
2487 sizeof(Oid) * partnatts);
2488
2489 part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
2490 memcpy(part_scheme->partopcintype, partkey->partopcintype,
2491 sizeof(Oid) * partnatts);
2492
2493 part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
2494 memcpy(part_scheme->partcollation, partkey->partcollation,
2495 sizeof(Oid) * partnatts);
2496
2497 part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
2498 memcpy(part_scheme->parttyplen, partkey->parttyplen,
2499 sizeof(int16) * partnatts);
2500
2501 part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
2502 memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2503 sizeof(bool) * partnatts);
2504
2505 part_scheme->partsupfunc = (FmgrInfo *)
2506 palloc(sizeof(FmgrInfo) * partnatts);
2507 for (i = 0; i < partnatts; i++)
2508 fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2510
2511 /* Add the partitioning scheme to PlannerInfo. */
2512 root->part_schemes = lappend(root->part_schemes, part_scheme);
2513
2514 return part_scheme;
2515}
int16_t int16
Definition: c.h:497
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:580
Assert(PointerIsAligned(start, uint64))
void * palloc0(Size size)
Definition: mcxt.c:1970
void * palloc(Size size)
Definition: mcxt.c:1940
MemoryContext CurrentMemoryContext
Definition: mcxt.c:159
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:51
struct PartitionSchemeData * PartitionScheme
Definition: pathnodes.h:631
unsigned int Oid
Definition: postgres_ext.h:30
Definition: fmgr.h:57
Oid fn_oid
Definition: fmgr.h:59
Oid * partcollation
Definition: partcache.h:39
Oid * partopfamily
Definition: partcache.h:34
bool * parttypbyval
Definition: partcache.h:45
PartitionStrategy strategy
Definition: partcache.h:27
int16 * parttyplen
Definition: partcache.h:44
FmgrInfo * partsupfunc
Definition: partcache.h:36
Oid * partopcintype
Definition: partcache.h:35
struct FmgrInfo * partsupfunc
Definition: pathnodes.h:628

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

Referenced by set_relation_partition_info().

◆ function_selectivity()

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

Definition at line 2049 of file plancat.c.

2057{
2058 RegProcedure prosupport = get_func_support(funcid);
2061
2062 /*
2063 * If no support function is provided, use our historical default
2064 * estimate, 0.3333333. This seems a pretty unprincipled choice, but
2065 * Postgres has been using that estimate for function calls since 1992.
2066 * The hoariness of this behavior suggests that we should not be in too
2067 * much hurry to use another value.
2068 */
2069 if (!prosupport)
2070 return (Selectivity) 0.3333333;
2071
2072 req.type = T_SupportRequestSelectivity;
2073 req.root = root;
2074 req.funcid = funcid;
2075 req.args = args;
2076 req.inputcollid = inputcollid;
2077 req.is_join = is_join;
2078 req.varRelid = varRelid;
2079 req.jointype = jointype;
2080 req.sjinfo = sjinfo;
2081 req.selectivity = -1; /* to catch failure to set the value */
2082
2083 sresult = (SupportRequestSelectivity *)
2085 PointerGetDatum(&req)));
2086
2087 /* If support function fails, use default */
2088 if (sresult != &req)
2089 return (Selectivity) 0.3333333;
2090
2091 if (req.selectivity < 0.0 || req.selectivity > 1.0)
2092 elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2093
2094 return (Selectivity) req.selectivity;
2095}
regproc RegProcedure
Definition: c.h:621
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1998
double Selectivity
Definition: nodes.h:256
struct PlannerInfo * root
Definition: supportnodes.h:96
struct SpecialJoinInfo * sjinfo
Definition: supportnodes.h:103

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

Referenced by clause_selectivity_ext().

◆ get_dependent_generated_columns()

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

Definition at line 2339 of file plancat.c.

2341{
2342 Bitmapset *dependentCols = NULL;
2343 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2344 Relation relation;
2345 TupleDesc tupdesc;
2346 TupleConstr *constr;
2347
2348 /* Assume we already have adequate lock */
2349 relation = table_open(rte->relid, NoLock);
2350
2351 tupdesc = RelationGetDescr(relation);
2352 constr = tupdesc->constr;
2353
2354 if (constr && constr->has_generated_stored)
2355 {
2356 for (int i = 0; i < constr->num_defval; i++)
2357 {
2358 AttrDefault *defval = &constr->defval[i];
2359 Node *expr;
2360 Bitmapset *attrs_used = NULL;
2361
2362 /* skip if not generated column */
2363 if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
2364 continue;
2365
2366 /* identify columns this generated column depends on */
2367 expr = stringToNode(defval->adbin);
2368 pull_varattnos(expr, 1, &attrs_used);
2369
2370 if (bms_overlap(target_cols, attrs_used))
2371 dependentCols = bms_add_member(dependentCols,
2373 }
2374 }
2375
2376 table_close(relation, NoLock);
2377
2378 return dependentCols;
2379}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetDescr(relation)
Definition: rel.h:542
AttrNumber adnum
Definition: tupdesc.h:24
char * adbin
Definition: tupdesc.h:25
Definition: nodes.h:135
AttrDefault * defval
Definition: tupdesc.h:40
bool has_generated_stored
Definition: tupdesc.h:46
uint16 num_defval
Definition: tupdesc.h:43
TupleConstr * constr
Definition: tupdesc.h:141
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:296

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

Referenced by get_rel_all_updated_cols().

◆ get_function_rows()

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

Definition at line 2172 of file plancat.c.

2173{
2174 HeapTuple proctup;
2175 Form_pg_proc procform;
2176 double result;
2177
2178 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2179 if (!HeapTupleIsValid(proctup))
2180 elog(ERROR, "cache lookup failed for function %u", funcid);
2181 procform = (Form_pg_proc) GETSTRUCT(proctup);
2182
2183 Assert(procform->proretset); /* else caller error */
2184
2185 if (OidIsValid(procform->prosupport))
2186 {
2188 SupportRequestRows *sresult;
2189
2190 req.type = T_SupportRequestRows;
2191 req.root = root;
2192 req.funcid = funcid;
2193 req.node = node;
2194
2195 req.rows = 0; /* just for sanity */
2196
2197 sresult = (SupportRequestRows *)
2198 DatumGetPointer(OidFunctionCall1(procform->prosupport,
2199 PointerGetDatum(&req)));
2200
2201 if (sresult == &req)
2202 {
2203 /* Success */
2204 ReleaseSysCache(proctup);
2205 return req.rows;
2206 }
2207 }
2208
2209 /* No support function, or it failed, so rely on prorows */
2210 result = procform->prorows;
2211
2212 ReleaseSysCache(proctup);
2213
2214 return result;
2215}
struct PlannerInfo * root
Definition: supportnodes.h:163

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

Referenced by expression_returns_set_rows().

◆ get_rel_data_width()

int32 get_rel_data_width ( Relation  rel,
int32 attr_widths 
)

Definition at line 1194 of file plancat.c.

1195{
1196 int64 tuple_width = 0;
1197 int i;
1198
1199 for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1200 {
1201 Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1202 int32 item_width;
1203
1204 if (att->attisdropped)
1205 continue;
1206
1207 /* use previously cached data, if any */
1208 if (attr_widths != NULL && attr_widths[i] > 0)
1209 {
1210 tuple_width += attr_widths[i];
1211 continue;
1212 }
1213
1214 /* This should match set_rel_width() in costsize.c */
1215 item_width = get_attavgwidth(RelationGetRelid(rel), i);
1216 if (item_width <= 0)
1217 {
1218 item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1219 Assert(item_width > 0);
1220 }
1221 if (attr_widths != NULL)
1222 attr_widths[i] = item_width;
1223 tuple_width += item_width;
1224 }
1225
1226 return clamp_width_est(tuple_width);
1227}
int64_t int64
Definition: c.h:499
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:242
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3298
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2718
#define RelationGetRelid(relation)
Definition: rel.h:516

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

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

◆ get_relation_constraints()

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

Definition at line 1277 of file plancat.c.

1282{
1283 List *result = NIL;
1284 Index varno = rel->relid;
1285 Relation relation;
1286 TupleConstr *constr;
1287
1288 /*
1289 * We assume the relation has already been safely locked.
1290 */
1291 relation = table_open(relationObjectId, NoLock);
1292
1293 constr = relation->rd_att->constr;
1294 if (constr != NULL)
1295 {
1296 int num_check = constr->num_check;
1297 int i;
1298
1299 for (i = 0; i < num_check; i++)
1300 {
1301 Node *cexpr;
1302
1303 /*
1304 * If this constraint hasn't been fully validated yet, we must
1305 * ignore it here.
1306 */
1307 if (!constr->check[i].ccvalid)
1308 continue;
1309
1310 /*
1311 * NOT ENFORCED constraints are always marked as invalid, which
1312 * should have been ignored.
1313 */
1314 Assert(constr->check[i].ccenforced);
1315
1316 /*
1317 * Also ignore if NO INHERIT and we weren't told that that's safe.
1318 */
1319 if (constr->check[i].ccnoinherit && !include_noinherit)
1320 continue;
1321
1322 cexpr = stringToNode(constr->check[i].ccbin);
1323
1324 /*
1325 * Run each expression through const-simplification and
1326 * canonicalization. This is not just an optimization, but is
1327 * necessary, because we will be comparing it to
1328 * similarly-processed qual clauses, and may fail to detect valid
1329 * matches without this. This must match the processing done to
1330 * qual clauses in preprocess_expression()! (We can skip the
1331 * stuff involving subqueries, however, since we don't allow any
1332 * in check constraints.)
1333 */
1334 cexpr = eval_const_expressions(root, cexpr);
1335
1336 cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1337
1338 /* Fix Vars to have the desired varno */
1339 if (varno != 1)
1340 ChangeVarNodes(cexpr, 1, varno, 0);
1341
1342 /*
1343 * Finally, convert to implicit-AND format (that is, a List) and
1344 * append the resulting item(s) to our output list.
1345 */
1346 result = list_concat(result,
1347 make_ands_implicit((Expr *) cexpr));
1348 }
1349
1350 /* Add NOT NULL constraints in expression form, if requested */
1351 if (include_notnull && constr->has_not_null)
1352 {
1353 int natts = relation->rd_att->natts;
1354
1355 for (i = 1; i <= natts; i++)
1356 {
1357 CompactAttribute *att = TupleDescCompactAttr(relation->rd_att, i - 1);
1358
1359 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
1360 {
1361 Form_pg_attribute wholeatt = TupleDescAttr(relation->rd_att, i - 1);
1362 NullTest *ntest = makeNode(NullTest);
1363
1364 ntest->arg = (Expr *) makeVar(varno,
1365 i,
1366 wholeatt->atttypid,
1367 wholeatt->atttypmod,
1368 wholeatt->attcollation,
1369 0);
1370 ntest->nulltesttype = IS_NOT_NULL;
1371
1372 /*
1373 * argisrow=false is correct even for a composite column,
1374 * because attnotnull does not represent a SQL-spec IS NOT
1375 * NULL test in such a case, just IS DISTINCT FROM NULL.
1376 */
1377 ntest->argisrow = false;
1378 ntest->location = -1;
1379 result = lappend(result, ntest);
1380 }
1381 }
1382 }
1383 }
1384
1385 /*
1386 * Add partitioning constraints, if requested.
1387 */
1388 if (include_partition && relation->rd_rel->relispartition)
1389 {
1390 /* make sure rel->partition_qual is set */
1391 set_baserel_partition_constraint(relation, rel);
1392 result = list_concat(result, rel->partition_qual);
1393 }
1394
1395 table_close(relation, NoLock);
1396
1397 return result;
1398}
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2256
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:810
#define makeNode(_type_)
Definition: nodes.h:161
static void set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2592
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:293
@ IS_NOT_NULL
Definition: primnodes.h:1957
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:793
bool attisdropped
Definition: tupdesc.h:77
char attnullability
Definition: tupdesc.h:79
bool ccenforced
Definition: tupdesc.h:32
bool ccnoinherit
Definition: tupdesc.h:34
bool ccvalid
Definition: tupdesc.h:33
char * ccbin
Definition: tupdesc.h:31
NullTestType nulltesttype
Definition: primnodes.h:1964
ParseLoc location
Definition: primnodes.h:1967
Expr * arg
Definition: primnodes.h:1963
List * partition_qual
Definition: pathnodes.h:1054
bool has_not_null
Definition: tupdesc.h:45
ConstrCheck * check
Definition: tupdesc.h:41
uint16 num_check
Definition: tupdesc.h:44
#define ATTNULLABLE_VALID
Definition: tupdesc.h:86
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175

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

Referenced by relation_excluded_by_constraints().

◆ get_relation_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)

Definition at line 1236 of file plancat.c.

1237{
1238 int32 result;
1239 Relation relation;
1240
1241 /* As above, assume relation is already locked */
1242 relation = table_open(relid, NoLock);
1243
1244 result = get_rel_data_width(relation, attr_widths);
1245
1246 table_close(relation, NoLock);
1247
1248 return result;
1249}

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

◆ get_relation_foreign_keys()

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

Definition at line 588 of file plancat.c.

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

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

Referenced by get_relation_info().

◆ get_relation_info()

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

Definition at line 116 of file plancat.c.

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

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

Referenced by build_simple_rel().

◆ get_relation_statistics()

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

Definition at line 1490 of file plancat.c.

1491{
1492 Index varno = rel->relid;
1493 List *statoidlist;
1494 List *stainfos = NIL;
1495 ListCell *l;
1496
1497 statoidlist = RelationGetStatExtList(relation);
1498
1499 foreach(l, statoidlist)
1500 {
1501 Oid statOid = lfirst_oid(l);
1502 Form_pg_statistic_ext staForm;
1503 HeapTuple htup;
1504 Bitmapset *keys = NULL;
1505 List *exprs = NIL;
1506 int i;
1507
1508 htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1509 if (!HeapTupleIsValid(htup))
1510 elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1511 staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1512
1513 /*
1514 * First, build the array of columns covered. This is ultimately
1515 * wasted if no stats within the object have actually been built, but
1516 * it doesn't seem worth troubling over that case.
1517 */
1518 for (i = 0; i < staForm->stxkeys.dim1; i++)
1519 keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1520
1521 /*
1522 * Preprocess expressions (if any). We read the expressions, run them
1523 * through eval_const_expressions, and fix the varnos.
1524 *
1525 * XXX We don't know yet if there are any data for this stats object,
1526 * with either stxdinherit value. But it's reasonable to assume there
1527 * is at least one of those, possibly both. So it's better to process
1528 * keys and expressions here.
1529 */
1530 {
1531 bool isnull;
1532 Datum datum;
1533
1534 /* decode expression (if any) */
1535 datum = SysCacheGetAttr(STATEXTOID, htup,
1536 Anum_pg_statistic_ext_stxexprs, &isnull);
1537
1538 if (!isnull)
1539 {
1540 char *exprsString;
1541
1542 exprsString = TextDatumGetCString(datum);
1543 exprs = (List *) stringToNode(exprsString);
1544 pfree(exprsString);
1545
1546 /*
1547 * Run the expressions through eval_const_expressions. This is
1548 * not just an optimization, but is necessary, because the
1549 * planner will be comparing them to similarly-processed qual
1550 * clauses, and may fail to detect valid matches without this.
1551 * We must not use canonicalize_qual, however, since these
1552 * aren't qual expressions.
1553 */
1554 exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
1555
1556 /* May as well fix opfuncids too */
1557 fix_opfuncids((Node *) exprs);
1558
1559 /*
1560 * Modify the copies we obtain from the relcache to have the
1561 * correct varno for the parent relation, so that they match
1562 * up correctly against qual clauses.
1563 */
1564 if (varno != 1)
1565 ChangeVarNodes((Node *) exprs, 1, varno, 0);
1566 }
1567 }
1568
1569 /* extract statistics for possible values of stxdinherit flag */
1570
1571 get_relation_statistics_worker(&stainfos, rel, statOid, true, keys, exprs);
1572
1573 get_relation_statistics_worker(&stainfos, rel, statOid, false, keys, exprs);
1574
1575 ReleaseSysCache(htup);
1576 bms_free(keys);
1577 }
1578
1579 list_free(statoidlist);
1580
1581 return stainfos;
1582}
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
#define TextDatumGetCString(d)
Definition: builtins.h:98
void pfree(void *pointer)
Definition: mcxt.c:2147
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1841
FormData_pg_statistic_ext * Form_pg_statistic_ext
static void get_relation_statistics_worker(List **stainfos, RelOptInfo *rel, Oid statOid, bool inh, Bitmapset *keys, List *exprs)
Definition: plancat.c:1407
uintptr_t Datum
Definition: postgres.h:69
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4960
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600

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

Referenced by get_relation_info().

◆ get_relation_statistics_worker()

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

Definition at line 1407 of file plancat.c.

1410{
1412 HeapTuple dtup;
1413
1414 dtup = SearchSysCache2(STATEXTDATASTXOID,
1415 ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1416 if (!HeapTupleIsValid(dtup))
1417 return;
1418
1419 dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
1420
1421 /* add one StatisticExtInfo for each kind built */
1422 if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1423 {
1425
1426 info->statOid = statOid;
1427 info->inherit = dataForm->stxdinherit;
1428 info->rel = rel;
1429 info->kind = STATS_EXT_NDISTINCT;
1430 info->keys = bms_copy(keys);
1431 info->exprs = exprs;
1432
1433 *stainfos = lappend(*stainfos, info);
1434 }
1435
1436 if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1437 {
1439
1440 info->statOid = statOid;
1441 info->inherit = dataForm->stxdinherit;
1442 info->rel = rel;
1443 info->kind = STATS_EXT_DEPENDENCIES;
1444 info->keys = bms_copy(keys);
1445 info->exprs = exprs;
1446
1447 *stainfos = lappend(*stainfos, info);
1448 }
1449
1450 if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1451 {
1453
1454 info->statOid = statOid;
1455 info->inherit = dataForm->stxdinherit;
1456 info->rel = rel;
1457 info->kind = STATS_EXT_MCV;
1458 info->keys = bms_copy(keys);
1459 info->exprs = exprs;
1460
1461 *stainfos = lappend(*stainfos, info);
1462 }
1463
1464 if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
1465 {
1467
1468 info->statOid = statOid;
1469 info->inherit = dataForm->stxdinherit;
1470 info->rel = rel;
1471 info->kind = STATS_EXT_EXPRESSIONS;
1472 info->keys = bms_copy(keys);
1473 info->exprs = exprs;
1474
1475 *stainfos = lappend(*stainfos, info);
1476 }
1477
1478 ReleaseSysCache(dtup);
1479}
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
bool statext_is_kind_built(HeapTuple htup, char type)
FormData_pg_statistic_ext_data * Form_pg_statistic_ext_data
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
Bitmapset * keys
Definition: pathnodes.h:1320
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:232

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

Referenced by get_relation_statistics().

◆ has_row_triggers()

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

Definition at line 2262 of file plancat.c.

2263{
2264 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2265 Relation relation;
2266 TriggerDesc *trigDesc;
2267 bool result = false;
2268
2269 /* Assume we already have adequate lock */
2270 relation = table_open(rte->relid, NoLock);
2271
2272 trigDesc = relation->trigdesc;
2273 switch (event)
2274 {
2275 case CMD_INSERT:
2276 if (trigDesc &&
2277 (trigDesc->trig_insert_after_row ||
2278 trigDesc->trig_insert_before_row))
2279 result = true;
2280 break;
2281 case CMD_UPDATE:
2282 if (trigDesc &&
2283 (trigDesc->trig_update_after_row ||
2284 trigDesc->trig_update_before_row))
2285 result = true;
2286 break;
2287 case CMD_DELETE:
2288 if (trigDesc &&
2289 (trigDesc->trig_delete_after_row ||
2290 trigDesc->trig_delete_before_row))
2291 result = true;
2292 break;
2293 /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2294 case CMD_MERGE:
2295 result = false;
2296 break;
2297 default:
2298 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2299 break;
2300 }
2301
2302 table_close(relation, NoLock);
2303 return result;
2304}
@ CMD_MERGE
Definition: nodes.h:275
@ CMD_INSERT
Definition: nodes.h:273
@ CMD_DELETE
Definition: nodes.h:274
@ CMD_UPDATE
Definition: nodes.h:272
TriggerDesc * trigdesc
Definition: rel.h:117
bool trig_delete_before_row
Definition: reltrigger.h:66
bool trig_update_after_row
Definition: reltrigger.h:62
bool trig_insert_after_row
Definition: reltrigger.h:57
bool trig_update_before_row
Definition: reltrigger.h:61
bool trig_delete_after_row
Definition: reltrigger.h:67
bool trig_insert_before_row
Definition: reltrigger.h:56

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

Referenced by make_modifytable().

◆ has_stored_generated_columns()

bool has_stored_generated_columns ( PlannerInfo root,
Index  rti 
)

Definition at line 2312 of file plancat.c.

2313{
2314 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2315 Relation relation;
2316 TupleDesc tupdesc;
2317 bool result = false;
2318
2319 /* Assume we already have adequate lock */
2320 relation = table_open(rte->relid, NoLock);
2321
2322 tupdesc = RelationGetDescr(relation);
2323 result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2324
2325 table_close(relation, NoLock);
2326
2327 return result;
2328}

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

Referenced by make_modifytable().

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2230 of file plancat.c.

2231{
2232 ListCell *ilist;
2233
2234 foreach(ilist, rel->indexlist)
2235 {
2236 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2237
2238 /*
2239 * Note: ignore partial indexes, since they don't allow us to conclude
2240 * that all attr values are distinct, *unless* they are marked predOK
2241 * which means we know the index's predicate is satisfied by the
2242 * query. We don't take any interest in expressional indexes either.
2243 * Also, a multicolumn unique index doesn't allow us to conclude that
2244 * just the specified attr is unique.
2245 */
2246 if (index->unique &&
2247 index->nkeycolumns == 1 &&
2248 index->indexkeys[0] == attno &&
2249 (index->indpred == NIL || index->predOK))
2250 return true;
2251 }
2252 return false;
2253}

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List * infer_arbiter_indexes ( PlannerInfo root)

Definition at line 707 of file plancat.c.

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

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

Referenced by make_modifytable().

◆ infer_collation_opclass_match()

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

Definition at line 987 of file plancat.c.

989{
990 AttrNumber natt;
991 Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
992 Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
993 int nplain = 0; /* # plain attrs observed */
994
995 /*
996 * If inference specification element lacks collation/opclass, then no
997 * need to check for exact match.
998 */
999 if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
1000 return true;
1001
1002 /*
1003 * Lookup opfamily and input type, for matching indexes
1004 */
1005 if (elem->inferopclass)
1006 {
1007 inferopfamily = get_opclass_family(elem->inferopclass);
1008 inferopcinputtype = get_opclass_input_type(elem->inferopclass);
1009 }
1010
1011 for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
1012 {
1013 Oid opfamily = idxRel->rd_opfamily[natt - 1];
1014 Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
1015 Oid collation = idxRel->rd_indcollation[natt - 1];
1016 int attno = idxRel->rd_index->indkey.values[natt - 1];
1017
1018 if (attno != 0)
1019 nplain++;
1020
1021 if (elem->inferopclass != InvalidOid &&
1022 (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
1023 {
1024 /* Attribute needed to match opclass, but didn't */
1025 continue;
1026 }
1027
1028 if (elem->infercollid != InvalidOid &&
1029 elem->infercollid != collation)
1030 {
1031 /* Attribute needed to match collation, but didn't */
1032 continue;
1033 }
1034
1035 /* If one matching index att found, good enough -- return true */
1036 if (IsA(elem->expr, Var))
1037 {
1038 if (((Var *) elem->expr)->varattno == attno)
1039 return true;
1040 }
1041 else if (attno == 0)
1042 {
1043 Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
1044
1045 /*
1046 * Note that unlike routines like match_index_to_operand() we
1047 * don't need to care about RelabelType. Neither the index
1048 * definition nor the inference clause should contain them.
1049 */
1050 if (equal(elem->expr, nattExpr))
1051 return true;
1052 }
1053 }
1054
1055 return false;
1056}
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1304
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1282
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299

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

Referenced by infer_arbiter_indexes().

◆ join_selectivity()

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

Definition at line 2008 of file plancat.c.

2014{
2015 RegProcedure oprjoin = get_oprjoin(operatorid);
2016 float8 result;
2017
2018 /*
2019 * if the oprjoin procedure is missing for whatever reason, use a
2020 * selectivity of 0.5
2021 */
2022 if (!oprjoin)
2023 return (Selectivity) 0.5;
2024
2025 result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
2026 inputcollid,
2028 ObjectIdGetDatum(operatorid),
2030 Int16GetDatum(jointype),
2031 PointerGetDatum(sjinfo)));
2032
2033 if (result < 0.0 || result > 1.0)
2034 elog(ERROR, "invalid join selectivity: %f", result);
2035
2036 return (Selectivity) result;
2037}
double float8
Definition: c.h:601
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1453
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1721
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:177
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:499

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

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

◆ relation_excluded_by_constraints()

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

Definition at line 1596 of file plancat.c.

1598{
1599 bool include_noinherit;
1600 bool include_notnull;
1601 bool include_partition = false;
1602 List *safe_restrictions;
1603 List *constraint_pred;
1604 List *safe_constraints;
1605 ListCell *lc;
1606
1607 /* As of now, constraint exclusion works only with simple relations. */
1608 Assert(IS_SIMPLE_REL(rel));
1609
1610 /*
1611 * If there are no base restriction clauses, we have no hope of proving
1612 * anything below, so fall out quickly.
1613 */
1614 if (rel->baserestrictinfo == NIL)
1615 return false;
1616
1617 /*
1618 * Regardless of the setting of constraint_exclusion, detect
1619 * constant-FALSE-or-NULL restriction clauses. Although const-folding
1620 * will reduce "anything AND FALSE" to just "FALSE", the baserestrictinfo
1621 * list can still have other members besides the FALSE constant, due to
1622 * qual pushdown and other mechanisms; so check them all. This doesn't
1623 * fire very often, but it seems cheap enough to be worth doing anyway.
1624 * (Without this, we'd miss some optimizations that 9.5 and earlier found
1625 * via much more roundabout methods.)
1626 */
1627 foreach(lc, rel->baserestrictinfo)
1628 {
1629 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1630 Expr *clause = rinfo->clause;
1631
1632 if (clause && IsA(clause, Const) &&
1633 (((Const *) clause)->constisnull ||
1634 !DatumGetBool(((Const *) clause)->constvalue)))
1635 return true;
1636 }
1637
1638 /*
1639 * Skip further tests, depending on constraint_exclusion.
1640 */
1641 switch (constraint_exclusion)
1642 {
1644 /* In 'off' mode, never make any further tests */
1645 return false;
1646
1648
1649 /*
1650 * When constraint_exclusion is set to 'partition' we only handle
1651 * appendrel members. Partition pruning has already been applied,
1652 * so there is no need to consider the rel's partition constraints
1653 * here.
1654 */
1656 break; /* appendrel member, so process it */
1657 return false;
1658
1660
1661 /*
1662 * In 'on' mode, always apply constraint exclusion. If we are
1663 * considering a baserel that is a partition (i.e., it was
1664 * directly named rather than expanded from a parent table), then
1665 * its partition constraints haven't been considered yet, so
1666 * include them in the processing here.
1667 */
1668 if (rel->reloptkind == RELOPT_BASEREL)
1669 include_partition = true;
1670 break; /* always try to exclude */
1671 }
1672
1673 /*
1674 * Check for self-contradictory restriction clauses. We dare not make
1675 * deductions with non-immutable functions, but any immutable clauses that
1676 * are self-contradictory allow us to conclude the scan is unnecessary.
1677 *
1678 * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1679 * expecting to see any in its predicate argument.
1680 */
1681 safe_restrictions = NIL;
1682 foreach(lc, rel->baserestrictinfo)
1683 {
1684 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1685
1686 if (!contain_mutable_functions((Node *) rinfo->clause))
1687 safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1688 }
1689
1690 /*
1691 * We can use weak refutation here, since we're comparing restriction
1692 * clauses with restriction clauses.
1693 */
1694 if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1695 return true;
1696
1697 /*
1698 * Only plain relations have constraints, so stop here for other rtekinds.
1699 */
1700 if (rte->rtekind != RTE_RELATION)
1701 return false;
1702
1703 /*
1704 * If we are scanning just this table, we can use NO INHERIT constraints,
1705 * but not if we're scanning its children too. (Note that partitioned
1706 * tables should never have NO INHERIT constraints; but it's not necessary
1707 * for us to assume that here.)
1708 */
1709 include_noinherit = !rte->inh;
1710
1711 /*
1712 * Currently, attnotnull constraints must be treated as NO INHERIT unless
1713 * this is a partitioned table. In future we might track their
1714 * inheritance status more accurately, allowing this to be refined.
1715 *
1716 * XXX do we need/want to change this?
1717 */
1718 include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
1719
1720 /*
1721 * Fetch the appropriate set of constraint expressions.
1722 */
1723 constraint_pred = get_relation_constraints(root, rte->relid, rel,
1724 include_noinherit,
1725 include_notnull,
1726 include_partition);
1727
1728 /*
1729 * We do not currently enforce that CHECK constraints contain only
1730 * immutable functions, so it's necessary to check here. We daren't draw
1731 * conclusions from plan-time evaluation of non-immutable functions. Since
1732 * they're ANDed, we can just ignore any mutable constraints in the list,
1733 * and reason about the rest.
1734 */
1735 safe_constraints = NIL;
1736 foreach(lc, constraint_pred)
1737 {
1738 Node *pred = (Node *) lfirst(lc);
1739
1740 if (!contain_mutable_functions(pred))
1741 safe_constraints = lappend(safe_constraints, pred);
1742 }
1743
1744 /*
1745 * The constraints are effectively ANDed together, so we can just try to
1746 * refute the entire collection at once. This may allow us to make proofs
1747 * that would fail if we took them individually.
1748 *
1749 * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1750 * an obvious optimization. Some of the clauses might be OR clauses that
1751 * have volatile and nonvolatile subclauses, and it's OK to make
1752 * deductions with the nonvolatile parts.
1753 *
1754 * We need strong refutation because we have to prove that the constraints
1755 * would yield false, not just NULL.
1756 */
1757 if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1758 return true;
1759
1760 return false;
1761}
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:371
@ CONSTRAINT_EXCLUSION_OFF
Definition: cost.h:38
@ CONSTRAINT_EXCLUSION_PARTITION
Definition: cost.h:40
@ CONSTRAINT_EXCLUSION_ON
Definition: cost.h:39
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:866
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:856
int constraint_exclusion
Definition: plancat.c:57
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
Definition: plancat.c:1277
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:222
List * baserestrictinfo
Definition: pathnodes.h:1012
Expr * clause
Definition: pathnodes.h:2700

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

Referenced by set_append_rel_size(), and set_rel_size().

◆ restriction_selectivity()

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

Definition at line 1969 of file plancat.c.

1974{
1975 RegProcedure oprrest = get_oprrest(operatorid);
1976 float8 result;
1977
1978 /*
1979 * if the oprrest procedure is missing for whatever reason, use a
1980 * selectivity of 0.5
1981 */
1982 if (!oprrest)
1983 return (Selectivity) 0.5;
1984
1985 result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1986 inputcollid,
1988 ObjectIdGetDatum(operatorid),
1990 Int32GetDatum(varRelid)));
1991
1992 if (result < 0.0 || result > 1.0)
1993 elog(ERROR, "invalid restriction selectivity: %f", result);
1994
1995 return (Selectivity) result;
1996}
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1442
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1697
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217

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

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

◆ set_baserel_partition_constraint()

static void set_baserel_partition_constraint ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2592 of file plancat.c.

2593{
2594 List *partconstr;
2595
2596 if (rel->partition_qual) /* already done */
2597 return;
2598
2599 /*
2600 * Run the partition quals through const-simplification similar to check
2601 * constraints. We skip canonicalize_qual, though, because partition
2602 * quals should be in canonical form already; also, since the qual is in
2603 * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2604 * format and back again.
2605 */
2606 partconstr = RelationGetPartitionQual(relation);
2607 if (partconstr)
2608 {
2609 partconstr = (List *) expression_planner((Expr *) partconstr);
2610 if (rel->relid != 1)
2611 ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2612 rel->partition_qual = partconstr;
2613 }
2614}
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:277
Expr * expression_planner(Expr *expr)
Definition: planner.c:6645

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

Referenced by get_relation_constraints(), and set_relation_partition_info().

◆ set_baserel_partition_key_exprs()

static void set_baserel_partition_key_exprs ( Relation  relation,
RelOptInfo rel 
)
static

Definition at line 2524 of file plancat.c.

2526{
2527 PartitionKey partkey = RelationGetPartitionKey(relation);
2528 int partnatts;
2529 int cnt;
2530 List **partexprs;
2531 ListCell *lc;
2532 Index varno = rel->relid;
2533
2534 Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2535
2536 /* A partitioned table should have a partition key. */
2537 Assert(partkey != NULL);
2538
2539 partnatts = partkey->partnatts;
2540 partexprs = (List **) palloc(sizeof(List *) * partnatts);
2541 lc = list_head(partkey->partexprs);
2542
2543 for (cnt = 0; cnt < partnatts; cnt++)
2544 {
2545 Expr *partexpr;
2546 AttrNumber attno = partkey->partattrs[cnt];
2547
2548 if (attno != InvalidAttrNumber)
2549 {
2550 /* Single column partition key is stored as a Var node. */
2551 Assert(attno > 0);
2552
2553 partexpr = (Expr *) makeVar(varno, attno,
2554 partkey->parttypid[cnt],
2555 partkey->parttypmod[cnt],
2556 partkey->parttypcoll[cnt], 0);
2557 }
2558 else
2559 {
2560 if (lc == NULL)
2561 elog(ERROR, "wrong number of partition key expressions");
2562
2563 /* Re-stamp the expression with given varno. */
2564 partexpr = (Expr *) copyObject(lfirst(lc));
2565 ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2566 lc = lnext(partkey->partexprs, lc);
2567 }
2568
2569 /* Base relations have a single expression per key. */
2570 partexprs[cnt] = list_make1(partexpr);
2571 }
2572
2573 rel->partexprs = partexprs;
2574
2575 /*
2576 * A base relation does not have nullable partition key expressions, since
2577 * no outer join is involved. We still allocate an array of empty
2578 * expression lists to keep partition key expression handling code simple.
2579 * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2580 */
2581 rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
2582}
#define InvalidAttrNumber
Definition: attnum.h:23
#define copyObject(obj)
Definition: nodes.h:230
#define list_make1(x1)
Definition: pg_list.h:212
Oid * parttypcoll
Definition: partcache.h:47
int32 * parttypmod
Definition: partcache.h:43
List * partexprs
Definition: partcache.h:31
AttrNumber * partattrs
Definition: partcache.h:29

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

Referenced by set_relation_partition_info().

◆ set_relation_partition_info()

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

Definition at line 2387 of file plancat.c.

2389{
2390 PartitionDesc partdesc;
2391
2392 /*
2393 * Create the PartitionDirectory infrastructure if we didn't already.
2394 */
2395 if (root->glob->partition_directory == NULL)
2396 {
2397 root->glob->partition_directory =
2399 }
2400
2401 partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
2402 relation);
2403 rel->part_scheme = find_partition_scheme(root, relation);
2404 Assert(partdesc != NULL && rel->part_scheme != NULL);
2405 rel->boundinfo = partdesc->boundinfo;
2406 rel->nparts = partdesc->nparts;
2407 set_baserel_partition_key_exprs(relation, rel);
2408 set_baserel_partition_constraint(relation, rel);
2409}
PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool omit_detached)
Definition: partdesc.c:423
PartitionDesc PartitionDirectoryLookup(PartitionDirectory pdir, Relation rel)
Definition: partdesc.c:456
static PartitionScheme find_partition_scheme(PlannerInfo *root, Relation relation)
Definition: plancat.c:2417
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2524
PartitionBoundInfo boundinfo
Definition: partdesc.h:38

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

Referenced by get_relation_info().

Variable Documentation

◆ constraint_exclusion

int constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION

Definition at line 57 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ get_relation_info_hook

get_relation_info_hook_type get_relation_info_hook = NULL

Definition at line 60 of file plancat.c.

Referenced by get_relation_info().