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.

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)
 

Function Documentation

◆ add_function_cost()

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

Definition at line 2355 of file plancat.c.

2357{
2360
2363 elog(ERROR, "cache lookup failed for function %u", funcid);
2365
2366 if (OidIsValid(procform->prosupport))
2367 {
2370
2372 req.root = root;
2373 req.funcid = funcid;
2374 req.node = node;
2375
2376 /* Initialize cost fields so that support function doesn't have to */
2377 req.startup = 0;
2378 req.per_tuple = 0;
2379
2382 PointerGetDatum(&req)));
2383
2384 if (sresult == &req)
2385 {
2386 /* Success, so accumulate support function's estimate into *cost */
2387 cost->startup += req.startup;
2388 cost->per_tuple += req.per_tuple;
2390 return;
2391 }
2392 }
2393
2394 /* No support function, or it failed, so rely on procost */
2395 cost->per_tuple += procform->procost * cpu_operator_cost;
2396
2398}
#define OidIsValid(objectId)
Definition c.h:860
double cpu_operator_cost
Definition costsize.c:135
#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:342
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
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_physical_tlist()

List * build_physical_tlist ( PlannerInfo root,
RelOptInfo rel 
)
extern

Definition at line 2039 of file plancat.c.

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

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

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

Bitmapset * find_relation_notnullatts ( PlannerInfo root,
Oid  relid 
)
extern

Definition at line 763 of file plancat.c.

764{
766 bool found;
767
768 if (root->glob->rel_notnullatts_hash == NULL)
769 return NULL;
770
771 hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
772 &relid,
773 HASH_FIND,
774 &found);
775 if (!found)
776 return NULL;
777
778 return hentry->notnullattnums;
779}
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:63

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

Definition at line 2301 of file plancat.c.

2309{
2313
2314 if (!prosupport)
2315 return (Selectivity) -1; /* no support function */
2316
2318 req.root = root;
2319 req.funcid = funcid;
2320 req.args = args;
2321 req.inputcollid = inputcollid;
2322 req.is_join = is_join;
2323 req.varRelid = varRelid;
2324 req.jointype = jointype;
2325 req.sjinfo = sjinfo;
2326 req.selectivity = -1; /* to catch failure to set the value */
2327
2330 PointerGetDatum(&req)));
2331
2332 if (sresult != &req)
2333 return (Selectivity) -1; /* function did not honor request */
2334
2335 if (req.selectivity < 0.0 || req.selectivity > 1.0)
2336 elog(ERROR, "invalid function selectivity: %f", req.selectivity);
2337
2338 return (Selectivity) req.selectivity;
2339}
regproc RegProcedure
Definition c.h:736
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2078
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 2637 of file plancat.c.

2639{
2642 Relation relation;
2643 TupleDesc tupdesc;
2644 TupleConstr *constr;
2645
2646 /* Assume we already have adequate lock */
2647 relation = table_open(rte->relid, NoLock);
2648
2649 tupdesc = RelationGetDescr(relation);
2650 constr = tupdesc->constr;
2651
2652 if (constr && constr->has_generated_stored)
2653 {
2654 for (int i = 0; i < constr->num_defval; i++)
2655 {
2656 AttrDefault *defval = &constr->defval[i];
2657 Node *expr;
2658 Bitmapset *attrs_used = NULL;
2659
2660 /* skip if not generated column */
2661 if (!TupleDescCompactAttr(tupdesc, defval->adnum - 1)->attgenerated)
2662 continue;
2663
2664 /* identify columns this generated column depends on */
2665 expr = stringToNode(defval->adbin);
2666 pull_varattnos(expr, 1, &attrs_used);
2667
2668 if (bms_overlap(target_cols, attrs_used))
2671 }
2672 }
2673
2674 table_close(relation, NoLock);
2675
2676 return dependentCols;
2677}
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
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:79
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:159
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:193
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 2416 of file plancat.c.

2417{
2420 double result;
2421
2424 elog(ERROR, "cache lookup failed for function %u", funcid);
2426
2427 Assert(procform->proretset); /* else caller error */
2428
2429 if (OidIsValid(procform->prosupport))
2430 {
2433
2435 req.root = root;
2436 req.funcid = funcid;
2437 req.node = node;
2438
2439 req.rows = 0; /* just for sanity */
2440
2443 PointerGetDatum(&req)));
2444
2445 if (sresult == &req)
2446 {
2447 /* Success */
2449 return req.rows;
2450 }
2451 }
2452
2453 /* No support function, or it failed, so rely on prorows */
2454 result = procform->prorows;
2455
2457
2458 return result;
2459}
#define Assert(condition)
Definition c.h:945

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

Definition at line 1430 of file plancat.c.

1431{
1432 int64 tuple_width = 0;
1433 int i;
1434
1435 for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1436 {
1439
1440 if (att->attisdropped)
1441 continue;
1442
1443 /* use previously cached data, if any */
1444 if (attr_widths != NULL && attr_widths[i] > 0)
1445 {
1447 continue;
1448 }
1449
1450 /* This should match set_rel_width() in costsize.c */
1452 if (item_width <= 0)
1453 {
1454 item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1455 Assert(item_width > 0);
1456 }
1457 if (attr_widths != NULL)
1460 }
1461
1463}
int64_t int64
Definition c.h:615
int32 clamp_width_est(int64 tuple_width)
Definition costsize.c:243
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition lsyscache.c:3380
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition lsyscache.c:2800
#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 1472 of file plancat.c.

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

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

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

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

691{
692 Oid relid = RelationGetRelid(relation);
694 bool found;
695 Bitmapset *notnullattnums = NULL;
696
697 /* bail out if the relation has no not-null constraints */
698 if (relation->rd_att->constr == NULL ||
699 !relation->rd_att->constr->has_not_null)
700 return;
701
702 /* create the hash table if it hasn't been created yet */
703 if (root->glob->rel_notnullatts_hash == NULL)
704 {
705 HTAB *hashtab;
707
708 hash_ctl.keysize = sizeof(Oid);
709 hash_ctl.entrysize = sizeof(NotnullHashEntry);
711
712 hashtab = hash_create("Relation NOT NULL attnums",
713 64L, /* arbitrary initial size */
714 &hash_ctl,
716
717 root->glob->rel_notnullatts_hash = hashtab;
718 }
719
720 /*
721 * Create a hash entry for this relation OID, if we don't have one
722 * already.
723 */
724 hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
725 &relid,
727 &found);
728
729 /* bail out if a hash entry already exists for this relation OID */
730 if (found)
731 return;
732
733 /* collect the column not-null constraint information for this relation */
734 for (int i = 0; i < relation->rd_att->natts; i++)
735 {
736 CompactAttribute *attr = TupleDescCompactAttr(relation->rd_att, i);
737
739
741 {
742 notnullattnums = bms_add_member(notnullattnums, i + 1);
743
744 /*
745 * Per RemoveAttributeById(), dropped columns will have their
746 * attnotnull unset, so we needn't check for dropped columns in
747 * the above condition.
748 */
749 Assert(!attr->attisdropped);
750 }
751 }
752
753 /* ... and initialize the new hash entry */
754 hentry->notnullattnums = notnullattnums;
755}
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:78
char attnullability
Definition tupdesc.h:80
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 2506 of file plancat.c.

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

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

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

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

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

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

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

Referenced by examine_variable().

◆ infer_arbiter_indexes()

List * infer_arbiter_indexes ( PlannerInfo root)
extern

Definition at line 802 of file plancat.c.

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

◆ join_selectivity()

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

Definition at line 2261 of file plancat.c.

2267{
2269 float8 result;
2270
2271 /*
2272 * if the oprjoin procedure is missing for whatever reason, use a
2273 * selectivity of 0.5
2274 */
2275 if (!oprjoin)
2276 return (Selectivity) 0.5;
2277
2279 inputcollid,
2282 PointerGetDatum(args),
2283 Int16GetDatum(jointype),
2284 PointerGetDatum(sjinfo)));
2285
2287 elog(ERROR, "invalid join selectivity: %f", result);
2288
2289 return (Selectivity) result;
2290}
double float8
Definition c.h:716
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition fmgr.c:1455
RegProcedure get_oprjoin(Oid opno)
Definition lsyscache.c:1801
static Datum Int16GetDatum(int16 X)
Definition postgres.h:172
static float8 DatumGetFloat8(Datum X)
Definition postgres.h:485

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

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

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

2227{
2229 float8 result;
2230
2231 /*
2232 * if the oprrest procedure is missing for whatever reason, use a
2233 * selectivity of 0.5
2234 */
2235 if (!oprrest)
2236 return (Selectivity) 0.5;
2237
2239 inputcollid,
2242 PointerGetDatum(args),
2243 Int32GetDatum(varRelid)));
2244
2246 elog(ERROR, "invalid restriction selectivity: %f", result);
2247
2248 return (Selectivity) result;
2249}
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition fmgr.c:1444
RegProcedure get_oprrest(Oid opno)
Definition lsyscache.c:1777
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212

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

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