PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 2369 of file plancat.c.

2371{
2374
2377 elog(ERROR, "cache lookup failed for function %u", funcid);
2379
2380 if (OidIsValid(procform->prosupport))
2381 {
2384
2386 req.root = root;
2387 req.funcid = funcid;
2388 req.node = node;
2389
2390 /* Initialize cost fields so that support function doesn't have to */
2391 req.startup = 0;
2392 req.per_tuple = 0;
2393
2396 PointerGetDatum(&req)));
2397
2398 if (sresult == &req)
2399 {
2400 /* Success, so accumulate support function's estimate into *cost */
2401 cost->startup += req.startup;
2402 cost->per_tuple += req.per_tuple;
2404 return;
2405 }
2406 }
2407
2408 /* No support function, or it failed, so rely on procost */
2409 cost->per_tuple += procform->procost * cpu_operator_cost;
2410
2412}
#define OidIsValid(objectId)
Definition c.h:800
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:722
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
END_CATALOG_STRUCT typedef FormData_pg_proc * Form_pg_proc
Definition pg_proc.h:140
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
static int fb(int x)
tree ctl root
Definition radixtree.h:1857
Cost per_tuple
Definition pathnodes.h:121
Cost startup
Definition pathnodes.h:120
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220

References cpu_operator_cost, DatumGetPointer(), elog, ERROR, fb(), Form_pg_proc, GETSTRUCT(), HeapTupleIsValid, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, QualCost::per_tuple, PointerGetDatum(), ReleaseSysCache(), root, SearchSysCache1(), QualCost::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 2174 of file plancat.c.

2176{
2177 List *tlist = NIL;
2178 Index varno = index->rel->relid;
2180 int i;
2181
2182 indexpr_item = list_head(index->indexprs);
2183 for (i = 0; i < index->ncolumns; i++)
2184 {
2185 int indexkey = index->indexkeys[i];
2186 Expr *indexvar;
2187
2188 if (indexkey != 0)
2189 {
2190 /* simple column */
2192
2193 if (indexkey < 0)
2195 else
2196 att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
2197
2198 indexvar = (Expr *) makeVar(varno,
2199 indexkey,
2200 att_tup->atttypid,
2201 att_tup->atttypmod,
2202 att_tup->attcollation,
2203 0);
2204 }
2205 else
2206 {
2207 /* expression column */
2208 if (indexpr_item == NULL)
2209 elog(ERROR, "wrong number of index expressions");
2211 indexpr_item = lnext(index->indexprs, indexpr_item);
2212 }
2213
2214 tlist = lappend(tlist,
2216 i + 1,
2217 NULL,
2218 false));
2219 }
2220 if (indexpr_item != NULL)
2221 elog(ERROR, "wrong number of index expressions");
2222
2223 return tlist;
2224}
unsigned int Index
Definition c.h:640
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
#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, fb(), 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 2053 of file plancat.c.

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

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

References fb(), get_rel_data_width(), 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 2729 of file plancat.c.

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

References Assert, CurrentMemoryContext, fb(), fmgr_info_copy(), i, lappend(), lfirst, palloc0_object, palloc_array, RelationGetPartitionKey(), and root.

Referenced by set_relation_partition_info().

◆ find_relation_notnullatts()

Bitmapset * find_relation_notnullatts ( PlannerInfo root,
Oid  relid 
)

Definition at line 777 of file plancat.c.

778{
780 bool found;
781
782 if (root->glob->rel_notnullatts_hash == NULL)
783 return NULL;
784
785 hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
786 &relid,
787 HASH_FIND,
788 &found);
789 if (!found)
790 return NULL;
791
792 return hentry->notnullattnums;
793}
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 fb(), HASH_FIND, hash_search(), NotnullHashEntry::notnullattnums, and root.

Referenced by get_relation_info(), has_notnull_forced_var(), 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 2315 of file plancat.c.

2323{
2327
2328 if (!prosupport)
2329 return (Selectivity) -1; /* no support function */
2330
2332 req.root = root;
2333 req.funcid = funcid;
2334 req.args = args;
2335 req.inputcollid = inputcollid;
2336 req.is_join = is_join;
2337 req.varRelid = varRelid;
2338 req.jointype = jointype;
2339 req.sjinfo = sjinfo;
2340 req.selectivity = -1; /* to catch failure to set the value */
2341
2344 PointerGetDatum(&req)));
2345
2346 if (sresult != &req)
2347 return (Selectivity) -1; /* function did not honor request */
2348
2349 if (req.selectivity < 0.0 || req.selectivity > 1.0)
2350 elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2351
2352 return (Selectivity) req.selectivity;
2353}
regproc RegProcedure
Definition c.h:676
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2008
double Selectivity
Definition nodes.h:260

References DatumGetPointer(), elog, ERROR, fb(), get_func_support(), OidFunctionCall1, PointerGetDatum(), root, and SupportRequestSelectivity::type.

Referenced by clause_selectivity_ext().

◆ get_dependent_generated_columns()

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

Definition at line 2651 of file plancat.c.

2653{
2656 Relation relation;
2657 TupleDesc tupdesc;
2658 TupleConstr *constr;
2659
2660 /* Assume we already have adequate lock */
2661 relation = table_open(rte->relid, NoLock);
2662
2663 tupdesc = RelationGetDescr(relation);
2664 constr = tupdesc->constr;
2665
2666 if (constr && constr->has_generated_stored)
2667 {
2668 for (int i = 0; i < constr->num_defval; i++)
2669 {
2670 AttrDefault *defval = &constr->defval[i];
2671 Node *expr;
2672 Bitmapset *attrs_used = NULL;
2673
2674 /* skip if not generated column */
2675 if (!TupleDescCompactAttr(tupdesc, defval->adnum - 1)->attgenerated)
2676 continue;
2677
2678 /* identify columns this generated column depends on */
2679 expr = stringToNode(defval->adbin);
2680 pull_varattnos(expr, 1, &attrs_used);
2681
2682 if (bms_overlap(target_cols, attrs_used))
2685 }
2686 }
2687
2688 table_close(relation, NoLock);
2689
2690 return dependentCols;
2691}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:575
void * stringToNode(const char *str)
Definition read.c:90
#define RelationGetDescr(relation)
Definition rel.h:540
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, fb(), 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 2430 of file plancat.c.

2431{
2434 double result;
2435
2438 elog(ERROR, "cache lookup failed for function %u", funcid);
2440
2441 Assert(procform->proretset); /* else caller error */
2442
2443 if (OidIsValid(procform->prosupport))
2444 {
2447
2449 req.root = root;
2450 req.funcid = funcid;
2451 req.node = node;
2452
2453 req.rows = 0; /* just for sanity */
2454
2457 PointerGetDatum(&req)));
2458
2459 if (sresult == &req)
2460 {
2461 /* Success */
2463 return req.rows;
2464 }
2465 }
2466
2467 /* No support function, or it failed, so rely on prorows */
2468 result = procform->prorows;
2469
2471
2472 return result;
2473}

References Assert, DatumGetPointer(), elog, ERROR, fb(), Form_pg_proc, GETSTRUCT(), HeapTupleIsValid, ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, PointerGetDatum(), ReleaseSysCache(), root, 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 1444 of file plancat.c.

1445{
1446 int64 tuple_width = 0;
1447 int i;
1448
1449 for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1450 {
1453
1454 if (att->attisdropped)
1455 continue;
1456
1457 /* use previously cached data, if any */
1458 if (attr_widths != NULL && attr_widths[i] > 0)
1459 {
1461 continue;
1462 }
1463
1464 /* This should match set_rel_width() in costsize.c */
1466 if (item_width <= 0)
1467 {
1468 item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1469 Assert(item_width > 0);
1470 }
1471 if (attr_widths != NULL)
1474 }
1475
1477}
int64_t int64
Definition c.h:555
int32 clamp_width_est(int64 tuple_width)
Definition costsize.c:242
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition lsyscache.c:3310
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition lsyscache.c:2730
#define RelationGetRelid(relation)
Definition rel.h:514

References Assert, clamp_width_est(), fb(), 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 1527 of file plancat.c.

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

References Assert, 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(), fb(), TupleConstr::has_not_null, i, IS_NOT_NULL, lappend(), list_concat(), Var::location, make_ands_implicit(), makeNode, makeVar(), TupleDescData::natts, NIL, NoLock, 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 1486 of file plancat.c.

1487{
1488 int32 result;
1489 Relation relation;
1490
1491 /* As above, assume relation is already locked */
1492 relation = table_open(relid, NoLock);
1493
1494 result = get_rel_data_width(relation, attr_widths);
1495
1496 table_close(relation, NoLock);
1497
1498 return result;
1499}

References fb(), 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 598 of file plancat.c.

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

References Assert, ForeignKeyOptInfo::con_relid, ForeignKeyOptInfo::eclass, fb(), ForeignKeyOptInfo::fk_eclass_member, lappend(), lfirst, list_length(), makeNode, ForeignKeyOptInfo::nconst_ec, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_rcols, ForeignKeyOptInfo::nmatched_ri, ForeignKeyOptInfo::ref_relid, RelationGetFKeyList(), RelationGetRelid, RelOptInfo::relid, RELOPT_BASEREL, RelOptInfo::reloptkind, ForeignKeyOptInfo::rinfos, root, and RTE_RELATION.

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;
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 */
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))
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())
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)
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 {
215 ListCell *l;
216
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;
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 &&
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
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
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 &&
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 *
580 * An extension can also modify rel->pgs_mask here to control path
581 * generation.
582 */
584 (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
585}
#define unlikely(x)
Definition c.h:424
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:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#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)
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:259
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:1417
bool IgnoreSystemIndexes
Definition miscinit.c:81
Bitmapset * Relids
Definition pathnodes.h:103
#define AMFLAG_HAS_TID_RANGE
Definition pathnodes.h:961
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
END_CATALOG_STRUCT typedef FormData_pg_index * Form_pg_index
Definition pg_index.h:74
#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:1319
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition plancat.c:598
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:1752
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition plancat.c:2174
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition plancat.c:2699
Bitmapset * find_relation_notnullatts(PlannerInfo *root, Oid relid)
Definition plancat.c:777
int restrict_nonsystem_relation_kind
Definition postgres.c:107
#define InvalidOid
#define RelationGetForm(relation)
Definition rel.h:508
#define RelationGetParallelWorkers(relation, defaultpw)
Definition rel.h:408
#define RelationGetRelationName(relation)
Definition rel.h:548
#define RelationIsPermanent(relation)
Definition rel.h:626
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4831
List * RelationGetIndexPredicate(Relation relation)
Definition relcache.c:5205
List * RelationGetIndexExpressions(Relation relation)
Definition relcache.c:5092
bytea ** RelationGetIndexAttOptions(Relation relation, bool copy)
Definition relcache.c:5983
TransactionId TransactionXmin
Definition snapmgr.c:159
HeapTupleHeader t_data
Definition htup.h:68
bool amcanparallel
Definition pathnodes.h:1430
void(* amcostestimate)(struct PlannerInfo *, struct IndexPath *, double, Cost *, Cost *, Selectivity *, double *, double *) pg_node_attr(read_write_ignore)
Definition pathnodes.h:1435
bool amoptionalkey
Definition pathnodes.h:1423
bool amcanmarkpos
Definition pathnodes.h:1432
List * indrestrictinfo
Definition pathnodes.h:1405
bool amhasgettuple
Definition pathnodes.h:1427
bool amcanorderbyop
Definition pathnodes.h:1422
bool hypothetical
Definition pathnodes.h:1416
bool nullsnotdistinct
Definition pathnodes.h:1412
List * indpred
Definition pathnodes.h:1395
Cardinality tuples
Definition pathnodes.h:1353
bool amsearcharray
Definition pathnodes.h:1424
BlockNumber pages
Definition pathnodes.h:1351
bool amsearchnulls
Definition pathnodes.h:1425
bool amhasgetbitmap
Definition pathnodes.h:1429
List * indextlist
Definition pathnodes.h:1398
uint32 amflags
Definition pathnodes.h:1093
Bitmapset * notnullattnums
Definition pathnodes.h:1071
List * statlist
Definition pathnodes.h:1081
Cardinality tuples
Definition pathnodes.h:1084
BlockNumber pages
Definition pathnodes.h:1083
List * indexlist
Definition pathnodes.h:1079
Oid reltablespace
Definition pathnodes.h:1059
int rel_parallel_workers
Definition pathnodes.h:1091
AttrNumber max_attr
Definition pathnodes.h:1065
double allvisfrac
Definition pathnodes.h:1085
AttrNumber min_attr
Definition pathnodes.h:1063
const struct IndexAmRoutine * rd_indam
Definition rel.h:206
const struct TableAmRoutine * rd_tableam
Definition rel.h:189
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:792
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:6460

References RelOptInfo::allvisfrac, IndexOptInfo::amcanmarkpos, IndexOptInfo::amcanorderbyop, IndexOptInfo::amcanparallel, IndexOptInfo::amcostestimate, AMFLAG_HAS_TID_RANGE, RelOptInfo::amflags, IndexOptInfo::amhasgetbitmap, IndexOptInfo::amhasgettuple, IndexOptInfo::amoptionalkey, IndexOptInfo::amsearcharray, IndexOptInfo::amsearchnulls, Assert, build_index_tlist(), ChangeVarNodes(), COMPARE_LT, ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, estimate_rel_size(), eval_const_expressions(), fb(), find_relation_notnullatts(), FirstLowInvalidHeapAttributeNumber, FirstNormalObjectId, Form_pg_index, 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 704 of file plancat.c.

705{
706 Oid relid = RelationGetRelid(relation);
708 bool found;
709 Bitmapset *notnullattnums = NULL;
710
711 /* bail out if the relation has no not-null constraints */
712 if (relation->rd_att->constr == NULL ||
713 !relation->rd_att->constr->has_not_null)
714 return;
715
716 /* create the hash table if it hasn't been created yet */
717 if (root->glob->rel_notnullatts_hash == NULL)
718 {
719 HTAB *hashtab;
721
722 hash_ctl.keysize = sizeof(Oid);
723 hash_ctl.entrysize = sizeof(NotnullHashEntry);
725
726 hashtab = hash_create("Relation NOT NULL attnums",
727 64L, /* arbitrary initial size */
728 &hash_ctl,
730
731 root->glob->rel_notnullatts_hash = hashtab;
732 }
733
734 /*
735 * Create a hash entry for this relation OID, if we don't have one
736 * already.
737 */
738 hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
739 &relid,
741 &found);
742
743 /* bail out if a hash entry already exists for this relation OID */
744 if (found)
745 return;
746
747 /* collect the column not-null constraint information for this relation */
748 for (int i = 0; i < relation->rd_att->natts; i++)
749 {
750 CompactAttribute *attr = TupleDescCompactAttr(relation->rd_att, i);
751
753
755 {
756 notnullattnums = bms_add_member(notnullattnums, i + 1);
757
758 /*
759 * Per RemoveAttributeById(), dropped columns will have their
760 * attnotnull unset, so we needn't check for dropped columns in
761 * the above condition.
762 */
763 Assert(!attr->attisdropped);
764 }
765 }
766
767 /* ... and initialize the new hash entry */
768 hentry->notnullattnums = notnullattnums;
769}
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
bool attisdropped
Definition tupdesc.h:77
char attnullability
Definition tupdesc.h:79
Size keysize
Definition hsearch.h:75
#define ATTNULLABLE_UNKNOWN
Definition tupdesc.h:85

References Assert, CompactAttribute::attisdropped, CompactAttribute::attnullability, ATTNULLABLE_UNKNOWN, ATTNULLABLE_VALID, bms_add_member(), TupleDescData::constr, CurrentMemoryContext, fb(), TupleConstr::has_not_null, HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), i, HASHCTL::keysize, TupleDescData::natts, 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 1752 of file plancat.c.

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

References bms_add_member(), bms_free(), ChangeVarNodes(), elog, ERROR, eval_const_expressions(), fb(), fix_opfuncids(), Form_pg_statistic_ext, 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 1669 of file plancat.c.

1672{
1675
1677 ObjectIdGetDatum(statOid), BoolGetDatum(inh));
1678 if (!HeapTupleIsValid(dtup))
1679 return;
1680
1682
1683 /* add one StatisticExtInfo for each kind built */
1685 {
1687
1688 info->statOid = statOid;
1689 info->inherit = dataForm->stxdinherit;
1690 info->rel = rel;
1691 info->kind = STATS_EXT_NDISTINCT;
1692 info->keys = bms_copy(keys);
1693 info->exprs = exprs;
1694
1695 *stainfos = lappend(*stainfos, info);
1696 }
1697
1699 {
1701
1702 info->statOid = statOid;
1703 info->inherit = dataForm->stxdinherit;
1704 info->rel = rel;
1706 info->keys = bms_copy(keys);
1707 info->exprs = exprs;
1708
1709 *stainfos = lappend(*stainfos, info);
1710 }
1711
1713 {
1715
1716 info->statOid = statOid;
1717 info->inherit = dataForm->stxdinherit;
1718 info->rel = rel;
1719 info->kind = STATS_EXT_MCV;
1720 info->keys = bms_copy(keys);
1721 info->exprs = exprs;
1722
1723 *stainfos = lappend(*stainfos, info);
1724 }
1725
1727 {
1729
1730 info->statOid = statOid;
1731 info->inherit = dataForm->stxdinherit;
1732 info->rel = rel;
1734 info->keys = bms_copy(keys);
1735 info->exprs = exprs;
1736
1737 *stainfos = lappend(*stainfos, info);
1738 }
1739
1741}
Bitmapset * bms_copy(const Bitmapset *a)
Definition bitmapset.c:122
bool statext_is_kind_built(HeapTuple htup, char type)
END_CATALOG_STRUCT typedef FormData_pg_statistic_ext_data * Form_pg_statistic_ext_data
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
Bitmapset * keys
Definition pathnodes.h:1515
HeapTuple SearchSysCache2(SysCacheIdentifier cacheId, Datum key1, Datum key2)
Definition syscache.c:230

References bms_copy(), BoolGetDatum(), StatisticExtInfo::exprs, fb(), Form_pg_statistic_ext_data, 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 2520 of file plancat.c.

2521{
2523 Relation relation;
2525 bool result = false;
2526
2527 /* Assume we already have adequate lock */
2528 relation = table_open(rte->relid, NoLock);
2529
2530 trigDesc = relation->trigdesc;
2531 switch (event)
2532 {
2533 case CMD_INSERT:
2534 if (trigDesc &&
2535 (trigDesc->trig_insert_after_row ||
2536 trigDesc->trig_insert_before_row))
2537 result = true;
2538 break;
2539 case CMD_UPDATE:
2540 if (trigDesc &&
2541 (trigDesc->trig_update_after_row ||
2542 trigDesc->trig_update_before_row))
2543 result = true;
2544 break;
2545 case CMD_DELETE:
2546 if (trigDesc &&
2547 (trigDesc->trig_delete_after_row ||
2548 trigDesc->trig_delete_before_row))
2549 result = true;
2550 break;
2551 /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2552 case CMD_MERGE:
2553 result = false;
2554 break;
2555 default:
2556 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2557 break;
2558 }
2559
2560 table_close(relation, NoLock);
2561 return result;
2562}
@ 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

References CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, elog, ERROR, fb(), NoLock, planner_rt_fetch, root, table_close(), table_open(), and RelationData::trigdesc.

Referenced by make_modifytable().

◆ has_stored_generated_columns()

bool has_stored_generated_columns ( PlannerInfo root,
Index  rti 
)

Definition at line 2624 of file plancat.c.

2625{
2627 Relation relation;
2628 TupleDesc tupdesc;
2629 bool result = false;
2630
2631 /* Assume we already have adequate lock */
2632 relation = table_open(rte->relid, NoLock);
2633
2634 tupdesc = RelationGetDescr(relation);
2635 result = tupdesc->constr && tupdesc->constr->has_generated_stored;
2636
2637 table_close(relation, NoLock);
2638
2639 return result;
2640}

References TupleDescData::constr, fb(), 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 2570 of file plancat.c.

2571{
2573 Relation relation;
2575 bool result = false;
2576
2577 Assert(rte->rtekind == RTE_RELATION);
2578
2579 /* Currently foreign tables cannot have transition tables */
2580 if (rte->relkind == RELKIND_FOREIGN_TABLE)
2581 return result;
2582
2583 /* Assume we already have adequate lock */
2584 relation = table_open(rte->relid, NoLock);
2585
2586 trigDesc = relation->trigdesc;
2587 switch (event)
2588 {
2589 case CMD_INSERT:
2590 if (trigDesc &&
2591 trigDesc->trig_insert_new_table)
2592 result = true;
2593 break;
2594 case CMD_UPDATE:
2595 if (trigDesc &&
2596 (trigDesc->trig_update_old_table ||
2597 trigDesc->trig_update_new_table))
2598 result = true;
2599 break;
2600 case CMD_DELETE:
2601 if (trigDesc &&
2602 trigDesc->trig_delete_old_table)
2603 result = true;
2604 break;
2605 /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
2606 case CMD_MERGE:
2607 result = false;
2608 break;
2609 default:
2610 elog(ERROR, "unrecognized CmdType: %d", (int) event);
2611 break;
2612 }
2613
2614 table_close(relation, NoLock);
2615 return result;
2616}

References Assert, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, elog, ERROR, fb(), NoLock, planner_rt_fetch, root, RTE_RELATION, table_close(), table_open(), and RelationData::trigdesc.

Referenced by make_modifytable().

◆ has_unique_index()

bool has_unique_index ( RelOptInfo rel,
AttrNumber  attno 
)

Definition at line 2488 of file plancat.c.

2489{
2490 ListCell *ilist;
2491
2492 foreach(ilist, rel->indexlist)
2493 {
2495
2496 /*
2497 * Note: ignore partial indexes, since they don't allow us to conclude
2498 * that all attr values are distinct, *unless* they are marked predOK
2499 * which means we know the index's predicate is satisfied by the
2500 * query. We don't take any interest in expressional indexes either.
2501 * Also, a multicolumn unique index doesn't allow us to conclude that
2502 * just the specified attr is unique.
2503 */
2504 if (index->unique &&
2505 index->nkeycolumns == 1 &&
2506 index->indexkeys[0] == attno &&
2507 (index->indpred == NIL || index->predOK))
2508 return true;
2509 }
2510 return false;
2511}

References fb(), RelOptInfo::indexlist, lfirst, and NIL.

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List * infer_arbiter_indexes ( PlannerInfo root)

Definition at line 816 of file plancat.c.

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

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, Assert, bms_add_member(), bms_equal(), ChangeVarNodes(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, eval_const_expressions(), fb(), FirstLowInvalidHeapAttributeNumber, foreach_oid, foreach_ptr, Form_pg_index, get_constraint_index(), 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_SELECT, 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 1237 of file plancat.c.

1239{
1241 Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
1242 Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
1243 int nplain = 0; /* # plain attrs observed */
1244
1245 /*
1246 * If inference specification element lacks collation/opclass, then no
1247 * need to check for exact match.
1248 */
1249 if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
1250 return true;
1251
1252 /*
1253 * Lookup opfamily and input type, for matching indexes
1254 */
1255 if (elem->inferopclass)
1256 {
1259 }
1260
1261 for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
1262 {
1263 Oid opfamily = idxRel->rd_opfamily[natt - 1];
1264 Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
1265 Oid collation = idxRel->rd_indcollation[natt - 1];
1266 int attno = idxRel->rd_index->indkey.values[natt - 1];
1267
1268 if (attno != 0)
1269 nplain++;
1270
1271 if (elem->inferopclass != InvalidOid &&
1272 (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
1273 {
1274 /* Attribute needed to match opclass, but didn't */
1275 continue;
1276 }
1277
1278 if (elem->infercollid != InvalidOid &&
1279 elem->infercollid != collation)
1280 {
1281 /* Attribute needed to match collation, but didn't */
1282 continue;
1283 }
1284
1285 /* If one matching index att found, good enough -- return true */
1286 if (IsA(elem->expr, Var))
1287 {
1288 if (((Var *) elem->expr)->varattno == attno)
1289 return true;
1290 }
1291 else if (attno == 0)
1292 {
1294
1295 /*
1296 * Note that unlike routines like match_index_to_operand() we
1297 * don't need to care about RelabelType. Neither the index
1298 * definition nor the inference clause should contain them.
1299 */
1300 if (equal(elem->expr, nattExpr))
1301 return true;
1302 }
1303 }
1304
1305 return false;
1306}
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
Oid get_opclass_input_type(Oid opclass)
Definition lsyscache.c:1314
Oid get_opclass_family(Oid opclass)
Definition lsyscache.c:1292
static void * list_nth(const List *list, int n)
Definition pg_list.h:299

References equal(), InferenceElem::expr, fb(), get_opclass_family(), get_opclass_input_type(), InferenceElem::infercollid, InferenceElem::inferopclass, InvalidOid, IsA, and list_nth().

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

2281{
2283 float8 result;
2284
2285 /*
2286 * if the oprjoin procedure is missing for whatever reason, use a
2287 * selectivity of 0.5
2288 */
2289 if (!oprjoin)
2290 return (Selectivity) 0.5;
2291
2293 inputcollid,
2296 PointerGetDatum(args),
2297 Int16GetDatum(jointype),
2298 PointerGetDatum(sjinfo)));
2299
2301 elog(ERROR, "invalid join selectivity: %f", result);
2302
2303 return (Selectivity) result;
2304}
double float8
Definition c.h:656
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:1731
static Datum Int16GetDatum(int16 X)
Definition postgres.h:182
static float8 DatumGetFloat8(Datum X)
Definition postgres.h:495

References DatumGetFloat8(), elog, ERROR, fb(), 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 1863 of file plancat.c.

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

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

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

2241{
2243 float8 result;
2244
2245 /*
2246 * if the oprrest procedure is missing for whatever reason, use a
2247 * selectivity of 0.5
2248 */
2249 if (!oprrest)
2250 return (Selectivity) 0.5;
2251
2253 inputcollid,
2256 PointerGetDatum(args),
2257 Int32GetDatum(varRelid)));
2258
2260 elog(ERROR, "invalid restriction selectivity: %f", result);
2261
2262 return (Selectivity) result;
2263}
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:1707
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222

References DatumGetFloat8(), elog, ERROR, fb(), 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 2903 of file plancat.c.

2904{
2906
2907 if (rel->partition_qual) /* already done */
2908 return;
2909
2910 /*
2911 * Run the partition quals through const-simplification similar to check
2912 * constraints. We skip canonicalize_qual, though, because partition
2913 * quals should be in canonical form already; also, since the qual is in
2914 * implicit-AND format, we'd have to explicitly convert it to explicit-AND
2915 * format and back again.
2916 */
2918 if (partconstr)
2919 {
2921 if (rel->relid != 1)
2922 ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
2924 }
2925}
List * RelationGetPartitionQual(Relation rel)
Definition partcache.c:277
Expr * expression_planner(Expr *expr)
Definition planner.c:6819

References ChangeVarNodes(), expression_planner(), fb(), 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 2835 of file plancat.c.

2837{
2839 int partnatts;
2840 int cnt;
2841 List **partexprs;
2842 ListCell *lc;
2843 Index varno = rel->relid;
2844
2845 Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
2846
2847 /* A partitioned table should have a partition key. */
2848 Assert(partkey != NULL);
2849
2850 partnatts = partkey->partnatts;
2851 partexprs = palloc_array(List *, partnatts);
2852 lc = list_head(partkey->partexprs);
2853
2854 for (cnt = 0; cnt < partnatts; cnt++)
2855 {
2856 Expr *partexpr;
2857 AttrNumber attno = partkey->partattrs[cnt];
2858
2859 if (attno != InvalidAttrNumber)
2860 {
2861 /* Single column partition key is stored as a Var node. */
2862 Assert(attno > 0);
2863
2864 partexpr = (Expr *) makeVar(varno, attno,
2865 partkey->parttypid[cnt],
2866 partkey->parttypmod[cnt],
2867 partkey->parttypcoll[cnt], 0);
2868 }
2869 else
2870 {
2871 if (lc == NULL)
2872 elog(ERROR, "wrong number of partition key expressions");
2873
2874 /* Re-stamp the expression with given varno. */
2876 ChangeVarNodes((Node *) partexpr, 1, varno, 0);
2877 lc = lnext(partkey->partexprs, lc);
2878 }
2879
2880 /* Base relations have a single expression per key. */
2881 partexprs[cnt] = list_make1(partexpr);
2882 }
2883
2884 rel->partexprs = partexprs;
2885
2886 /*
2887 * A base relation does not have nullable partition key expressions, since
2888 * no outer join is involved. We still allocate an array of empty
2889 * expression lists to keep partition key expression handling code simple.
2890 * See build_joinrel_partition_info() and match_expr_to_partition_keys().
2891 */
2892 rel->nullable_partexprs = palloc0_array(List *, partnatts);
2893}
#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

References Assert, ChangeVarNodes(), copyObject, elog, ERROR, fb(), InvalidAttrNumber, IS_SIMPLE_REL, lfirst, list_head(), list_make1, lnext(), makeVar(), palloc0_array, palloc_array, 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 2699 of file plancat.c.

2701{
2702 PartitionDesc partdesc;
2703
2704 /*
2705 * Create the PartitionDirectory infrastructure if we didn't already.
2706 */
2707 if (root->glob->partition_directory == NULL)
2708 {
2709 root->glob->partition_directory =
2711 }
2712
2713 partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
2714 relation);
2715 rel->part_scheme = find_partition_scheme(root, relation);
2716 Assert(partdesc != NULL && rel->part_scheme != NULL);
2717 rel->boundinfo = partdesc->boundinfo;
2718 rel->nparts = partdesc->nparts;
2719 set_baserel_partition_key_exprs(relation, rel);
2720 set_baserel_partition_constraint(relation, rel);
2721}
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:2729
static void set_baserel_partition_key_exprs(Relation relation, RelOptInfo *rel)
Definition plancat.c:2835
PartitionBoundInfo boundinfo
Definition partdesc.h:38

References Assert, PartitionDescData::boundinfo, CreatePartitionDirectory(), CurrentMemoryContext, fb(), 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().