PostgreSQL Source Code git master
plancat.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/sysattr.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xlog.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/pg_am.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_statistic_ext_data.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/supportnodes.h"
#include "optimizer/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/rewriteHandler.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.

Data Structures

struct  NotnullHashEntry
 

Typedefs

typedef struct NotnullHashEntry NotnullHashEntry
 

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 (PlannerInfo *root, 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)
 
void get_relation_notnullatts (PlannerInfo *root, Relation relation)
 
Bitmapsetfind_relation_notnullatts (PlannerInfo *root, Oid relid)
 
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_transition_tables (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
 

Typedef Documentation

◆ NotnullHashEntry

Function Documentation

◆ add_function_cost()

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

Definition at line 2357 of file plancat.c.

2359{
2360 HeapTuple proctup;
2361 Form_pg_proc procform;
2362
2363 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2364 if (!HeapTupleIsValid(proctup))
2365 elog(ERROR, "cache lookup failed for function %u", funcid);
2366 procform = (Form_pg_proc) GETSTRUCT(proctup);
2367
2368 if (OidIsValid(procform->prosupport))
2369 {
2371 SupportRequestCost *sresult;
2372
2373 req.type = T_SupportRequestCost;
2374 req.root = root;
2375 req.funcid = funcid;
2376 req.node = node;
2377
2378 /* Initialize cost fields so that support function doesn't have to */
2379 req.startup = 0;
2380 req.per_tuple = 0;
2381
2382 sresult = (SupportRequestCost *)
2383 DatumGetPointer(OidFunctionCall1(procform->prosupport,
2384 PointerGetDatum(&req)));
2385
2386 if (sresult == &req)
2387 {
2388 /* Success, so accumulate support function's estimate into *cost */
2389 cost->startup += req.startup;
2390 cost->per_tuple += req.per_tuple;
2391 ReleaseSysCache(proctup);
2392 return;
2393 }
2394 }
2395
2396 /* No support function, or it failed, so rely on procost */
2397 cost->per_tuple += procform->procost * cpu_operator_cost;
2398
2399 ReleaseSysCache(proctup);
2400}
#define OidIsValid(objectId)
Definition: c.h:788
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:332
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
tree ctl root
Definition: radixtree.h:1857
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47
PlannerInfo * root
Definition: supportnodes.h:191
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220

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

2164{
2165 List *tlist = NIL;
2166 Index varno = index->rel->relid;
2167 ListCell *indexpr_item;
2168 int i;
2169
2170 indexpr_item = list_head(index->indexprs);
2171 for (i = 0; i < index->ncolumns; i++)
2172 {
2173 int indexkey = index->indexkeys[i];
2174 Expr *indexvar;
2175
2176 if (indexkey != 0)
2177 {
2178 /* simple column */
2179 const FormData_pg_attribute *att_tup;
2180
2181 if (indexkey < 0)
2182 att_tup = SystemAttributeDefinition(indexkey);
2183 else
2184 att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
2185
2186 indexvar = (Expr *) makeVar(varno,
2187 indexkey,
2188 att_tup->atttypid,
2189 att_tup->atttypmod,
2190 att_tup->attcollation,
2191 0);
2192 }
2193 else
2194 {
2195 /* expression column */
2196 if (indexpr_item == NULL)
2197 elog(ERROR, "wrong number of index expressions");
2198 indexvar = (Expr *) lfirst(indexpr_item);
2199 indexpr_item = lnext(index->indexprs, indexpr_item);
2200 }
2201
2202 tlist = lappend(tlist,
2203 makeTargetEntry(indexvar,
2204 i + 1,
2205 NULL,
2206 false));
2207 }
2208 if (indexpr_item != NULL)
2209 elog(ERROR, "wrong number of index expressions");
2210
2211 return tlist;
2212}
unsigned int Index
Definition: c.h:633
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 2041 of file plancat.c.

2042{
2043 List *tlist = NIL;
2044 Index varno = rel->relid;
2045 RangeTblEntry *rte = planner_rt_fetch(varno, root);
2046 Relation relation;
2047 Query *subquery;
2048 Var *var;
2049 ListCell *l;
2050 int attrno,
2051 numattrs;
2052 List *colvars;
2053
2054 switch (rte->rtekind)
2055 {
2056 case RTE_RELATION:
2057 /* Assume we already have adequate lock */
2058 relation = table_open(rte->relid, NoLock);
2059
2060 numattrs = RelationGetNumberOfAttributes(relation);
2061 for (attrno = 1; attrno <= numattrs; attrno++)
2062 {
2063 Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
2064 attrno - 1);
2065
2066 if (att_tup->attisdropped || att_tup->atthasmissing)
2067 {
2068 /* found a dropped or missing col, so punt */
2069 tlist = NIL;
2070 break;
2071 }
2072
2073 var = makeVar(varno,
2074 attrno,
2075 att_tup->atttypid,
2076 att_tup->atttypmod,
2077 att_tup->attcollation,
2078 0);
2079
2080 tlist = lappend(tlist,
2081 makeTargetEntry((Expr *) var,
2082 attrno,
2083 NULL,
2084 false));
2085 }
2086
2087 table_close(relation, NoLock);
2088 break;
2089
2090 case RTE_SUBQUERY:
2091 subquery = rte->subquery;
2092 foreach(l, subquery->targetList)
2093 {
2094 TargetEntry *tle = (TargetEntry *) lfirst(l);
2095
2096 /*
2097 * A resjunk column of the subquery can be reflected as
2098 * resjunk in the physical tlist; we need not punt.
2099 */
2100 var = makeVarFromTargetEntry(varno, tle);
2101
2102 tlist = lappend(tlist,
2103 makeTargetEntry((Expr *) var,
2104 tle->resno,
2105 NULL,
2106 tle->resjunk));
2107 }
2108 break;
2109
2110 case RTE_FUNCTION:
2111 case RTE_TABLEFUNC:
2112 case RTE_VALUES:
2113 case RTE_CTE:
2115 case RTE_RESULT:
2116 /* Not all of these can have dropped cols, but share code anyway */
2117 expandRTE(rte, varno, 0, VAR_RETURNING_DEFAULT, -1,
2118 true /* include dropped */ , NULL, &colvars);
2119 foreach(l, colvars)
2120 {
2121 var = (Var *) lfirst(l);
2122
2123 /*
2124 * A non-Var in expandRTE's output means a dropped column;
2125 * must punt.
2126 */
2127 if (!IsA(var, Var))
2128 {
2129 tlist = NIL;
2130 break;
2131 }
2132
2133 tlist = lappend(tlist,
2134 makeTargetEntry((Expr *) var,
2135 var->varattno,
2136 NULL,
2137 false));
2138 }
2139 break;
2140
2141 default:
2142 /* caller error */
2143 elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
2144 (int) rte->rtekind);
2145 break;
2146 }
2147
2148 return tlist;
2149}
#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:1049
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1050
@ RTE_VALUES
Definition: parsenodes.h:1048
@ RTE_SUBQUERY
Definition: parsenodes.h:1044
@ RTE_RESULT
Definition: parsenodes.h:1051
@ RTE_FUNCTION
Definition: parsenodes.h:1046
@ RTE_TABLEFUNC
Definition: parsenodes.h:1047
@ RTE_RELATION
Definition: parsenodes.h:1043
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:610
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
@ VAR_RETURNING_DEFAULT
Definition: primnodes.h:256
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:521
List * targetList
Definition: parsenodes.h:198
Query * subquery
Definition: parsenodes.h:1135
RTEKind rtekind
Definition: parsenodes.h:1078
Index relid
Definition: pathnodes.h:973
AttrNumber resno
Definition: primnodes.h:2241
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 1307 of file plancat.c.

1309{
1310 BlockNumber curpages;
1311 BlockNumber relpages;
1312 double reltuples;
1313 BlockNumber relallvisible;
1314 double density;
1315
1316 if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
1317 {
1318 table_relation_estimate_size(rel, attr_widths, pages, tuples,
1319 allvisfrac);
1320 }
1321 else if (rel->rd_rel->relkind == RELKIND_INDEX)
1322 {
1323 /*
1324 * XXX: It'd probably be good to move this into a callback, individual
1325 * index types e.g. know if they have a metapage.
1326 */
1327
1328 /* it has storage, ok to call the smgr */
1329 curpages = RelationGetNumberOfBlocks(rel);
1330
1331 /* report estimated # pages */
1332 *pages = curpages;
1333 /* quick exit if rel is clearly empty */
1334 if (curpages == 0)
1335 {
1336 *tuples = 0;
1337 *allvisfrac = 0;
1338 return;
1339 }
1340
1341 /* coerce values in pg_class to more desirable types */
1342 relpages = (BlockNumber) rel->rd_rel->relpages;
1343 reltuples = (double) rel->rd_rel->reltuples;
1344 relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
1345
1346 /*
1347 * Discount the metapage while estimating the number of tuples. This
1348 * is a kluge because it assumes more than it ought to about index
1349 * structure. Currently it's OK for btree, hash, and GIN indexes but
1350 * suspect for GiST indexes.
1351 */
1352 if (relpages > 0)
1353 {
1354 curpages--;
1355 relpages--;
1356 }
1357
1358 /* estimate number of tuples from previous tuple density */
1359 if (reltuples >= 0 && relpages > 0)
1360 density = reltuples / (double) relpages;
1361 else
1362 {
1363 /*
1364 * If we have no data because the relation was never vacuumed,
1365 * estimate tuple width from attribute datatypes. We assume here
1366 * that the pages are completely full, which is OK for tables
1367 * (since they've presumably not been VACUUMed yet) but is
1368 * probably an overestimate for indexes. Fortunately
1369 * get_relation_info() can clamp the overestimate to the parent
1370 * table's size.
1371 *
1372 * Note: this code intentionally disregards alignment
1373 * considerations, because (a) that would be gilding the lily
1374 * considering how crude the estimate is, and (b) it creates
1375 * platform dependencies in the default plans which are kind of a
1376 * headache for regression testing.
1377 *
1378 * XXX: Should this logic be more index specific?
1379 */
1380 int32 tuple_width;
1381
1382 tuple_width = get_rel_data_width(rel, attr_widths);
1383 tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1384 tuple_width += sizeof(ItemIdData);
1385 /* note: integer division is intentional here */
1386 density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1387 }
1388 *tuples = rint(density * (double) curpages);
1389
1390 /*
1391 * We use relallvisible as-is, rather than scaling it up like we do
1392 * for the pages and tuples counts, on the theory that any pages added
1393 * since the last VACUUM are most likely not marked all-visible. But
1394 * costsize.c wants it converted to a fraction.
1395 */
1396 if (relallvisible == 0 || curpages <= 0)
1397 *allvisfrac = 0;
1398 else if ((double) relallvisible >= curpages)
1399 *allvisfrac = 1;
1400 else
1401 *allvisfrac = (double) relallvisible / curpages;
1402 }
1403 else
1404 {
1405 /*
1406 * Just use whatever's in pg_class. This covers foreign tables,
1407 * sequences, and also relkinds without storage (shouldn't get here?);
1408 * see initializations in AddNewRelationTuple(). Note that FDW must
1409 * cope if reltuples is -1!
1410 */
1411 *pages = rel->rd_rel->relpages;
1412 *tuples = rel->rd_rel->reltuples;
1413 *allvisfrac = 0;
1414 }
1415}
uint32 BlockNumber
Definition: block.h:31
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:294
#define SizeOfPageHeaderData
Definition: bufpage.h:216
#define MAXALIGN(LEN)
Definition: c.h:824
int32_t int32
Definition: c.h:548
#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:1432
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:1916

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

2718{
2719 PartitionKey partkey = RelationGetPartitionKey(relation);
2720 ListCell *lc;
2721 int partnatts,
2722 i;
2723 PartitionScheme part_scheme;
2724
2725 /* A partitioned table should have a partition key. */
2726 Assert(partkey != NULL);
2727
2728 partnatts = partkey->partnatts;
2729
2730 /* Search for a matching partition scheme and return if found one. */
2731 foreach(lc, root->part_schemes)
2732 {
2733 part_scheme = lfirst(lc);
2734
2735 /* Match partitioning strategy and number of keys. */
2736 if (partkey->strategy != part_scheme->strategy ||
2737 partnatts != part_scheme->partnatts)
2738 continue;
2739
2740 /* Match partition key type properties. */
2741 if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
2742 sizeof(Oid) * partnatts) != 0 ||
2743 memcmp(partkey->partopcintype, part_scheme->partopcintype,
2744 sizeof(Oid) * partnatts) != 0 ||
2745 memcmp(partkey->partcollation, part_scheme->partcollation,
2746 sizeof(Oid) * partnatts) != 0)
2747 continue;
2748
2749 /*
2750 * Length and byval information should match when partopcintype
2751 * matches.
2752 */
2753 Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
2754 sizeof(int16) * partnatts) == 0);
2755 Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
2756 sizeof(bool) * partnatts) == 0);
2757
2758 /*
2759 * If partopfamily and partopcintype matched, must have the same
2760 * partition comparison functions. Note that we cannot reliably
2761 * Assert the equality of function structs themselves for they might
2762 * be different across PartitionKey's, so just Assert for the function
2763 * OIDs.
2764 */
2765#ifdef USE_ASSERT_CHECKING
2766 for (i = 0; i < partkey->partnatts; i++)
2767 Assert(partkey->partsupfunc[i].fn_oid ==
2768 part_scheme->partsupfunc[i].fn_oid);
2769#endif
2770
2771 /* Found matching partition scheme. */
2772 return part_scheme;
2773 }
2774
2775 /*
2776 * Did not find matching partition scheme. Create one copying relevant
2777 * information from the relcache. We need to copy the contents of the
2778 * array since the relcache entry may not survive after we have closed the
2779 * relation.
2780 */
2781 part_scheme = palloc0_object(PartitionSchemeData);
2782 part_scheme->strategy = partkey->strategy;
2783 part_scheme->partnatts = partkey->partnatts;
2784
2785 part_scheme->partopfamily = palloc_array(Oid, partnatts);
2786 memcpy(part_scheme->partopfamily, partkey->partopfamily,
2787 sizeof(Oid) * partnatts);
2788
2789 part_scheme->partopcintype = palloc_array(Oid, partnatts);
2790 memcpy(part_scheme->partopcintype, partkey->partopcintype,
2791 sizeof(Oid) * partnatts);
2792
2793 part_scheme->partcollation = palloc_array(Oid, partnatts);
2794 memcpy(part_scheme->partcollation, partkey->partcollation,
2795 sizeof(Oid) * partnatts);
2796
2797 part_scheme->parttyplen = palloc_array(int16, partnatts);
2798 memcpy(part_scheme->parttyplen, partkey->parttyplen,
2799 sizeof(int16) * partnatts);
2800
2801 part_scheme->parttypbyval = palloc_array(bool, partnatts);
2802 memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
2803 sizeof(bool) * partnatts);
2804
2805 part_scheme->partsupfunc = palloc_array(FmgrInfo, partnatts);
2806 for (i = 0; i < partnatts; i++)
2807 fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
2809
2810 /* Add the partitioning scheme to PlannerInfo. */
2811 root->part_schemes = lappend(root->part_schemes, part_scheme);
2812
2813 return part_scheme;
2814}
int16_t int16
Definition: c.h:547
#define palloc_array(type, count)
Definition: fe_memutils.h:76
#define palloc0_object(type)
Definition: fe_memutils.h:75
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition: fmgr.c:581
Assert(PointerIsAligned(start, uint64))
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
PartitionKey RelationGetPartitionKey(Relation rel)
Definition: partcache.c:51
unsigned int Oid
Definition: postgres_ext.h:32
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:641

References Assert(), CurrentMemoryContext, fmgr_info_copy(), FmgrInfo::fn_oid, i, lappend(), lfirst, palloc0_object, palloc_array, 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().

◆ find_relation_notnullatts()

Bitmapset * find_relation_notnullatts ( PlannerInfo root,
Oid  relid 
)

Definition at line 774 of file plancat.c.

775{
776 NotnullHashEntry *hentry;
777 bool found;
778
779 if (root->glob->rel_notnullatts_hash == NULL)
780 return NULL;
781
782 hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
783 &relid,
784 HASH_FIND,
785 &found);
786 if (!found)
787 return NULL;
788
789 return hentry->notnullattnums;
790}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:952
@ HASH_FIND
Definition: hsearch.h:113
Bitmapset * notnullattnums
Definition: plancat.c:66

References HASH_FIND, hash_search(), NotnullHashEntry::notnullattnums, and root.

Referenced by get_relation_info(), and var_is_nonnullable().

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

2311{
2312 RegProcedure prosupport = get_func_support(funcid);
2315
2316 if (!prosupport)
2317 return (Selectivity) -1; /* no support function */
2318
2319 req.type = T_SupportRequestSelectivity;
2320 req.root = root;
2321 req.funcid = funcid;
2322 req.args = args;
2323 req.inputcollid = inputcollid;
2324 req.is_join = is_join;
2325 req.varRelid = varRelid;
2326 req.jointype = jointype;
2327 req.sjinfo = sjinfo;
2328 req.selectivity = -1; /* to catch failure to set the value */
2329
2330 sresult = (SupportRequestSelectivity *)
2332 PointerGetDatum(&req)));
2333
2334 if (sresult != &req)
2335 return (Selectivity) -1; /* function did not honor request */
2336
2337 if (req.selectivity < 0.0 || req.selectivity > 1.0)
2338 elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2339
2340 return (Selectivity) req.selectivity;
2341}
regproc RegProcedure
Definition: c.h:669
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:2023
double Selectivity
Definition: nodes.h:260
SpecialJoinInfo * sjinfo
Definition: supportnodes.h:158

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

2641{
2642 Bitmapset *dependentCols = NULL;
2643 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2644 Relation relation;
2645 TupleDesc tupdesc;
2646 TupleConstr *constr;
2647
2648 /* Assume we already have adequate lock */
2649 relation = table_open(rte->relid, NoLock);
2650
2651 tupdesc = RelationGetDescr(relation);
2652 constr = tupdesc->constr;
2653
2654 if (constr && constr->has_generated_stored)
2655 {
2656 for (int i = 0; i < constr->num_defval; i++)
2657 {
2658 AttrDefault *defval = &constr->defval[i];
2659 Node *expr;
2660 Bitmapset *attrs_used = NULL;
2661
2662 /* skip if not generated column */
2663 if (!TupleDescCompactAttr(tupdesc, defval->adnum - 1)->attgenerated)
2664 continue;
2665
2666 /* identify columns this generated column depends on */
2667 expr = stringToNode(defval->adbin);
2668 pull_varattnos(expr, 1, &attrs_used);
2669
2670 if (bms_overlap(target_cols, attrs_used))
2671 dependentCols = bms_add_member(dependentCols,
2673 }
2674 }
2675
2676 table_close(relation, NoLock);
2677
2678 return dependentCols;
2679}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:581
void * stringToNode(const char *str)
Definition: read.c:90
#define RelationGetDescr(relation)
Definition: rel.h:541
AttrNumber adnum
Definition: tupdesc.h:24
char * adbin
Definition: tupdesc.h:25
bool attgenerated
Definition: tupdesc.h:78
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
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:175
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:296

References AttrDefault::adbin, AttrDefault::adnum, CompactAttribute::attgenerated, 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 TupleDescCompactAttr().

Referenced by get_rel_all_updated_cols().

◆ get_function_rows()

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

Definition at line 2418 of file plancat.c.

2419{
2420 HeapTuple proctup;
2421 Form_pg_proc procform;
2422 double result;
2423
2424 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2425 if (!HeapTupleIsValid(proctup))
2426 elog(ERROR, "cache lookup failed for function %u", funcid);
2427 procform = (Form_pg_proc) GETSTRUCT(proctup);
2428
2429 Assert(procform->proretset); /* else caller error */
2430
2431 if (OidIsValid(procform->prosupport))
2432 {
2434 SupportRequestRows *sresult;
2435
2436 req.type = T_SupportRequestRows;
2437 req.root = root;
2438 req.funcid = funcid;
2439 req.node = node;
2440
2441 req.rows = 0; /* just for sanity */
2442
2443 sresult = (SupportRequestRows *)
2444 DatumGetPointer(OidFunctionCall1(procform->prosupport,
2445 PointerGetDatum(&req)));
2446
2447 if (sresult == &req)
2448 {
2449 /* Success */
2450 ReleaseSysCache(proctup);
2451 return req.rows;
2452 }
2453 }
2454
2455 /* No support function, or it failed, so rely on prorows */
2456 result = procform->prorows;
2457
2458 ReleaseSysCache(proctup);
2459
2460 return result;
2461}
PlannerInfo * root
Definition: supportnodes.h:218

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

1433{
1434 int64 tuple_width = 0;
1435 int i;
1436
1437 for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1438 {
1439 Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
1440 int32 item_width;
1441
1442 if (att->attisdropped)
1443 continue;
1444
1445 /* use previously cached data, if any */
1446 if (attr_widths != NULL && attr_widths[i] > 0)
1447 {
1448 tuple_width += attr_widths[i];
1449 continue;
1450 }
1451
1452 /* This should match set_rel_width() in costsize.c */
1453 item_width = get_attavgwidth(RelationGetRelid(rel), i);
1454 if (item_width <= 0)
1455 {
1456 item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1457 Assert(item_width > 0);
1458 }
1459 if (attr_widths != NULL)
1460 attr_widths[i] = item_width;
1461 tuple_width += item_width;
1462 }
1463
1464 return clamp_width_est(tuple_width);
1465}
int64_t int64
Definition: c.h:549
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:242
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3323
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2743
#define RelationGetRelid(relation)
Definition: rel.h:515

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

1520{
1521 List *result = NIL;
1522 Index varno = rel->relid;
1523 Relation relation;
1524 TupleConstr *constr;
1525
1526 /*
1527 * We assume the relation has already been safely locked.
1528 */
1529 relation = table_open(relationObjectId, NoLock);
1530
1531 constr = relation->rd_att->constr;
1532 if (constr != NULL)
1533 {
1534 int num_check = constr->num_check;
1535 int i;
1536
1537 for (i = 0; i < num_check; i++)
1538 {
1539 Node *cexpr;
1540
1541 /*
1542 * If this constraint hasn't been fully validated yet, we must
1543 * ignore it here.
1544 */
1545 if (!constr->check[i].ccvalid)
1546 continue;
1547
1548 /*
1549 * NOT ENFORCED constraints are always marked as invalid, which
1550 * should have been ignored.
1551 */
1552 Assert(constr->check[i].ccenforced);
1553
1554 /*
1555 * Also ignore if NO INHERIT and we weren't told that that's safe.
1556 */
1557 if (constr->check[i].ccnoinherit && !include_noinherit)
1558 continue;
1559
1560 cexpr = stringToNode(constr->check[i].ccbin);
1561
1562 /*
1563 * Fix Vars to have the desired varno. This must be done before
1564 * const-simplification because eval_const_expressions reduces
1565 * NullTest for Vars based on varno.
1566 */
1567 if (varno != 1)
1568 ChangeVarNodes(cexpr, 1, varno, 0);
1569
1570 /*
1571 * Run each expression through const-simplification and
1572 * canonicalization. This is not just an optimization, but is
1573 * necessary, because we will be comparing it to
1574 * similarly-processed qual clauses, and may fail to detect valid
1575 * matches without this. This must match the processing done to
1576 * qual clauses in preprocess_expression()! (We can skip the
1577 * stuff involving subqueries, however, since we don't allow any
1578 * in check constraints.)
1579 */
1580 cexpr = eval_const_expressions(root, cexpr);
1581
1582 cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
1583
1584 /*
1585 * Finally, convert to implicit-AND format (that is, a List) and
1586 * append the resulting item(s) to our output list.
1587 */
1588 result = list_concat(result,
1589 make_ands_implicit((Expr *) cexpr));
1590 }
1591
1592 /* Add NOT NULL constraints in expression form, if requested */
1593 if (include_notnull && constr->has_not_null)
1594 {
1595 int natts = relation->rd_att->natts;
1596
1597 for (i = 1; i <= natts; i++)
1598 {
1599 CompactAttribute *att = TupleDescCompactAttr(relation->rd_att, i - 1);
1600
1601 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
1602 {
1603 Form_pg_attribute wholeatt = TupleDescAttr(relation->rd_att, i - 1);
1604 NullTest *ntest = makeNode(NullTest);
1605
1606 ntest->arg = (Expr *) makeVar(varno,
1607 i,
1608 wholeatt->atttypid,
1609 wholeatt->atttypmod,
1610 wholeatt->attcollation,
1611 0);
1612 ntest->nulltesttype = IS_NOT_NULL;
1613
1614 /*
1615 * argisrow=false is correct even for a composite column,
1616 * because attnotnull does not represent a SQL-spec IS NOT
1617 * NULL test in such a case, just IS DISTINCT FROM NULL.
1618 */
1619 ntest->argisrow = false;
1620 ntest->location = -1;
1621 result = lappend(result, ntest);
1622 }
1623 }
1624 }
1625 }
1626
1627 /*
1628 * Add partitioning constraints, if requested.
1629 */
1630 if (include_partition && relation->rd_rel->relispartition)
1631 {
1632 /* make sure rel->partition_qual is set */
1633 set_baserel_partition_constraint(relation, rel);
1634 result = list_concat(result, rel->partition_qual);
1635 }
1636
1637 /*
1638 * Expand virtual generated columns in the constraint expressions.
1639 */
1640 if (result)
1641 result = (List *) expand_generated_columns_in_expr((Node *) result,
1642 relation,
1643 varno);
1644
1645 table_close(relation, NoLock);
1646
1647 return result;
1648}
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2270
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:2891
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:293
@ IS_NOT_NULL
Definition: primnodes.h:1977
Node * expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index)
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:733
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:1984
ParseLoc location
Definition: primnodes.h:1987
Expr * arg
Definition: primnodes.h:1983
List * partition_qual
Definition: pathnodes.h:1096
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

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(), expand_generated_columns_in_expr(), 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 1474 of file plancat.c.

1475{
1476 int32 result;
1477 Relation relation;
1478
1479 /* As above, assume relation is already locked */
1480 relation = table_open(relid, NoLock);
1481
1482 result = get_rel_data_width(relation, attr_widths);
1483
1484 table_close(relation, NoLock);
1485
1486 return result;
1487}

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

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

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

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

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(), build_index_tlist(), ChangeVarNodes(), COMPARE_LT, ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, estimate_rel_size(), eval_const_expressions(), find_relation_notnullatts(), 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(), make_ands_explicit(), make_ands_implicit(), makeNode, RelOptInfo::max_attr, RelOptInfo::min_attr, IndexOptInfo::ncolumns, NIL, IndexOptInfo::nkeycolumns, NoLock, RelOptInfo::notnullattnums, IndexOptInfo::nullsnotdistinct, OidIsValid, RelOptInfo::pages, IndexOptInfo::pages, palloc0(), palloc_array, IndexOptInfo::predOK, RelationData::rd_indam, RelationData::rd_indcollation, RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_indoption, RelationData::rd_opcintype, RelationData::rd_opfamily, RelationData::rd_rel, RelationData::rd_tableam, RecoveryInProgress(), RelOptInfo::rel_parallel_workers, IndexOptInfo::relam, RelationGetForm, RelationGetIndexAttOptions(), RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), RelationGetNumberOfAttributes, RelationGetNumberOfBlocks, RelationGetParallelWorkers, RelationGetRelationName, RelationGetRelid, RelationIsPermanent, RelOptInfo::relid, RelOptInfo::reltablespace, IndexOptInfo::reltablespace, 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, RelOptInfo::tuples, IndexOptInfo::tuples, IndexOptInfo::unique, and unlikely.

Referenced by build_simple_rel().

◆ get_relation_notnullatts()

void get_relation_notnullatts ( PlannerInfo root,
Relation  relation 
)

Definition at line 701 of file plancat.c.

702{
703 Oid relid = RelationGetRelid(relation);
704 NotnullHashEntry *hentry;
705 bool found;
706 Bitmapset *notnullattnums = NULL;
707
708 /* bail out if the relation has no not-null constraints */
709 if (relation->rd_att->constr == NULL ||
710 !relation->rd_att->constr->has_not_null)
711 return;
712
713 /* create the hash table if it hasn't been created yet */
714 if (root->glob->rel_notnullatts_hash == NULL)
715 {
716 HTAB *hashtab;
717 HASHCTL hash_ctl;
718
719 hash_ctl.keysize = sizeof(Oid);
720 hash_ctl.entrysize = sizeof(NotnullHashEntry);
721 hash_ctl.hcxt = CurrentMemoryContext;
722
723 hashtab = hash_create("Relation NOT NULL attnums",
724 64L, /* arbitrary initial size */
725 &hash_ctl,
727
728 root->glob->rel_notnullatts_hash = hashtab;
729 }
730
731 /*
732 * Create a hash entry for this relation OID, if we don't have one
733 * already.
734 */
735 hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
736 &relid,
738 &found);
739
740 /* bail out if a hash entry already exists for this relation OID */
741 if (found)
742 return;
743
744 /* collect the column not-null constraint information for this relation */
745 for (int i = 0; i < relation->rd_att->natts; i++)
746 {
747 CompactAttribute *attr = TupleDescCompactAttr(relation->rd_att, i);
748
750
752 {
753 notnullattnums = bms_add_member(notnullattnums, i + 1);
754
755 /*
756 * Per RemoveAttributeById(), dropped columns will have their
757 * attnotnull unset, so we needn't check for dropped columns in
758 * the above condition.
759 */
760 Assert(!attr->attisdropped);
761 }
762 }
763
764 /* ... and initialize the new hash entry */
765 hentry->notnullattnums = notnullattnums;
766}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:358
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
struct NotnullHashEntry NotnullHashEntry
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:222
#define ATTNULLABLE_UNKNOWN
Definition: tupdesc.h:85

References Assert(), CompactAttribute::attisdropped, CompactAttribute::attnullability, ATTNULLABLE_UNKNOWN, ATTNULLABLE_VALID, bms_add_member(), TupleDescData::constr, CurrentMemoryContext, HASHCTL::entrysize, TupleConstr::has_not_null, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASHCTL::hcxt, i, HASHCTL::keysize, TupleDescData::natts, NotnullHashEntry::notnullattnums, RelationData::rd_att, RelationGetRelid, root, and TupleDescCompactAttr().

Referenced by expand_single_inheritance_child(), and preprocess_relation_rtes().

◆ get_relation_statistics()

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

Definition at line 1740 of file plancat.c.

1742{
1743 Index varno = rel->relid;
1744 List *statoidlist;
1745 List *stainfos = NIL;
1746 ListCell *l;
1747
1748 statoidlist = RelationGetStatExtList(relation);
1749
1750 foreach(l, statoidlist)
1751 {
1752 Oid statOid = lfirst_oid(l);
1753 Form_pg_statistic_ext staForm;
1754 HeapTuple htup;
1755 Bitmapset *keys = NULL;
1756 List *exprs = NIL;
1757 int i;
1758
1759 htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1760 if (!HeapTupleIsValid(htup))
1761 elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1762 staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1763
1764 /*
1765 * First, build the array of columns covered. This is ultimately
1766 * wasted if no stats within the object have actually been built, but
1767 * it doesn't seem worth troubling over that case.
1768 */
1769 for (i = 0; i < staForm->stxkeys.dim1; i++)
1770 keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1771
1772 /*
1773 * Preprocess expressions (if any). We read the expressions, fix the
1774 * varnos, and run them through eval_const_expressions.
1775 *
1776 * XXX We don't know yet if there are any data for this stats object,
1777 * with either stxdinherit value. But it's reasonable to assume there
1778 * is at least one of those, possibly both. So it's better to process
1779 * keys and expressions here.
1780 */
1781 {
1782 bool isnull;
1783 Datum datum;
1784
1785 /* decode expression (if any) */
1786 datum = SysCacheGetAttr(STATEXTOID, htup,
1787 Anum_pg_statistic_ext_stxexprs, &isnull);
1788
1789 if (!isnull)
1790 {
1791 char *exprsString;
1792
1793 exprsString = TextDatumGetCString(datum);
1794 exprs = (List *) stringToNode(exprsString);
1795 pfree(exprsString);
1796
1797 /*
1798 * Modify the copies we obtain from the relcache to have the
1799 * correct varno for the parent relation, so that they match
1800 * up correctly against qual clauses.
1801 *
1802 * This must be done before const-simplification because
1803 * eval_const_expressions reduces NullTest for Vars based on
1804 * varno.
1805 */
1806 if (varno != 1)
1807 ChangeVarNodes((Node *) exprs, 1, varno, 0);
1808
1809 /*
1810 * Run the expressions through eval_const_expressions. This is
1811 * not just an optimization, but is necessary, because the
1812 * planner will be comparing them to similarly-processed qual
1813 * clauses, and may fail to detect valid matches without this.
1814 * We must not use canonicalize_qual, however, since these
1815 * aren't qual expressions.
1816 */
1817 exprs = (List *) eval_const_expressions(root, (Node *) exprs);
1818
1819 /* May as well fix opfuncids too */
1820 fix_opfuncids((Node *) exprs);
1821 }
1822 }
1823
1824 /* extract statistics for possible values of stxdinherit flag */
1825
1826 get_relation_statistics_worker(&stainfos, rel, statOid, true, keys, exprs);
1827
1828 get_relation_statistics_worker(&stainfos, rel, statOid, false, keys, exprs);
1829
1830 ReleaseSysCache(htup);
1831 bms_free(keys);
1832 }
1833
1834 list_free(statoidlist);
1835
1836 return stainfos;
1837}
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
#define TextDatumGetCString(d)
Definition: builtins.h:98
void pfree(void *pointer)
Definition: mcxt.c:1594
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1837
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:1657
uint64_t Datum
Definition: postgres.h:70
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4977
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:595

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, root, 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 1657 of file plancat.c.

1660{
1662 HeapTuple dtup;
1663
1664 dtup = SearchSysCache2(STATEXTDATASTXOID,
1665 ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1666 if (!HeapTupleIsValid(dtup))
1667 return;
1668
1669 dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
1670
1671 /* add one StatisticExtInfo for each kind built */
1672 if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
1673 {
1675
1676 info->statOid = statOid;
1677 info->inherit = dataForm->stxdinherit;
1678 info->rel = rel;
1679 info->kind = STATS_EXT_NDISTINCT;
1680 info->keys = bms_copy(keys);
1681 info->exprs = exprs;
1682
1683 *stainfos = lappend(*stainfos, info);
1684 }
1685
1686 if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
1687 {
1689
1690 info->statOid = statOid;
1691 info->inherit = dataForm->stxdinherit;
1692 info->rel = rel;
1693 info->kind = STATS_EXT_DEPENDENCIES;
1694 info->keys = bms_copy(keys);
1695 info->exprs = exprs;
1696
1697 *stainfos = lappend(*stainfos, info);
1698 }
1699
1700 if (statext_is_kind_built(dtup, STATS_EXT_MCV))
1701 {
1703
1704 info->statOid = statOid;
1705 info->inherit = dataForm->stxdinherit;
1706 info->rel = rel;
1707 info->kind = STATS_EXT_MCV;
1708 info->keys = bms_copy(keys);
1709 info->exprs = exprs;
1710
1711 *stainfos = lappend(*stainfos, info);
1712 }
1713
1714 if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
1715 {
1717
1718 info->statOid = statOid;
1719 info->inherit = dataForm->stxdinherit;
1720 info->rel = rel;
1721 info->kind = STATS_EXT_EXPRESSIONS;
1722 info->keys = bms_copy(keys);
1723 info->exprs = exprs;
1724
1725 *stainfos = lappend(*stainfos, info);
1726 }
1727
1728 ReleaseSysCache(dtup);
1729}
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:112
Bitmapset * keys
Definition: pathnodes.h:1431
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:230

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

Referenced by get_relation_statistics().

◆ has_row_triggers()

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

Definition at line 2508 of file plancat.c.

2509{
2510 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2511 Relation relation;
2512 TriggerDesc *trigDesc;
2513 bool result = false;
2514
2515 /* Assume we already have adequate lock */
2516 relation = table_open(rte->relid, NoLock);
2517
2518 trigDesc = relation->trigdesc;
2519 switch (event)
2520 {
2521 case CMD_INSERT:
2522 if (trigDesc &&
2523 (trigDesc->trig_insert_after_row ||
2524 trigDesc->trig_insert_before_row))
2525 result = true;
2526 break;
2527 case CMD_UPDATE:
2528 if (trigDesc &&
2529 (trigDesc->trig_update_after_row ||
2530 trigDesc->trig_update_before_row))
2531 result = true;
2532 break;
2533 case CMD_DELETE:
2534 if (trigDesc &&
2535 (trigDesc->trig_delete_after_row ||
2536 trigDesc->trig_delete_before_row))
2537 result = true;
2538 break;
2539 /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2540 case CMD_MERGE:
2541 result = false;
2542 break;
2543 default:
2544 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2545 break;
2546 }
2547
2548 table_close(relation, NoLock);
2549 return result;
2550}
@ CMD_MERGE
Definition: nodes.h:279
@ CMD_INSERT
Definition: nodes.h:277
@ CMD_DELETE
Definition: nodes.h:278
@ CMD_UPDATE
Definition: nodes.h:276
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 2612 of file plancat.c.

2613{
2614 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2615 Relation relation;
2616 TupleDesc tupdesc;
2617 bool result = false;
2618
2619 /* Assume we already have adequate lock */
2620 relation = table_open(rte->relid, NoLock);
2621
2622 tupdesc = RelationGetDescr(relation);
2623 result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2624
2625 table_close(relation, NoLock);
2626
2627 return result;
2628}

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

Referenced by make_modifytable().

◆ has_transition_tables()

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

Definition at line 2558 of file plancat.c.

2559{
2560 RangeTblEntry *rte = planner_rt_fetch(rti, root);
2561 Relation relation;
2562 TriggerDesc *trigDesc;
2563 bool result = false;
2564
2565 Assert(rte->rtekind == RTE_RELATION);
2566
2567 /* Currently foreign tables cannot have transition tables */
2568 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2569 return result;
2570
2571 /* Assume we already have adequate lock */
2572 relation = table_open(rte->relid, NoLock);
2573
2574 trigDesc = relation->trigdesc;
2575 switch (event)
2576 {
2577 case CMD_INSERT:
2578 if (trigDesc &&
2579 trigDesc->trig_insert_new_table)
2580 result = true;
2581 break;
2582 case CMD_UPDATE:
2583 if (trigDesc &&
2584 (trigDesc->trig_update_old_table ||
2585 trigDesc->trig_update_new_table))
2586 result = true;
2587 break;
2588 case CMD_DELETE:
2589 if (trigDesc &&
2590 trigDesc->trig_delete_old_table)
2591 result = true;
2592 break;
2593 /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2594 case CMD_MERGE:
2595 result = false;
2596 break;
2597 default:
2598 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2599 break;
2600 }
2601
2602 table_close(relation, NoLock);
2603 return result;
2604}
bool trig_update_new_table
Definition: reltrigger.h:77
bool trig_insert_new_table
Definition: reltrigger.h:75
bool trig_delete_old_table
Definition: reltrigger.h:78
bool trig_update_old_table
Definition: reltrigger.h:76

References Assert(), CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, elog, ERROR, NoLock, planner_rt_fetch, root, RTE_RELATION, RangeTblEntry::rtekind, table_close(), table_open(), TriggerDesc::trig_delete_old_table, TriggerDesc::trig_insert_new_table, TriggerDesc::trig_update_new_table, TriggerDesc::trig_update_old_table, and RelationData::trigdesc.

Referenced by make_modifytable().

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2476 of file plancat.c.

2477{
2478 ListCell *ilist;
2479
2480 foreach(ilist, rel->indexlist)
2481 {
2482 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
2483
2484 /*
2485 * Note: ignore partial indexes, since they don't allow us to conclude
2486 * that all attr values are distinct, *unless* they are marked predOK
2487 * which means we know the index's predicate is satisfied by the
2488 * query. We don't take any interest in expressional indexes either.
2489 * Also, a multicolumn unique index doesn't allow us to conclude that
2490 * just the specified attr is unique.
2491 */
2492 if (index->unique &&
2493 index->nkeycolumns == 1 &&
2494 index->indexkeys[0] == attno &&
2495 (index->indpred == NIL || index->predOK))
2496 return true;
2497 }
2498 return false;
2499}

References RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List * infer_arbiter_indexes ( PlannerInfo root)

Definition at line 813 of file plancat.c.

814{
815 OnConflictExpr *onconflict = root->parse->onConflict;
816
817 /* Iteration state */
818 Index varno;
819 RangeTblEntry *rte;
820 Relation relation;
821 Oid indexOidFromConstraint = InvalidOid;
822 List *indexList;
823 List *indexRelList = NIL;
824
825 /*
826 * Required attributes and expressions used to match indexes to the clause
827 * given by the user. In the ON CONFLICT ON CONSTRAINT case, we compute
828 * these from that constraint's index to match all other indexes, to
829 * account for the case where that index is being concurrently reindexed.
830 */
831 List *inferIndexExprs = (List *) onconflict->arbiterWhere;
832 Bitmapset *inferAttrs = NULL;
833 List *inferElems = NIL;
834
835 /* Results */
836 List *results = NIL;
837 bool foundValid = false;
838
839 /*
840 * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
841 * specification or named constraint. ON CONFLICT DO UPDATE statements
842 * must always provide one or the other (but parser ought to have caught
843 * that already).
844 */
845 if (onconflict->arbiterElems == NIL &&
846 onconflict->constraint == InvalidOid)
847 return NIL;
848
849 /*
850 * We need not lock the relation since it was already locked, either by
851 * the rewriter or when expand_inherited_rtentry() added it to the query's
852 * rangetable.
853 */
854 varno = root->parse->resultRelation;
855 rte = rt_fetch(varno, root->parse->rtable);
856
857 relation = table_open(rte->relid, NoLock);
858
859 /*
860 * Build normalized/BMS representation of plain indexed attributes, as
861 * well as a separate list of expression items. This simplifies matching
862 * the cataloged definition of indexes.
863 */
864 foreach_ptr(InferenceElem, elem, onconflict->arbiterElems)
865 {
866 Var *var;
867 int attno;
868
869 /* we cannot also have a constraint name, per grammar */
870 Assert(!OidIsValid(onconflict->constraint));
871
872 if (!IsA(elem->expr, Var))
873 {
874 /* If not a plain Var, just shove it in inferElems for now */
875 inferElems = lappend(inferElems, elem->expr);
876 continue;
877 }
878
879 var = (Var *) elem->expr;
880 attno = var->varattno;
881
882 if (attno == 0)
884 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
885 errmsg("whole row unique index inference specifications are not supported")));
886
887 inferAttrs = bms_add_member(inferAttrs,
889 }
890
891 /*
892 * Next, open all the indexes. We need this list for two things: first,
893 * if an ON CONSTRAINT clause was given, and that constraint's index is
894 * undergoing REINDEX CONCURRENTLY, then we need to consider all matches
895 * for that index. Second, if an attribute list was specified in the ON
896 * CONFLICT clause, we use the list to find the indexes whose attributes
897 * match that list.
898 */
899 indexList = RelationGetIndexList(relation);
900 foreach_oid(indexoid, indexList)
901 {
902 Relation idxRel;
903
904 /* obtain the same lock type that the executor will ultimately use */
905 idxRel = index_open(indexoid, rte->rellockmode);
906 indexRelList = lappend(indexRelList, idxRel);
907 }
908
909 /*
910 * If a constraint was named in the command, look up its index. We don't
911 * return it immediately because we need some additional sanity checks,
912 * and also because we need to include other indexes as arbiters to
913 * account for REINDEX CONCURRENTLY processing it.
914 */
915 if (onconflict->constraint != InvalidOid)
916 {
917 /* we cannot also have an explicit list of elements, per grammar */
918 Assert(onconflict->arbiterElems == NIL);
919
920 indexOidFromConstraint = get_constraint_index(onconflict->constraint);
921 if (indexOidFromConstraint == InvalidOid)
923 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
924 errmsg("constraint in ON CONFLICT clause has no associated index")));
925
926 /*
927 * Find the named constraint index to extract its attributes and
928 * predicates.
929 */
930 foreach_ptr(RelationData, idxRel, indexRelList)
931 {
932 Form_pg_index idxForm = idxRel->rd_index;
933
934 if (indexOidFromConstraint == idxForm->indexrelid)
935 {
936 /* Found it. */
937 Assert(idxForm->indisready);
938
939 /*
940 * Set up inferElems and inferPredExprs to match the
941 * constraint index, so that we can match them in the loop
942 * below.
943 */
944 for (int natt = 0; natt < idxForm->indnkeyatts; natt++)
945 {
946 int attno;
947
948 attno = idxRel->rd_index->indkey.values[natt];
949 if (attno != InvalidAttrNumber)
950 inferAttrs =
951 bms_add_member(inferAttrs,
953 }
954
955 inferElems = RelationGetIndexExpressions(idxRel);
956 inferIndexExprs = RelationGetIndexPredicate(idxRel);
957 break;
958 }
959 }
960 }
961
962 /*
963 * Using that representation, iterate through the list of indexes on the
964 * target relation to find matches.
965 */
966 foreach_ptr(RelationData, idxRel, indexRelList)
967 {
968 Form_pg_index idxForm;
969 Bitmapset *indexedAttrs;
970 List *idxExprs;
971 List *predExprs;
972 AttrNumber natt;
973 bool match;
974
975 /*
976 * Extract info from the relation descriptor for the index.
977 *
978 * Let executor complain about !indimmediate case directly, because
979 * enforcement needs to occur there anyway when an inference clause is
980 * omitted.
981 */
982 idxForm = idxRel->rd_index;
983
984 /*
985 * Ignore indexes that aren't indisready, because we cannot trust
986 * their catalog structure yet. However, if any indexes are marked
987 * indisready but not yet indisvalid, we still consider them, because
988 * they might turn valid while we're running. Doing it this way
989 * allows a concurrent transaction with a slightly later catalog
990 * snapshot infer the same set of indexes, which is critical to
991 * prevent spurious 'duplicate key' errors.
992 *
993 * However, another critical aspect is that a unique index that isn't
994 * yet marked indisvalid=true might not be complete yet, meaning it
995 * wouldn't detect possible duplicate rows. In order to prevent false
996 * negatives, we require that we include in the set of inferred
997 * indexes at least one index that is marked valid.
998 */
999 if (!idxForm->indisready)
1000 continue;
1001
1002 /*
1003 * Ignore invalid indexes for partitioned tables. It's possible that
1004 * some partitions don't have the index (yet), and then we would not
1005 * find a match during ExecInitPartitionInfo.
1006 */
1007 if (relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
1008 !idxForm->indisvalid)
1009 continue;
1010
1011 /*
1012 * Note that we do not perform a check against indcheckxmin (like e.g.
1013 * get_relation_info()) here to eliminate candidates, because
1014 * uniqueness checking only cares about the most recently committed
1015 * tuple versions.
1016 */
1017
1018 /*
1019 * Look for match for "ON constraint_name" variant, which may not be a
1020 * unique constraint. This can only be a constraint name.
1021 */
1022 if (indexOidFromConstraint == idxForm->indexrelid)
1023 {
1024 if (idxForm->indisexclusion && onconflict->action == ONCONFLICT_UPDATE)
1025 ereport(ERROR,
1026 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1027 errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
1028
1029 /* Consider this one a match already */
1030 results = lappend_oid(results, idxForm->indexrelid);
1031 foundValid |= idxForm->indisvalid;
1032 continue;
1033 }
1034 else if (indexOidFromConstraint != InvalidOid)
1035 {
1036 /*
1037 * In the case of "ON constraint_name DO UPDATE" we need to skip
1038 * non-unique candidates.
1039 */
1040 if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
1041 continue;
1042 }
1043 else
1044 {
1045 /*
1046 * Only considering conventional inference at this point (not
1047 * named constraints), so index under consideration can be
1048 * immediately skipped if it's not unique.
1049 */
1050 if (!idxForm->indisunique)
1051 continue;
1052 }
1053
1054 /*
1055 * So-called unique constraints with WITHOUT OVERLAPS are really
1056 * exclusion constraints, so skip those too.
1057 */
1058 if (idxForm->indisexclusion)
1059 continue;
1060
1061 /* Build BMS representation of plain (non expression) index attrs */
1062 indexedAttrs = NULL;
1063 for (natt = 0; natt < idxForm->indnkeyatts; natt++)
1064 {
1065 int attno = idxRel->rd_index->indkey.values[natt];
1066
1067 if (attno != 0)
1068 indexedAttrs = bms_add_member(indexedAttrs,
1070 }
1071
1072 /* Non-expression attributes (if any) must match */
1073 if (!bms_equal(indexedAttrs, inferAttrs))
1074 continue;
1075
1076 /* Expression attributes (if any) must match */
1077 idxExprs = RelationGetIndexExpressions(idxRel);
1078 if (idxExprs)
1079 {
1080 if (varno != 1)
1081 ChangeVarNodes((Node *) idxExprs, 1, varno, 0);
1082
1083 idxExprs = (List *) eval_const_expressions(root, (Node *) idxExprs);
1084 }
1085
1086 /*
1087 * If arbiterElems are present, check them. (Note that if a
1088 * constraint name was given in the command line, this list is NIL.)
1089 */
1090 match = true;
1091 foreach_ptr(InferenceElem, elem, onconflict->arbiterElems)
1092 {
1093 /*
1094 * Ensure that collation/opclass aspects of inference expression
1095 * element match. Even though this loop is primarily concerned
1096 * with matching expressions, it is a convenient point to check
1097 * this for both expressions and ordinary (non-expression)
1098 * attributes appearing as inference elements.
1099 */
1100 if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
1101 {
1102 match = false;
1103 break;
1104 }
1105
1106 /*
1107 * Plain Vars don't factor into count of expression elements, and
1108 * the question of whether or not they satisfy the index
1109 * definition has already been considered (they must).
1110 */
1111 if (IsA(elem->expr, Var))
1112 continue;
1113
1114 /*
1115 * Might as well avoid redundant check in the rare cases where
1116 * infer_collation_opclass_match() is required to do real work.
1117 * Otherwise, check that element expression appears in cataloged
1118 * index definition.
1119 */
1120 if (elem->infercollid != InvalidOid ||
1121 elem->inferopclass != InvalidOid ||
1122 list_member(idxExprs, elem->expr))
1123 continue;
1124
1125 match = false;
1126 break;
1127 }
1128 if (!match)
1129 continue;
1130
1131 /*
1132 * In case of inference from an attribute list, ensure that the
1133 * expression elements from inference clause are not missing any
1134 * cataloged expressions. This does the right thing when unique
1135 * indexes redundantly repeat the same attribute, or if attributes
1136 * redundantly appear multiple times within an inference clause.
1137 *
1138 * In case a constraint was named, ensure the candidate has an equal
1139 * set of expressions as the named constraint's index.
1140 */
1141 if (list_difference(idxExprs, inferElems) != NIL)
1142 continue;
1143
1144 predExprs = RelationGetIndexPredicate(idxRel);
1145 if (predExprs)
1146 {
1147 if (varno != 1)
1148 ChangeVarNodes((Node *) predExprs, 1, varno, 0);
1149
1150 predExprs = (List *)
1152 (Node *) make_ands_explicit(predExprs));
1153 predExprs = make_ands_implicit((Expr *) predExprs);
1154 }
1155
1156 /*
1157 * Partial indexes affect each form of ON CONFLICT differently: if a
1158 * constraint was named, then the predicates must be identical. In
1159 * conventional inference, the index's predicate must be implied by
1160 * the WHERE clause.
1161 */
1162 if (OidIsValid(indexOidFromConstraint))
1163 {
1164 if (list_difference(predExprs, inferIndexExprs) != NIL)
1165 continue;
1166 }
1167 else
1168 {
1169 if (!predicate_implied_by(predExprs, inferIndexExprs, false))
1170 continue;
1171 }
1172
1173 /* All good -- consider this index a match */
1174 results = lappend_oid(results, idxForm->indexrelid);
1175 foundValid |= idxForm->indisvalid;
1176 }
1177
1178 /* Close all indexes */
1179 foreach_ptr(RelationData, idxRel, indexRelList)
1180 {
1181 index_close(idxRel, NoLock);
1182 }
1183
1184 list_free(indexList);
1185 list_free(indexRelList);
1186 table_close(relation, NoLock);
1187
1188 /* We require at least one indisvalid index */
1189 if (results == NIL || !foundValid)
1190 ereport(ERROR,
1191 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1192 errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
1193
1194 return results;
1195}
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
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:1204
@ ONCONFLICT_UPDATE
Definition: nodes.h:430
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define foreach_ptr(type, var, lst)
Definition: pg_list.h:469
#define foreach_oid(var, lst)
Definition: pg_list.h:471
static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel, List *idxExprs)
Definition: plancat.c:1225
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:152
List * arbiterElems
Definition: primnodes.h:2376
OnConflictAction action
Definition: primnodes.h:2373
Node * arbiterWhere
Definition: primnodes.h:2378
AttrNumber varattno
Definition: primnodes.h:274

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, Assert(), bms_add_member(), bms_equal(), ChangeVarNodes(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, eval_const_expressions(), FirstLowInvalidHeapAttributeNumber, foreach_oid, foreach_ptr, get_constraint_index(), if(), index_close(), index_open(), infer_collation_opclass_match(), InvalidAttrNumber, InvalidOid, IsA, lappend(), lappend_oid(), list_difference(), list_free(), list_member(), make_ands_explicit(), make_ands_implicit(), NIL, NoLock, OidIsValid, ONCONFLICT_UPDATE, predicate_implied_by(), RelationData::rd_rel, 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 1225 of file plancat.c.

1227{
1228 AttrNumber natt;
1229 Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
1230 Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
1231 int nplain = 0; /* # plain attrs observed */
1232
1233 /*
1234 * If inference specification element lacks collation/opclass, then no
1235 * need to check for exact match.
1236 */
1237 if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
1238 return true;
1239
1240 /*
1241 * Lookup opfamily and input type, for matching indexes
1242 */
1243 if (elem->inferopclass)
1244 {
1245 inferopfamily = get_opclass_family(elem->inferopclass);
1246 inferopcinputtype = get_opclass_input_type(elem->inferopclass);
1247 }
1248
1249 for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
1250 {
1251 Oid opfamily = idxRel->rd_opfamily[natt - 1];
1252 Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
1253 Oid collation = idxRel->rd_indcollation[natt - 1];
1254 int attno = idxRel->rd_index->indkey.values[natt - 1];
1255
1256 if (attno != 0)
1257 nplain++;
1258
1259 if (elem->inferopclass != InvalidOid &&
1260 (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
1261 {
1262 /* Attribute needed to match opclass, but didn't */
1263 continue;
1264 }
1265
1266 if (elem->infercollid != InvalidOid &&
1267 elem->infercollid != collation)
1268 {
1269 /* Attribute needed to match collation, but didn't */
1270 continue;
1271 }
1272
1273 /* If one matching index att found, good enough -- return true */
1274 if (IsA(elem->expr, Var))
1275 {
1276 if (((Var *) elem->expr)->varattno == attno)
1277 return true;
1278 }
1279 else if (attno == 0)
1280 {
1281 Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
1282
1283 /*
1284 * Note that unlike routines like match_index_to_operand() we
1285 * don't need to care about RelabelType. Neither the index
1286 * definition nor the inference clause should contain them.
1287 */
1288 if (equal(elem->expr, nattExpr))
1289 return true;
1290 }
1291 }
1292
1293 return false;
1294}
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1329
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1307
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 2263 of file plancat.c.

2269{
2270 RegProcedure oprjoin = get_oprjoin(operatorid);
2271 float8 result;
2272
2273 /*
2274 * if the oprjoin procedure is missing for whatever reason, use a
2275 * selectivity of 0.5
2276 */
2277 if (!oprjoin)
2278 return (Selectivity) 0.5;
2279
2280 result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
2281 inputcollid,
2283 ObjectIdGetDatum(operatorid),
2285 Int16GetDatum(jointype),
2286 PointerGetDatum(sjinfo)));
2287
2288 if (result < 0.0 || result > 1.0)
2289 elog(ERROR, "invalid join selectivity: %f", result);
2290
2291 return (Selectivity) result;
2292}
double float8
Definition: c.h:649
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1454
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1746
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:182
static float8 DatumGetFloat8(Datum X)
Definition: postgres.h:475

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

1853{
1854 bool include_noinherit;
1855 bool include_notnull;
1856 bool include_partition = false;
1857 List *safe_restrictions;
1858 List *constraint_pred;
1859 List *safe_constraints;
1860 ListCell *lc;
1861
1862 /* As of now, constraint exclusion works only with simple relations. */
1863 Assert(IS_SIMPLE_REL(rel));
1864
1865 /*
1866 * If there are no base restriction clauses, we have no hope of proving
1867 * anything below, so fall out quickly.
1868 */
1869 if (rel->baserestrictinfo == NIL)
1870 return false;
1871
1872 /*
1873 * Regardless of the setting of constraint_exclusion, detect
1874 * constant-FALSE-or-NULL restriction clauses. Although const-folding
1875 * will reduce "anything AND FALSE" to just "FALSE", the baserestrictinfo
1876 * list can still have other members besides the FALSE constant, due to
1877 * qual pushdown and other mechanisms; so check them all. This doesn't
1878 * fire very often, but it seems cheap enough to be worth doing anyway.
1879 * (Without this, we'd miss some optimizations that 9.5 and earlier found
1880 * via much more roundabout methods.)
1881 */
1882 foreach(lc, rel->baserestrictinfo)
1883 {
1884 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1885 Expr *clause = rinfo->clause;
1886
1887 if (clause && IsA(clause, Const) &&
1888 (((Const *) clause)->constisnull ||
1889 !DatumGetBool(((Const *) clause)->constvalue)))
1890 return true;
1891 }
1892
1893 /*
1894 * Skip further tests, depending on constraint_exclusion.
1895 */
1896 switch (constraint_exclusion)
1897 {
1899 /* In 'off' mode, never make any further tests */
1900 return false;
1901
1903
1904 /*
1905 * When constraint_exclusion is set to 'partition' we only handle
1906 * appendrel members. Partition pruning has already been applied,
1907 * so there is no need to consider the rel's partition constraints
1908 * here.
1909 */
1911 break; /* appendrel member, so process it */
1912 return false;
1913
1915
1916 /*
1917 * In 'on' mode, always apply constraint exclusion. If we are
1918 * considering a baserel that is a partition (i.e., it was
1919 * directly named rather than expanded from a parent table), then
1920 * its partition constraints haven't been considered yet, so
1921 * include them in the processing here.
1922 */
1923 if (rel->reloptkind == RELOPT_BASEREL)
1924 include_partition = true;
1925 break; /* always try to exclude */
1926 }
1927
1928 /*
1929 * Check for self-contradictory restriction clauses. We dare not make
1930 * deductions with non-immutable functions, but any immutable clauses that
1931 * are self-contradictory allow us to conclude the scan is unnecessary.
1932 *
1933 * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1934 * expecting to see any in its predicate argument.
1935 */
1936 safe_restrictions = NIL;
1937 foreach(lc, rel->baserestrictinfo)
1938 {
1939 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1940
1941 if (!contain_mutable_functions((Node *) rinfo->clause))
1942 safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1943 }
1944
1945 /*
1946 * We can use weak refutation here, since we're comparing restriction
1947 * clauses with restriction clauses.
1948 */
1949 if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
1950 return true;
1951
1952 /*
1953 * Only plain relations have constraints, so stop here for other rtekinds.
1954 */
1955 if (rte->rtekind != RTE_RELATION)
1956 return false;
1957
1958 /*
1959 * If we are scanning just this table, we can use NO INHERIT constraints,
1960 * but not if we're scanning its children too. (Note that partitioned
1961 * tables should never have NO INHERIT constraints; but it's not necessary
1962 * for us to assume that here.)
1963 */
1964 include_noinherit = !rte->inh;
1965
1966 /*
1967 * Currently, attnotnull constraints must be treated as NO INHERIT unless
1968 * this is a partitioned table. In future we might track their
1969 * inheritance status more accurately, allowing this to be refined.
1970 *
1971 * XXX do we need/want to change this?
1972 */
1973 include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
1974
1975 /*
1976 * Fetch the appropriate set of constraint expressions.
1977 */
1978 constraint_pred = get_relation_constraints(root, rte->relid, rel,
1979 include_noinherit,
1980 include_notnull,
1981 include_partition);
1982
1983 /*
1984 * We do not currently enforce that CHECK constraints contain only
1985 * immutable functions, so it's necessary to check here. We daren't draw
1986 * conclusions from plan-time evaluation of non-immutable functions. Since
1987 * they're ANDed, we can just ignore any mutable constraints in the list,
1988 * and reason about the rest.
1989 */
1990 safe_constraints = NIL;
1991 foreach(lc, constraint_pred)
1992 {
1993 Node *pred = (Node *) lfirst(lc);
1994
1995 if (!contain_mutable_functions(pred))
1996 safe_constraints = lappend(safe_constraints, pred);
1997 }
1998
1999 /*
2000 * The constraints are effectively ANDed together, so we can just try to
2001 * refute the entire collection at once. This may allow us to make proofs
2002 * that would fail if we took them individually.
2003 *
2004 * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
2005 * an obvious optimization. Some of the clauses might be OR clauses that
2006 * have volatile and nonvolatile subclauses, and it's OK to make
2007 * deductions with the nonvolatile parts.
2008 *
2009 * We need strong refutation because we have to prove that the constraints
2010 * would yield false, not just NULL.
2011 */
2012 if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
2013 return true;
2014
2015 return false;
2016}
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:382
@ 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:895
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:885
int constraint_exclusion
Definition: plancat.c:58
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_noinherit, bool include_notnull, bool include_partition)
Definition: plancat.c:1515
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:222
List * baserestrictinfo
Definition: pathnodes.h:1046
Expr * clause
Definition: pathnodes.h:2792

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

2229{
2230 RegProcedure oprrest = get_oprrest(operatorid);
2231 float8 result;
2232
2233 /*
2234 * if the oprrest procedure is missing for whatever reason, use a
2235 * selectivity of 0.5
2236 */
2237 if (!oprrest)
2238 return (Selectivity) 0.5;
2239
2240 result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
2241 inputcollid,
2243 ObjectIdGetDatum(operatorid),
2245 Int32GetDatum(varRelid)));
2246
2247 if (result < 0.0 || result > 1.0)
2248 elog(ERROR, "invalid restriction selectivity: %f", result);
2249
2250 return (Selectivity) result;
2251}
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1443
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1722
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222

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

2892{
2893 List *partconstr;
2894
2895 if (rel->partition_qual) /* already done */
2896 return;
2897
2898 /*
2899 * Run the partition quals through const-simplification similar to check
2900 * constraints. We skip canonicalize_qual, though, because partition
2901 * quals should be in canonical form already; also, since the qual is in
2902 * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2903 * format and back again.
2904 */
2905 partconstr = RelationGetPartitionQual(relation);
2906 if (partconstr)
2907 {
2908 partconstr = (List *) expression_planner((Expr *) partconstr);
2909 if (rel->relid != 1)
2910 ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2911 rel->partition_qual = partconstr;
2912 }
2913}
List * RelationGetPartitionQual(Relation rel)
Definition: partcache.c:277
Expr * expression_planner(Expr *expr)
Definition: planner.c:6763

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

2825{
2826 PartitionKey partkey = RelationGetPartitionKey(relation);
2827 int partnatts;
2828 int cnt;
2829 List **partexprs;
2830 ListCell *lc;
2831 Index varno = rel->relid;
2832
2833 Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2834
2835 /* A partitioned table should have a partition key. */
2836 Assert(partkey != NULL);
2837
2838 partnatts = partkey->partnatts;
2839 partexprs = palloc_array(List *, partnatts);
2840 lc = list_head(partkey->partexprs);
2841
2842 for (cnt = 0; cnt < partnatts; cnt++)
2843 {
2844 Expr *partexpr;
2845 AttrNumber attno = partkey->partattrs[cnt];
2846
2847 if (attno != InvalidAttrNumber)
2848 {
2849 /* Single column partition key is stored as a Var node. */
2850 Assert(attno > 0);
2851
2852 partexpr = (Expr *) makeVar(varno, attno,
2853 partkey->parttypid[cnt],
2854 partkey->parttypmod[cnt],
2855 partkey->parttypcoll[cnt], 0);
2856 }
2857 else
2858 {
2859 if (lc == NULL)
2860 elog(ERROR, "wrong number of partition key expressions");
2861
2862 /* Re-stamp the expression with given varno. */
2863 partexpr = (Expr *) copyObject(lfirst(lc));
2864 ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2865 lc = lnext(partkey->partexprs, lc);
2866 }
2867
2868 /* Base relations have a single expression per key. */
2869 partexprs[cnt] = list_make1(partexpr);
2870 }
2871
2872 rel->partexprs = partexprs;
2873
2874 /*
2875 * A base relation does not have nullable partition key expressions, since
2876 * no outer join is involved. We still allocate an array of empty
2877 * expression lists to keep partition key expression handling code simple.
2878 * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2879 */
2880 rel->nullable_partexprs = palloc0_array(List *, partnatts);
2881}
#define palloc0_array(type, count)
Definition: fe_memutils.h:77
#define copyObject(obj)
Definition: nodes.h:232
#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(), palloc0_array, palloc_array, 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 2687 of file plancat.c.

2689{
2690 PartitionDesc partdesc;
2691
2692 /*
2693 * Create the PartitionDirectory infrastructure if we didn't already.
2694 */
2695 if (root->glob->partition_directory == NULL)
2696 {
2697 root->glob->partition_directory =
2699 }
2700
2701 partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
2702 relation);
2703 rel->part_scheme = find_partition_scheme(root, relation);
2704 Assert(partdesc != NULL && rel->part_scheme != NULL);
2705 rel->boundinfo = partdesc->boundinfo;
2706 rel->nparts = partdesc->nparts;
2707 set_baserel_partition_key_exprs(relation, rel);
2708 set_baserel_partition_constraint(relation, rel);
2709}
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:2717
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition: plancat.c:2823
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 58 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ get_relation_info_hook

get_relation_info_hook_type get_relation_info_hook = NULL

Definition at line 61 of file plancat.c.

Referenced by get_relation_info().