PostgreSQL Source Code git master
Loading...
Searching...
No Matches
plancat.h File Reference
#include "nodes/pathnodes.h"
#include "utils/relcache.h"
Include dependency graph for plancat.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef void(* get_relation_info_hook_type) (PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
 

Functions

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)
 
bool relation_excluded_by_constraints (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
Listbuild_physical_tlist (PlannerInfo *root, RelOptInfo *rel)
 
bool has_unique_index (RelOptInfo *rel, AttrNumber attno)
 
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_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

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook
 

Typedef Documentation

◆ get_relation_info_hook_type

typedef void(* get_relation_info_hook_type) (PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)

Definition at line 21 of file plancat.h.

Function Documentation

◆ add_function_cost()

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

Definition at line 2360 of file plancat.c.

2362{
2365
2368 elog(ERROR, "cache lookup failed for function %u", funcid);
2370
2371 if (OidIsValid(procform->prosupport))
2372 {
2375
2377 req.root = root;
2378 req.funcid = funcid;
2379 req.node = node;
2380
2381 /* Initialize cost fields so that support function doesn't have to */
2382 req.startup = 0;
2383 req.per_tuple = 0;
2384
2387 PointerGetDatum(&req)));
2388
2389 if (sresult == &req)
2390 {
2391 /* Success, so accumulate support function's estimate into *cost */
2392 cost->startup += req.startup;
2393 cost->per_tuple += req.per_tuple;
2395 return;
2396 }
2397 }
2398
2399 /* No support function, or it failed, so rely on procost */
2400 cost->per_tuple += procform->procost * cpu_operator_cost;
2401
2403}
#define OidIsValid(objectId)
Definition c.h:788
double cpu_operator_cost
Definition costsize.c:134
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:722
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
FormData_pg_proc * Form_pg_proc
Definition pg_proc.h:136
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(int cacheId, Datum key1)
Definition syscache.c:220

References cpu_operator_cost, DatumGetPointer(), elog, ERROR, fb(), 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_physical_tlist()

List * build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)
extern

Definition at line 2044 of file plancat.c.

2045{
2046 List *tlist = NIL;
2047 Index varno = rel->relid;
2049 Relation relation;
2050 Query *subquery;
2051 Var *var;
2052 ListCell *l;
2053 int attrno,
2054 numattrs;
2055 List *colvars;
2056
2057 switch (rte->rtekind)
2058 {
2059 case RTE_RELATION:
2060 /* Assume we already have adequate lock */
2061 relation = table_open(rte->relid, NoLock);
2062
2064 for (attrno = 1; attrno <= numattrs; attrno++)
2065 {
2067 attrno - 1);
2068
2069 if (att_tup->attisdropped || att_tup->atthasmissing)
2070 {
2071 /* found a dropped or missing col, so punt */
2072 tlist = NIL;
2073 break;
2074 }
2075
2076 var = makeVar(varno,
2077 attrno,
2078 att_tup->atttypid,
2079 att_tup->atttypmod,
2080 att_tup->attcollation,
2081 0);
2082
2083 tlist = lappend(tlist,
2084 makeTargetEntry((Expr *) var,
2085 attrno,
2086 NULL,
2087 false));
2088 }
2089
2090 table_close(relation, NoLock);
2091 break;
2092
2093 case RTE_SUBQUERY:
2094 subquery = rte->subquery;
2095 foreach(l, subquery->targetList)
2096 {
2098
2099 /*
2100 * A resjunk column of the subquery can be reflected as
2101 * resjunk in the physical tlist; we need not punt.
2102 */
2103 var = makeVarFromTargetEntry(varno, tle);
2104
2105 tlist = lappend(tlist,
2106 makeTargetEntry((Expr *) var,
2107 tle->resno,
2108 NULL,
2109 tle->resjunk));
2110 }
2111 break;
2112
2113 case RTE_FUNCTION:
2114 case RTE_TABLEFUNC:
2115 case RTE_VALUES:
2116 case RTE_CTE:
2118 case RTE_RESULT:
2119 /* Not all of these can have dropped cols, but share code anyway */
2120 expandRTE(rte, varno, 0, VAR_RETURNING_DEFAULT, -1,
2121 true /* include dropped */ , NULL, &colvars);
2122 foreach(l, colvars)
2123 {
2124 var = (Var *) lfirst(l);
2125
2126 /*
2127 * A non-Var in expandRTE's output means a dropped column;
2128 * must punt.
2129 */
2130 if (!IsA(var, Var))
2131 {
2132 tlist = NIL;
2133 break;
2134 }
2135
2136 tlist = lappend(tlist,
2137 makeTargetEntry((Expr *) var,
2138 var->varattno,
2139 NULL,
2140 false));
2141 }
2142 break;
2143
2144 default:
2145 /* caller error */
2146 elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
2147 (int) rte->rtekind);
2148 break;
2149 }
2150
2151 return tlist;
2152}
unsigned int Index
Definition c.h:628
List * lappend(List *list, void *datum)
Definition list.c:339
#define NoLock
Definition lockdefs.h:34
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition makefuncs.c:107
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
#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:686
FormData_pg_attribute * Form_pg_attribute
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
@ VAR_RETURNING_DEFAULT
Definition primnodes.h:256
#define RelationGetNumberOfAttributes(relation)
Definition rel.h:520
Definition pg_list.h:54
List * targetList
Definition parsenodes.h:198
Index relid
Definition pathnodes.h:1051
TupleDesc rd_att
Definition rel.h:112
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:160

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 
)
extern

Definition at line 1310 of file plancat.c.

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

References 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_relation_notnullatts()

Bitmapset * find_relation_notnullatts ( PlannerInfo root,
Oid  relid 
)
extern

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(), 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 
)
extern

Definition at line 2306 of file plancat.c.

2314{
2318
2319 if (!prosupport)
2320 return (Selectivity) -1; /* no support function */
2321
2323 req.root = root;
2324 req.funcid = funcid;
2325 req.args = args;
2326 req.inputcollid = inputcollid;
2327 req.is_join = is_join;
2328 req.varRelid = varRelid;
2329 req.jointype = jointype;
2330 req.sjinfo = sjinfo;
2331 req.selectivity = -1; /* to catch failure to set the value */
2332
2335 PointerGetDatum(&req)));
2336
2337 if (sresult != &req)
2338 return (Selectivity) -1; /* function did not honor request */
2339
2340 if (req.selectivity < 0.0 || req.selectivity > 1.0)
2341 elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2342
2343 return (Selectivity) req.selectivity;
2344}
regproc RegProcedure
Definition c.h:664
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 
)
extern

Definition at line 2642 of file plancat.c.

2644{
2647 Relation relation;
2648 TupleDesc tupdesc;
2649 TupleConstr *constr;
2650
2651 /* Assume we already have adequate lock */
2652 relation = table_open(rte->relid, NoLock);
2653
2654 tupdesc = RelationGetDescr(relation);
2655 constr = tupdesc->constr;
2656
2657 if (constr && constr->has_generated_stored)
2658 {
2659 for (int i = 0; i < constr->num_defval; i++)
2660 {
2661 AttrDefault *defval = &constr->defval[i];
2662 Node *expr;
2663 Bitmapset *attrs_used = NULL;
2664
2665 /* skip if not generated column */
2666 if (!TupleDescCompactAttr(tupdesc, defval->adnum - 1)->attgenerated)
2667 continue;
2668
2669 /* identify columns this generated column depends on */
2670 expr = stringToNode(defval->adbin);
2671 pull_varattnos(expr, 1, &attrs_used);
2672
2673 if (bms_overlap(target_cols, attrs_used))
2676 }
2677 }
2678
2679 table_close(relation, NoLock);
2680
2681 return dependentCols;
2682}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:814
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:581
int i
Definition isn.c:77
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 
)
extern

Definition at line 2421 of file plancat.c.

2422{
2425 double result;
2426
2429 elog(ERROR, "cache lookup failed for function %u", funcid);
2431
2432 Assert(procform->proretset); /* else caller error */
2433
2434 if (OidIsValid(procform->prosupport))
2435 {
2438
2440 req.root = root;
2441 req.funcid = funcid;
2442 req.node = node;
2443
2444 req.rows = 0; /* just for sanity */
2445
2448 PointerGetDatum(&req)));
2449
2450 if (sresult == &req)
2451 {
2452 /* Success */
2454 return req.rows;
2455 }
2456 }
2457
2458 /* No support function, or it failed, so rely on prorows */
2459 result = procform->prorows;
2460
2462
2463 return result;
2464}
#define Assert(condition)
Definition c.h:873

References Assert, DatumGetPointer(), elog, ERROR, fb(), 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 
)
extern

Definition at line 1435 of file plancat.c.

1436{
1437 int64 tuple_width = 0;
1438 int i;
1439
1440 for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1441 {
1444
1445 if (att->attisdropped)
1446 continue;
1447
1448 /* use previously cached data, if any */
1449 if (attr_widths != NULL && attr_widths[i] > 0)
1450 {
1452 continue;
1453 }
1454
1455 /* This should match set_rel_width() in costsize.c */
1457 if (item_width <= 0)
1458 {
1459 item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1460 Assert(item_width > 0);
1461 }
1462 if (attr_widths != NULL)
1465 }
1466
1468}
int64_t int64
Definition c.h:543
int32 clamp_width_est(int64 tuple_width)
Definition costsize.c:242
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition lsyscache.c:3308
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition lsyscache.c:2728
#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_data_width()

int32 get_relation_data_width ( Oid  relid,
int32 attr_widths 
)
extern

Definition at line 1477 of file plancat.c.

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

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

Referenced by plan_cluster_use_sort(), and set_rel_width().

◆ get_relation_info()

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

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}
int16_t int16
Definition c.h:541
#define unlikely(x)
Definition c.h:412
bool IsSystemRelation(Relation relation)
Definition catalog.c:74
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition clauses.c:2267
CompareType
Definition cmptype.h:32
@ COMPARE_LT
Definition cmptype.h:34
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ereport(elevel,...)
Definition elog.h:150
#define palloc_array(type, count)
Definition fe_memutils.h:76
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
List * make_ands_implicit(Expr *clause)
Definition makefuncs.c:810
void * palloc0(Size size)
Definition mcxt.c:1417
bool IgnoreSystemIndexes
Definition miscinit.c:81
#define makeNode(_type_)
Definition nodes.h:161
Bitmapset * Relids
Definition pathnodes.h:103
#define AMFLAG_HAS_TID_RANGE
Definition pathnodes.h:955
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
FormData_pg_index * Form_pg_index
Definition pg_index.h:70
#define lfirst_oid(lc)
Definition pg_list.h:174
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition plancat.c:1310
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:1743
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition plancat.c:2165
static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel, Relation relation)
Definition plancat.c:2690
Bitmapset * find_relation_notnullatts(PlannerInfo *root, Oid relid)
Definition plancat.c:777
int restrict_nonsystem_relation_kind
Definition postgres.c:106
#define InvalidOid
unsigned int Oid
#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
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
TransactionId TransactionXmin
Definition snapmgr.c:159
HeapTupleHeader t_data
Definition htup.h:68
bool amcanparallel
Definition pathnodes.h:1424
void(* amcostestimate)(struct PlannerInfo *, struct IndexPath *, double, Cost *, Cost *, Selectivity *, double *, double *) pg_node_attr(read_write_ignore)
Definition pathnodes.h:1429
bool amoptionalkey
Definition pathnodes.h:1417
bool amcanmarkpos
Definition pathnodes.h:1426
List * indrestrictinfo
Definition pathnodes.h:1399
bool amhasgettuple
Definition pathnodes.h:1421
bool amcanorderbyop
Definition pathnodes.h:1416
bool hypothetical
Definition pathnodes.h:1410
bool nullsnotdistinct
Definition pathnodes.h:1406
List * indpred
Definition pathnodes.h:1389
Cardinality tuples
Definition pathnodes.h:1347
bool amsearcharray
Definition pathnodes.h:1418
BlockNumber pages
Definition pathnodes.h:1345
bool amsearchnulls
Definition pathnodes.h:1419
bool amhasgetbitmap
Definition pathnodes.h:1423
List * indextlist
Definition pathnodes.h:1392
uint32 amflags
Definition pathnodes.h:1087
Bitmapset * notnullattnums
Definition pathnodes.h:1065
List * statlist
Definition pathnodes.h:1075
Cardinality tuples
Definition pathnodes.h:1078
BlockNumber pages
Definition pathnodes.h:1077
List * indexlist
Definition pathnodes.h:1073
Oid reltablespace
Definition pathnodes.h:1053
int rel_parallel_workers
Definition pathnodes.h:1085
AttrNumber max_attr
Definition pathnodes.h:1059
double allvisfrac
Definition pathnodes.h:1079
AttrNumber min_attr
Definition pathnodes.h:1057
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:793
bool(* scan_getnextslot_tidrange)(TableScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
Definition tableam.h:379
void(* scan_set_tidrange)(TableScanDesc scan, ItemPointer mintid, ItemPointer maxtid)
Definition tableam.h:371
Definition type.h:96
#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, 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 
)
extern

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
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
bool attisdropped
Definition tupdesc.h:77
char attnullability
Definition tupdesc.h:79
Size keysize
Definition hsearch.h:75
bool has_not_null
Definition tupdesc.h:45
#define ATTNULLABLE_UNKNOWN
Definition tupdesc.h:85
#define ATTNULLABLE_VALID
Definition tupdesc.h:86

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().

◆ has_row_triggers()

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

Definition at line 2511 of file plancat.c.

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

Definition at line 2615 of file plancat.c.

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

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 
)
extern

Definition at line 2561 of file plancat.c.

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

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 
)
extern

Definition at line 2479 of file plancat.c.

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

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

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List * infer_arbiter_indexes ( PlannerInfo root)
extern

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 UPDATE statements
845 * must always provide one or the other (but parser ought to have caught
846 * 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 if (idxForm->indisexclusion && onconflict->action == ONCONFLICT_UPDATE)
1028 ereport(ERROR,
1030 errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
1031
1032 /* Consider this one a match already */
1033 results = lappend_oid(results, idxForm->indexrelid);
1034 foundValid |= idxForm->indisvalid;
1035 continue;
1036 }
1038 {
1039 /*
1040 * In the case of "ON constraint_name DO UPDATE" we need to skip
1041 * non-unique candidates.
1042 */
1043 if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
1044 continue;
1045 }
1046 else
1047 {
1048 /*
1049 * Only considering conventional inference at this point (not
1050 * named constraints), so index under consideration can be
1051 * immediately skipped if it's not unique.
1052 */
1053 if (!idxForm->indisunique)
1054 continue;
1055 }
1056
1057 /*
1058 * So-called unique constraints with WITHOUT OVERLAPS are really
1059 * exclusion constraints, so skip those too.
1060 */
1061 if (idxForm->indisexclusion)
1062 continue;
1063
1064 /* Build BMS representation of plain (non expression) index attrs */
1066 for (natt = 0; natt < idxForm->indnkeyatts; natt++)
1067 {
1068 int attno = idxRel->rd_index->indkey.values[natt];
1069
1070 if (attno != 0)
1073 }
1074
1075 /* Non-expression attributes (if any) must match */
1077 continue;
1078
1079 /* Expression attributes (if any) must match */
1081 if (idxExprs)
1082 {
1083 if (varno != 1)
1084 ChangeVarNodes((Node *) idxExprs, 1, varno, 0);
1085
1087 }
1088
1089 /*
1090 * If arbiterElems are present, check them. (Note that if a
1091 * constraint name was given in the command line, this list is NIL.)
1092 */
1093 match = true;
1094 foreach_ptr(InferenceElem, elem, onconflict->arbiterElems)
1095 {
1096 /*
1097 * Ensure that collation/opclass aspects of inference expression
1098 * element match. Even though this loop is primarily concerned
1099 * with matching expressions, it is a convenient point to check
1100 * this for both expressions and ordinary (non-expression)
1101 * attributes appearing as inference elements.
1102 */
1104 {
1105 match = false;
1106 break;
1107 }
1108
1109 /*
1110 * Plain Vars don't factor into count of expression elements, and
1111 * the question of whether or not they satisfy the index
1112 * definition has already been considered (they must).
1113 */
1114 if (IsA(elem->expr, Var))
1115 continue;
1116
1117 /*
1118 * Might as well avoid redundant check in the rare cases where
1119 * infer_collation_opclass_match() is required to do real work.
1120 * Otherwise, check that element expression appears in cataloged
1121 * index definition.
1122 */
1123 if (elem->infercollid != InvalidOid ||
1124 elem->inferopclass != InvalidOid ||
1125 list_member(idxExprs, elem->expr))
1126 continue;
1127
1128 match = false;
1129 break;
1130 }
1131 if (!match)
1132 continue;
1133
1134 /*
1135 * In case of inference from an attribute list, ensure that the
1136 * expression elements from inference clause are not missing any
1137 * cataloged expressions. This does the right thing when unique
1138 * indexes redundantly repeat the same attribute, or if attributes
1139 * redundantly appear multiple times within an inference clause.
1140 *
1141 * In case a constraint was named, ensure the candidate has an equal
1142 * set of expressions as the named constraint's index.
1143 */
1145 continue;
1146
1148 if (predExprs)
1149 {
1150 if (varno != 1)
1151 ChangeVarNodes((Node *) predExprs, 1, varno, 0);
1152
1153 predExprs = (List *)
1157 }
1158
1159 /*
1160 * Partial indexes affect each form of ON CONFLICT differently: if a
1161 * constraint was named, then the predicates must be identical. In
1162 * conventional inference, the index's predicate must be implied by
1163 * the WHERE clause.
1164 */
1166 {
1168 continue;
1169 }
1170 else
1171 {
1173 continue;
1174 }
1175
1176 /* All good -- consider this index a match */
1177 results = lappend_oid(results, idxForm->indexrelid);
1178 foundValid |= idxForm->indisvalid;
1179 }
1180
1181 /* Close all indexes */
1183 {
1185 }
1186
1189 table_close(relation, NoLock);
1190
1191 /* We require at least one indisvalid index */
1192 if (results == NIL || !foundValid)
1193 ereport(ERROR,
1195 errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
1196
1197 return results;
1198}
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_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:1228
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition predtest.c:152
Node * arbiterWhere
Definition primnodes.h:2378
AttrNumber varattno
Definition primnodes.h:274

References OnConflictExpr::action, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, Assert, bms_add_member(), bms_equal(), ChangeVarNodes(), OnConflictExpr::constraint, ereport, errcode(), errmsg(), ERROR, eval_const_expressions(), fb(), FirstLowInvalidHeapAttributeNumber, foreach_oid, foreach_ptr, 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_UPDATE, predicate_implied_by(), RelationData::rd_rel, RelationGetIndexExpressions(), RelationGetIndexList(), RelationGetIndexPredicate(), root, rt_fetch, table_close(), table_open(), and Var::varattno.

Referenced by make_modifytable().

◆ join_selectivity()

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

Definition at line 2266 of file plancat.c.

2272{
2274 float8 result;
2275
2276 /*
2277 * if the oprjoin procedure is missing for whatever reason, use a
2278 * selectivity of 0.5
2279 */
2280 if (!oprjoin)
2281 return (Selectivity) 0.5;
2282
2284 inputcollid,
2287 PointerGetDatum(args),
2288 Int16GetDatum(jointype),
2289 PointerGetDatum(sjinfo)));
2290
2292 elog(ERROR, "invalid join selectivity: %f", result);
2293
2294 return (Selectivity) result;
2295}
double float8
Definition c.h:644
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 
)
extern

Definition at line 1854 of file plancat.c.

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

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 
)
extern

Definition at line 2227 of file plancat.c.

2232{
2234 float8 result;
2235
2236 /*
2237 * if the oprrest procedure is missing for whatever reason, use a
2238 * selectivity of 0.5
2239 */
2240 if (!oprrest)
2241 return (Selectivity) 0.5;
2242
2244 inputcollid,
2247 PointerGetDatum(args),
2248 Int32GetDatum(varRelid)));
2249
2251 elog(ERROR, "invalid restriction selectivity: %f", result);
2252
2253 return (Selectivity) result;
2254}
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().

Variable Documentation

◆ get_relation_info_hook

PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook
extern

Definition at line 61 of file plancat.c.

Referenced by get_relation_info().