PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
plancat.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * plancat.c
4  * routines for accessing the system catalogs
5  *
6  *
7  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  * src/backend/optimizer/util/plancat.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17 
18 #include <math.h>
19 
20 #include "access/genam.h"
21 #include "access/heapam.h"
22 #include "access/htup_details.h"
23 #include "access/nbtree.h"
24 #include "access/sysattr.h"
25 #include "access/transam.h"
26 #include "access/xlog.h"
27 #include "catalog/catalog.h"
28 #include "catalog/dependency.h"
29 #include "catalog/heap.h"
30 #include "catalog/partition.h"
31 #include "catalog/pg_am.h"
33 #include "foreign/fdwapi.h"
34 #include "miscadmin.h"
35 #include "nodes/makefuncs.h"
36 #include "optimizer/clauses.h"
37 #include "optimizer/cost.h"
38 #include "optimizer/plancat.h"
39 #include "optimizer/predtest.h"
40 #include "optimizer/prep.h"
41 #include "parser/parse_relation.h"
42 #include "parser/parsetree.h"
43 #include "rewrite/rewriteManip.h"
44 #include "statistics/statistics.h"
45 #include "storage/bufmgr.h"
46 #include "utils/builtins.h"
47 #include "utils/lsyscache.h"
48 #include "utils/syscache.h"
49 #include "utils/rel.h"
50 #include "utils/snapmgr.h"
51 
52 
53 /* GUC parameter */
55 
56 /* Hook for plugins to get control in get_relation_info() */
58 
59 
60 static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
61  Relation relation, bool inhparent);
62 static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
63  List *idxExprs);
64 static int32 get_rel_data_width(Relation rel, int32 *attr_widths);
66  Oid relationObjectId, RelOptInfo *rel,
67  bool include_notnull);
69  Relation heapRelation);
70 static List *get_relation_statistics(RelOptInfo *rel, Relation relation);
71 
72 /*
73  * get_relation_info -
74  * Retrieves catalog information for a given relation.
75  *
76  * Given the Oid of the relation, return the following info into fields
77  * of the RelOptInfo struct:
78  *
79  * min_attr lowest valid AttrNumber
80  * max_attr highest valid AttrNumber
81  * indexlist list of IndexOptInfos for relation's indexes
82  * statlist list of StatisticExtInfo for relation's statistic objects
83  * serverid if it's a foreign table, the server OID
84  * fdwroutine if it's a foreign table, the FDW function pointers
85  * pages number of pages
86  * tuples number of tuples
87  * rel_parallel_workers user-defined number of parallel workers
88  *
89  * Also, add information about the relation's foreign keys to root->fkey_list.
90  *
91  * Also, initialize the attr_needed[] and attr_widths[] arrays. In most
92  * cases these are left as zeroes, but sometimes we need to compute attr
93  * widths here, and we may as well cache the results for costsize.c.
94  *
95  * If inhparent is true, all we need to do is set up the attr arrays:
96  * the RelOptInfo actually represents the appendrel formed by an inheritance
97  * tree, and so the parent rel's physical size and index information isn't
98  * important for it.
99  */
100 void
101 get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
102  RelOptInfo *rel)
103 {
104  Index varno = rel->relid;
105  Relation relation;
106  bool hasindex;
107  List *indexinfos = NIL;
108 
109  /*
110  * We need not lock the relation since it was already locked, either by
111  * the rewriter or when expand_inherited_rtentry() added it to the query's
112  * rangetable.
113  */
114  relation = heap_open(relationObjectId, NoLock);
115 
116  /* Temporary and unlogged relations are inaccessible during recovery. */
117  if (!RelationNeedsWAL(relation) && RecoveryInProgress())
118  ereport(ERROR,
119  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
120  errmsg("cannot access temporary or unlogged relations during recovery")));
121 
123  rel->max_attr = RelationGetNumberOfAttributes(relation);
124  rel->reltablespace = RelationGetForm(relation)->reltablespace;
125 
126  Assert(rel->max_attr >= rel->min_attr);
127  rel->attr_needed = (Relids *)
128  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
129  rel->attr_widths = (int32 *)
130  palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
131 
132  /*
133  * Estimate relation size --- unless it's an inheritance parent, in which
134  * case the size will be computed later in set_append_rel_pathlist, and we
135  * must leave it zero for now to avoid bollixing the total_table_pages
136  * calculation.
137  */
138  if (!inhparent)
139  estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
140  &rel->pages, &rel->tuples, &rel->allvisfrac);
141 
142  /* Retrieve the parallel_workers reloption, or -1 if not set. */
144 
145  /*
146  * Make list of indexes. Ignore indexes on system catalogs if told to.
147  * Don't bother with indexes for an inheritance parent, either.
148  */
149  if (inhparent ||
150  (IgnoreSystemIndexes && IsSystemRelation(relation)))
151  hasindex = false;
152  else
153  hasindex = relation->rd_rel->relhasindex;
154 
155  if (hasindex)
156  {
157  List *indexoidlist;
158  ListCell *l;
159  LOCKMODE lmode;
160 
161  indexoidlist = RelationGetIndexList(relation);
162 
163  /*
164  * For each index, we get the same type of lock that the executor will
165  * need, and do not release it. This saves a couple of trips to the
166  * shared lock manager while not creating any real loss of
167  * concurrency, because no schema changes could be happening on the
168  * index while we hold lock on the parent rel, and neither lock type
169  * blocks any other kind of index operation.
170  */
171  if (rel->relid == root->parse->resultRelation)
172  lmode = RowExclusiveLock;
173  else
174  lmode = AccessShareLock;
175 
176  foreach(l, indexoidlist)
177  {
178  Oid indexoid = lfirst_oid(l);
179  Relation indexRelation;
181  IndexAmRoutine *amroutine;
182  IndexOptInfo *info;
183  int ncolumns;
184  int i;
185 
186  /*
187  * Extract info from the relation descriptor for the index.
188  */
189  indexRelation = index_open(indexoid, lmode);
190  index = indexRelation->rd_index;
191 
192  /*
193  * Ignore invalid indexes, since they can't safely be used for
194  * queries. Note that this is OK because the data structure we
195  * are constructing is only used by the planner --- the executor
196  * still needs to insert into "invalid" indexes, if they're marked
197  * IndexIsReady.
198  */
199  if (!IndexIsValid(index))
200  {
201  index_close(indexRelation, NoLock);
202  continue;
203  }
204 
205  /*
206  * If the index is valid, but cannot yet be used, ignore it; but
207  * mark the plan we are generating as transient. See
208  * src/backend/access/heap/README.HOT for discussion.
209  */
210  if (index->indcheckxmin &&
213  {
214  root->glob->transientPlan = true;
215  index_close(indexRelation, NoLock);
216  continue;
217  }
218 
219  info = makeNode(IndexOptInfo);
220 
221  info->indexoid = index->indexrelid;
222  info->reltablespace =
223  RelationGetForm(indexRelation)->reltablespace;
224  info->rel = rel;
225  info->ncolumns = ncolumns = index->indnatts;
226  info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
227  info->indexcollations = (Oid *) palloc(sizeof(Oid) * ncolumns);
228  info->opfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
229  info->opcintype = (Oid *) palloc(sizeof(Oid) * ncolumns);
230  info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
231 
232  for (i = 0; i < ncolumns; i++)
233  {
234  info->indexkeys[i] = index->indkey.values[i];
235  info->indexcollations[i] = indexRelation->rd_indcollation[i];
236  info->opfamily[i] = indexRelation->rd_opfamily[i];
237  info->opcintype[i] = indexRelation->rd_opcintype[i];
238  info->canreturn[i] = index_can_return(indexRelation, i + 1);
239  }
240 
241  info->relam = indexRelation->rd_rel->relam;
242 
243  /* We copy just the fields we need, not all of rd_amroutine */
244  amroutine = indexRelation->rd_amroutine;
245  info->amcanorderbyop = amroutine->amcanorderbyop;
246  info->amoptionalkey = amroutine->amoptionalkey;
247  info->amsearcharray = amroutine->amsearcharray;
248  info->amsearchnulls = amroutine->amsearchnulls;
249  info->amcanparallel = amroutine->amcanparallel;
250  info->amhasgettuple = (amroutine->amgettuple != NULL);
251  info->amhasgetbitmap = (amroutine->amgetbitmap != NULL);
252  info->amcostestimate = amroutine->amcostestimate;
253  Assert(info->amcostestimate != NULL);
254 
255  /*
256  * Fetch the ordering information for the index, if any.
257  */
258  if (info->relam == BTREE_AM_OID)
259  {
260  /*
261  * If it's a btree index, we can use its opfamily OIDs
262  * directly as the sort ordering opfamily OIDs.
263  */
264  Assert(amroutine->amcanorder);
265 
266  info->sortopfamily = info->opfamily;
267  info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
268  info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);
269 
270  for (i = 0; i < ncolumns; i++)
271  {
272  int16 opt = indexRelation->rd_indoption[i];
273 
274  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
275  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
276  }
277  }
278  else if (amroutine->amcanorder)
279  {
280  /*
281  * Otherwise, identify the corresponding btree opfamilies by
282  * trying to map this index's "<" operators into btree. Since
283  * "<" uniquely defines the behavior of a sort order, this is
284  * a sufficient test.
285  *
286  * XXX This method is rather slow and also requires the
287  * undesirable assumption that the other index AM numbers its
288  * strategies the same as btree. It'd be better to have a way
289  * to explicitly declare the corresponding btree opfamily for
290  * each opfamily of the other index type. But given the lack
291  * of current or foreseeable amcanorder index types, it's not
292  * worth expending more effort on now.
293  */
294  info->sortopfamily = (Oid *) palloc(sizeof(Oid) * ncolumns);
295  info->reverse_sort = (bool *) palloc(sizeof(bool) * ncolumns);
296  info->nulls_first = (bool *) palloc(sizeof(bool) * ncolumns);
297 
298  for (i = 0; i < ncolumns; i++)
299  {
300  int16 opt = indexRelation->rd_indoption[i];
301  Oid ltopr;
302  Oid btopfamily;
303  Oid btopcintype;
304  int16 btstrategy;
305 
306  info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
307  info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
308 
309  ltopr = get_opfamily_member(info->opfamily[i],
310  info->opcintype[i],
311  info->opcintype[i],
313  if (OidIsValid(ltopr) &&
315  &btopfamily,
316  &btopcintype,
317  &btstrategy) &&
318  btopcintype == info->opcintype[i] &&
319  btstrategy == BTLessStrategyNumber)
320  {
321  /* Successful mapping */
322  info->sortopfamily[i] = btopfamily;
323  }
324  else
325  {
326  /* Fail ... quietly treat index as unordered */
327  info->sortopfamily = NULL;
328  info->reverse_sort = NULL;
329  info->nulls_first = NULL;
330  break;
331  }
332  }
333  }
334  else
335  {
336  info->sortopfamily = NULL;
337  info->reverse_sort = NULL;
338  info->nulls_first = NULL;
339  }
340 
341  /*
342  * Fetch the index expressions and predicate, if any. We must
343  * modify the copies we obtain from the relcache to have the
344  * correct varno for the parent relation, so that they match up
345  * correctly against qual clauses.
346  */
347  info->indexprs = RelationGetIndexExpressions(indexRelation);
348  info->indpred = RelationGetIndexPredicate(indexRelation);
349  if (info->indexprs && varno != 1)
350  ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
351  if (info->indpred && varno != 1)
352  ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
353 
354  /* Build targetlist using the completed indexprs data */
355  info->indextlist = build_index_tlist(root, info, relation);
356 
357  info->indrestrictinfo = NIL; /* set later, in indxpath.c */
358  info->predOK = false; /* set later, in indxpath.c */
359  info->unique = index->indisunique;
360  info->immediate = index->indimmediate;
361  info->hypothetical = false;
362 
363  /*
364  * Estimate the index size. If it's not a partial index, we lock
365  * the number-of-tuples estimate to equal the parent table; if it
366  * is partial then we have to use the same methods as we would for
367  * a table, except we can be sure that the index is not larger
368  * than the table.
369  */
370  if (info->indpred == NIL)
371  {
372  info->pages = RelationGetNumberOfBlocks(indexRelation);
373  info->tuples = rel->tuples;
374  }
375  else
376  {
377  double allvisfrac; /* dummy */
378 
379  estimate_rel_size(indexRelation, NULL,
380  &info->pages, &info->tuples, &allvisfrac);
381  if (info->tuples > rel->tuples)
382  info->tuples = rel->tuples;
383  }
384 
385  if (info->relam == BTREE_AM_OID)
386  {
387  /* For btrees, get tree height while we have the index open */
388  info->tree_height = _bt_getrootheight(indexRelation);
389  }
390  else
391  {
392  /* For other index types, just set it to "unknown" for now */
393  info->tree_height = -1;
394  }
395 
396  index_close(indexRelation, NoLock);
397 
398  indexinfos = lcons(info, indexinfos);
399  }
400 
401  list_free(indexoidlist);
402  }
403 
404  rel->indexlist = indexinfos;
405 
406  rel->statlist = get_relation_statistics(rel, relation);
407 
408  /* Grab foreign-table info using the relcache, while we have it */
409  if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
410  {
412  rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
413  }
414  else
415  {
416  rel->serverid = InvalidOid;
417  rel->fdwroutine = NULL;
418  }
419 
420  /* Collect info about relation's foreign keys, if relevant */
421  get_relation_foreign_keys(root, rel, relation, inhparent);
422 
423  heap_close(relation, NoLock);
424 
425  /*
426  * Allow a plugin to editorialize on the info we obtained from the
427  * catalogs. Actions might include altering the assumed relation size,
428  * removing an index, or adding a hypothetical index to the indexlist.
429  */
431  (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
432 }
433 
434 /*
435  * get_relation_foreign_keys -
436  * Retrieves foreign key information for a given relation.
437  *
438  * ForeignKeyOptInfos for relevant foreign keys are created and added to
439  * root->fkey_list. We do this now while we have the relcache entry open.
440  * We could sometimes avoid making useless ForeignKeyOptInfos if we waited
441  * until all RelOptInfos have been built, but the cost of re-opening the
442  * relcache entries would probably exceed any savings.
443  */
444 static void
446  Relation relation, bool inhparent)
447 {
448  List *rtable = root->parse->rtable;
449  List *cachedfkeys;
450  ListCell *lc;
451 
452  /*
453  * If it's not a baserel, we don't care about its FKs. Also, if the query
454  * references only a single relation, we can skip the lookup since no FKs
455  * could satisfy the requirements below.
456  */
457  if (rel->reloptkind != RELOPT_BASEREL ||
458  list_length(rtable) < 2)
459  return;
460 
461  /*
462  * If it's the parent of an inheritance tree, ignore its FKs. We could
463  * make useful FK-based deductions if we found that all members of the
464  * inheritance tree have equivalent FK constraints, but detecting that
465  * would require code that hasn't been written.
466  */
467  if (inhparent)
468  return;
469 
470  /*
471  * Extract data about relation's FKs from the relcache. Note that this
472  * list belongs to the relcache and might disappear in a cache flush, so
473  * we must not do any further catalog access within this function.
474  */
475  cachedfkeys = RelationGetFKeyList(relation);
476 
477  /*
478  * Figure out which FKs are of interest for this query, and create
479  * ForeignKeyOptInfos for them. We want only FKs that reference some
480  * other RTE of the current query. In queries containing self-joins,
481  * there might be more than one other RTE for a referenced table, and we
482  * should make a ForeignKeyOptInfo for each occurrence.
483  *
484  * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
485  * too hard to identify those here, so we might end up making some useless
486  * ForeignKeyOptInfos. If so, match_foreign_keys_to_quals() will remove
487  * them again.
488  */
489  foreach(lc, cachedfkeys)
490  {
491  ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
492  Index rti;
493  ListCell *lc2;
494 
495  /* conrelid should always be that of the table we're considering */
496  Assert(cachedfk->conrelid == RelationGetRelid(relation));
497 
498  /* Scan to find other RTEs matching confrelid */
499  rti = 0;
500  foreach(lc2, rtable)
501  {
502  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
503  ForeignKeyOptInfo *info;
504 
505  rti++;
506  /* Ignore if not the correct table */
507  if (rte->rtekind != RTE_RELATION ||
508  rte->relid != cachedfk->confrelid)
509  continue;
510  /* Ignore if it's an inheritance parent; doesn't really match */
511  if (rte->inh)
512  continue;
513  /* Ignore self-referential FKs; we only care about joins */
514  if (rti == rel->relid)
515  continue;
516 
517  /* OK, let's make an entry */
518  info = makeNode(ForeignKeyOptInfo);
519  info->con_relid = rel->relid;
520  info->ref_relid = rti;
521  info->nkeys = cachedfk->nkeys;
522  memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
523  memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
524  memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
525  /* zero out fields to be filled by match_foreign_keys_to_quals */
526  info->nmatched_ec = 0;
527  info->nmatched_rcols = 0;
528  info->nmatched_ri = 0;
529  memset(info->eclass, 0, sizeof(info->eclass));
530  memset(info->rinfos, 0, sizeof(info->rinfos));
531 
532  root->fkey_list = lappend(root->fkey_list, info);
533  }
534  }
535 }
536 
537 /*
538  * infer_arbiter_indexes -
539  * Determine the unique indexes used to arbitrate speculative insertion.
540  *
541  * Uses user-supplied inference clause expressions and predicate to match a
542  * unique index from those defined and ready on the heap relation (target).
543  * An exact match is required on columns/expressions (although they can appear
544  * in any order). However, the predicate given by the user need only restrict
545  * insertion to a subset of some part of the table covered by some particular
546  * unique index (in particular, a partial unique index) in order to be
547  * inferred.
548  *
549  * The implementation does not consider which B-Tree operator class any
550  * particular available unique index attribute uses, unless one was specified
551  * in the inference specification. The same is true of collations. In
552  * particular, there is no system dependency on the default operator class for
553  * the purposes of inference. If no opclass (or collation) is specified, then
554  * all matching indexes (that may or may not match the default in terms of
555  * each attribute opclass/collation) are used for inference.
556  */
557 List *
559 {
560  OnConflictExpr *onconflict = root->parse->onConflict;
561 
562  /* Iteration state */
563  Relation relation;
564  Oid relationObjectId;
565  Oid indexOidFromConstraint = InvalidOid;
566  List *indexList;
567  ListCell *l;
568 
569  /* Normalized inference attributes and inference expressions: */
570  Bitmapset *inferAttrs = NULL;
571  List *inferElems = NIL;
572 
573  /* Results */
574  List *results = NIL;
575 
576  /*
577  * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
578  * specification or named constraint. ON CONFLICT DO UPDATE statements
579  * must always provide one or the other (but parser ought to have caught
580  * that already).
581  */
582  if (onconflict->arbiterElems == NIL &&
583  onconflict->constraint == InvalidOid)
584  return NIL;
585 
586  /*
587  * We need not lock the relation since it was already locked, either by
588  * the rewriter or when expand_inherited_rtentry() added it to the query's
589  * rangetable.
590  */
591  relationObjectId = rt_fetch(root->parse->resultRelation,
592  root->parse->rtable)->relid;
593 
594  relation = heap_open(relationObjectId, NoLock);
595 
596  /*
597  * Build normalized/BMS representation of plain indexed attributes, as
598  * well as a separate list of expression items. This simplifies matching
599  * the cataloged definition of indexes.
600  */
601  foreach(l, onconflict->arbiterElems)
602  {
603  InferenceElem *elem = (InferenceElem *) lfirst(l);
604  Var *var;
605  int attno;
606 
607  if (!IsA(elem->expr, Var))
608  {
609  /* If not a plain Var, just shove it in inferElems for now */
610  inferElems = lappend(inferElems, elem->expr);
611  continue;
612  }
613 
614  var = (Var *) elem->expr;
615  attno = var->varattno;
616 
617  if (attno == 0)
618  ereport(ERROR,
619  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
620  errmsg("whole row unique index inference specifications are not supported")));
621 
622  inferAttrs = bms_add_member(inferAttrs,
624  }
625 
626  /*
627  * Lookup named constraint's index. This is not immediately returned
628  * because some additional sanity checks are required.
629  */
630  if (onconflict->constraint != InvalidOid)
631  {
632  indexOidFromConstraint = get_constraint_index(onconflict->constraint);
633 
634  if (indexOidFromConstraint == InvalidOid)
635  ereport(ERROR,
636  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
637  errmsg("constraint in ON CONFLICT clause has no associated index")));
638  }
639 
640  /*
641  * Using that representation, iterate through the list of indexes on the
642  * target relation to try and find a match
643  */
644  indexList = RelationGetIndexList(relation);
645 
646  foreach(l, indexList)
647  {
648  Oid indexoid = lfirst_oid(l);
649  Relation idxRel;
650  Form_pg_index idxForm;
651  Bitmapset *indexedAttrs;
652  List *idxExprs;
653  List *predExprs;
654  AttrNumber natt;
655  ListCell *el;
656 
657  /*
658  * Extract info from the relation descriptor for the index. We know
659  * that this is a target, so get lock type it is known will ultimately
660  * be required by the executor.
661  *
662  * Let executor complain about !indimmediate case directly, because
663  * enforcement needs to occur there anyway when an inference clause is
664  * omitted.
665  */
666  idxRel = index_open(indexoid, RowExclusiveLock);
667  idxForm = idxRel->rd_index;
668 
669  if (!IndexIsValid(idxForm))
670  goto next;
671 
672  /*
673  * Note that we do not perform a check against indcheckxmin (like e.g.
674  * get_relation_info()) here to eliminate candidates, because
675  * uniqueness checking only cares about the most recently committed
676  * tuple versions.
677  */
678 
679  /*
680  * Look for match on "ON constraint_name" variant, which may not be
681  * unique constraint. This can only be a constraint name.
682  */
683  if (indexOidFromConstraint == idxForm->indexrelid)
684  {
685  if (!idxForm->indisunique && onconflict->action == ONCONFLICT_UPDATE)
686  ereport(ERROR,
687  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
688  errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
689 
690  results = lappend_oid(results, idxForm->indexrelid);
691  list_free(indexList);
692  index_close(idxRel, NoLock);
693  heap_close(relation, NoLock);
694  return results;
695  }
696  else if (indexOidFromConstraint != InvalidOid)
697  {
698  /* No point in further work for index in named constraint case */
699  goto next;
700  }
701 
702  /*
703  * Only considering conventional inference at this point (not named
704  * constraints), so index under consideration can be immediately
705  * skipped if it's not unique
706  */
707  if (!idxForm->indisunique)
708  goto next;
709 
710  /* Build BMS representation of plain (non expression) index attrs */
711  indexedAttrs = NULL;
712  for (natt = 0; natt < idxForm->indnatts; natt++)
713  {
714  int attno = idxRel->rd_index->indkey.values[natt];
715 
716  if (attno != 0)
717  indexedAttrs = bms_add_member(indexedAttrs,
719  }
720 
721  /* Non-expression attributes (if any) must match */
722  if (!bms_equal(indexedAttrs, inferAttrs))
723  goto next;
724 
725  /* Expression attributes (if any) must match */
726  idxExprs = RelationGetIndexExpressions(idxRel);
727  foreach(el, onconflict->arbiterElems)
728  {
729  InferenceElem *elem = (InferenceElem *) lfirst(el);
730 
731  /*
732  * Ensure that collation/opclass aspects of inference expression
733  * element match. Even though this loop is primarily concerned
734  * with matching expressions, it is a convenient point to check
735  * this for both expressions and ordinary (non-expression)
736  * attributes appearing as inference elements.
737  */
738  if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
739  goto next;
740 
741  /*
742  * Plain Vars don't factor into count of expression elements, and
743  * the question of whether or not they satisfy the index
744  * definition has already been considered (they must).
745  */
746  if (IsA(elem->expr, Var))
747  continue;
748 
749  /*
750  * Might as well avoid redundant check in the rare cases where
751  * infer_collation_opclass_match() is required to do real work.
752  * Otherwise, check that element expression appears in cataloged
753  * index definition.
754  */
755  if (elem->infercollid != InvalidOid ||
756  elem->inferopclass != InvalidOid ||
757  list_member(idxExprs, elem->expr))
758  continue;
759 
760  goto next;
761  }
762 
763  /*
764  * Now that all inference elements were matched, ensure that the
765  * expression elements from inference clause are not missing any
766  * cataloged expressions. This does the right thing when unique
767  * indexes redundantly repeat the same attribute, or if attributes
768  * redundantly appear multiple times within an inference clause.
769  */
770  if (list_difference(idxExprs, inferElems) != NIL)
771  goto next;
772 
773  /*
774  * If it's a partial index, its predicate must be implied by the ON
775  * CONFLICT's WHERE clause.
776  */
777  predExprs = RelationGetIndexPredicate(idxRel);
778 
779  if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, false))
780  goto next;
781 
782  results = lappend_oid(results, idxForm->indexrelid);
783 next:
784  index_close(idxRel, NoLock);
785  }
786 
787  list_free(indexList);
788  heap_close(relation, NoLock);
789 
790  if (results == NIL)
791  ereport(ERROR,
792  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
793  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
794 
795  return results;
796 }
797 
798 /*
799  * infer_collation_opclass_match - ensure infer element opclass/collation match
800  *
801  * Given unique index inference element from inference specification, if
802  * collation was specified, or if opclass was specified, verify that there is
803  * at least one matching indexed attribute (occasionally, there may be more).
804  * Skip this in the common case where inference specification does not include
805  * collation or opclass (instead matching everything, regardless of cataloged
806  * collation/opclass of indexed attribute).
807  *
808  * At least historically, Postgres has not offered collations or opclasses
809  * with alternative-to-default notions of equality, so these additional
810  * criteria should only be required infrequently.
811  *
812  * Don't give up immediately when an inference element matches some attribute
813  * cataloged as indexed but not matching additional opclass/collation
814  * criteria. This is done so that the implementation is as forgiving as
815  * possible of redundancy within cataloged index attributes (or, less
816  * usefully, within inference specification elements). If collations actually
817  * differ between apparently redundantly indexed attributes (redundant within
818  * or across indexes), then there really is no redundancy as such.
819  *
820  * Note that if an inference element specifies an opclass and a collation at
821  * once, both must match in at least one particular attribute within index
822  * catalog definition in order for that inference element to be considered
823  * inferred/satisfied.
824  */
825 static bool
827  List *idxExprs)
828 {
829  AttrNumber natt;
830  Oid inferopfamily = InvalidOid; /* OID of opclass opfamily */
831  Oid inferopcinputtype = InvalidOid; /* OID of opclass input type */
832  int nplain = 0; /* # plain attrs observed */
833 
834  /*
835  * If inference specification element lacks collation/opclass, then no
836  * need to check for exact match.
837  */
838  if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
839  return true;
840 
841  /*
842  * Lookup opfamily and input type, for matching indexes
843  */
844  if (elem->inferopclass)
845  {
846  inferopfamily = get_opclass_family(elem->inferopclass);
847  inferopcinputtype = get_opclass_input_type(elem->inferopclass);
848  }
849 
850  for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
851  {
852  Oid opfamily = idxRel->rd_opfamily[natt - 1];
853  Oid opcinputtype = idxRel->rd_opcintype[natt - 1];
854  Oid collation = idxRel->rd_indcollation[natt - 1];
855  int attno = idxRel->rd_index->indkey.values[natt - 1];
856 
857  if (attno != 0)
858  nplain++;
859 
860  if (elem->inferopclass != InvalidOid &&
861  (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
862  {
863  /* Attribute needed to match opclass, but didn't */
864  continue;
865  }
866 
867  if (elem->infercollid != InvalidOid &&
868  elem->infercollid != collation)
869  {
870  /* Attribute needed to match collation, but didn't */
871  continue;
872  }
873 
874  /* If one matching index att found, good enough -- return true */
875  if (IsA(elem->expr, Var))
876  {
877  if (((Var *) elem->expr)->varattno == attno)
878  return true;
879  }
880  else if (attno == 0)
881  {
882  Node *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
883 
884  /*
885  * Note that unlike routines like match_index_to_operand() we
886  * don't need to care about RelabelType. Neither the index
887  * definition nor the inference clause should contain them.
888  */
889  if (equal(elem->expr, nattExpr))
890  return true;
891  }
892  }
893 
894  return false;
895 }
896 
897 /*
898  * estimate_rel_size - estimate # pages and # tuples in a table or index
899  *
900  * We also estimate the fraction of the pages that are marked all-visible in
901  * the visibility map, for use in estimation of index-only scans.
902  *
903  * If attr_widths isn't NULL, it points to the zero-index entry of the
904  * relation's attr_widths[] cache; we fill this in if we have need to compute
905  * the attribute widths for estimation purposes.
906  */
907 void
908 estimate_rel_size(Relation rel, int32 *attr_widths,
909  BlockNumber *pages, double *tuples, double *allvisfrac)
910 {
911  BlockNumber curpages;
912  BlockNumber relpages;
913  double reltuples;
914  BlockNumber relallvisible;
915  double density;
916 
917  switch (rel->rd_rel->relkind)
918  {
919  case RELKIND_RELATION:
920  case RELKIND_INDEX:
921  case RELKIND_MATVIEW:
922  case RELKIND_TOASTVALUE:
923  /* it has storage, ok to call the smgr */
924  curpages = RelationGetNumberOfBlocks(rel);
925 
926  /*
927  * HACK: if the relation has never yet been vacuumed, use a
928  * minimum size estimate of 10 pages. The idea here is to avoid
929  * assuming a newly-created table is really small, even if it
930  * currently is, because that may not be true once some data gets
931  * loaded into it. Once a vacuum or analyze cycle has been done
932  * on it, it's more reasonable to believe the size is somewhat
933  * stable.
934  *
935  * (Note that this is only an issue if the plan gets cached and
936  * used again after the table has been filled. What we're trying
937  * to avoid is using a nestloop-type plan on a table that has
938  * grown substantially since the plan was made. Normally,
939  * autovacuum/autoanalyze will occur once enough inserts have
940  * happened and cause cached-plan invalidation; but that doesn't
941  * happen instantaneously, and it won't happen at all for cases
942  * such as temporary tables.)
943  *
944  * We approximate "never vacuumed" by "has relpages = 0", which
945  * means this will also fire on genuinely empty relations. Not
946  * great, but fortunately that's a seldom-seen case in the real
947  * world, and it shouldn't degrade the quality of the plan too
948  * much anyway to err in this direction.
949  *
950  * There are two exceptions wherein we don't apply this heuristic.
951  * One is if the table has inheritance children. Totally empty
952  * parent tables are quite common, so we should be willing to
953  * believe that they are empty. Also, we don't apply the 10-page
954  * minimum to indexes.
955  */
956  if (curpages < 10 &&
957  rel->rd_rel->relpages == 0 &&
958  !rel->rd_rel->relhassubclass &&
959  rel->rd_rel->relkind != RELKIND_INDEX)
960  curpages = 10;
961 
962  /* report estimated # pages */
963  *pages = curpages;
964  /* quick exit if rel is clearly empty */
965  if (curpages == 0)
966  {
967  *tuples = 0;
968  *allvisfrac = 0;
969  break;
970  }
971  /* coerce values in pg_class to more desirable types */
972  relpages = (BlockNumber) rel->rd_rel->relpages;
973  reltuples = (double) rel->rd_rel->reltuples;
974  relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
975 
976  /*
977  * If it's an index, discount the metapage while estimating the
978  * number of tuples. This is a kluge because it assumes more than
979  * it ought to about index structure. Currently it's OK for
980  * btree, hash, and GIN indexes but suspect for GiST indexes.
981  */
982  if (rel->rd_rel->relkind == RELKIND_INDEX &&
983  relpages > 0)
984  {
985  curpages--;
986  relpages--;
987  }
988 
989  /* estimate number of tuples from previous tuple density */
990  if (relpages > 0)
991  density = reltuples / (double) relpages;
992  else
993  {
994  /*
995  * When we have no data because the relation was truncated,
996  * estimate tuple width from attribute datatypes. We assume
997  * here that the pages are completely full, which is OK for
998  * tables (since they've presumably not been VACUUMed yet) but
999  * is probably an overestimate for indexes. Fortunately
1000  * get_relation_info() can clamp the overestimate to the
1001  * parent table's size.
1002  *
1003  * Note: this code intentionally disregards alignment
1004  * considerations, because (a) that would be gilding the lily
1005  * considering how crude the estimate is, and (b) it creates
1006  * platform dependencies in the default plans which are kind
1007  * of a headache for regression testing.
1008  */
1009  int32 tuple_width;
1010 
1011  tuple_width = get_rel_data_width(rel, attr_widths);
1012  tuple_width += MAXALIGN(SizeofHeapTupleHeader);
1013  tuple_width += sizeof(ItemIdData);
1014  /* note: integer division is intentional here */
1015  density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
1016  }
1017  *tuples = rint(density * (double) curpages);
1018 
1019  /*
1020  * We use relallvisible as-is, rather than scaling it up like we
1021  * do for the pages and tuples counts, on the theory that any
1022  * pages added since the last VACUUM are most likely not marked
1023  * all-visible. But costsize.c wants it converted to a fraction.
1024  */
1025  if (relallvisible == 0 || curpages <= 0)
1026  *allvisfrac = 0;
1027  else if ((double) relallvisible >= curpages)
1028  *allvisfrac = 1;
1029  else
1030  *allvisfrac = (double) relallvisible / curpages;
1031  break;
1032  case RELKIND_SEQUENCE:
1033  /* Sequences always have a known size */
1034  *pages = 1;
1035  *tuples = 1;
1036  *allvisfrac = 0;
1037  break;
1038  case RELKIND_FOREIGN_TABLE:
1039  /* Just use whatever's in pg_class */
1040  *pages = rel->rd_rel->relpages;
1041  *tuples = rel->rd_rel->reltuples;
1042  *allvisfrac = 0;
1043  break;
1044  default:
1045  /* else it has no disk storage; probably shouldn't get here? */
1046  *pages = 0;
1047  *tuples = 0;
1048  *allvisfrac = 0;
1049  break;
1050  }
1051 }
1052 
1053 
1054 /*
1055  * get_rel_data_width
1056  *
1057  * Estimate the average width of (the data part of) the relation's tuples.
1058  *
1059  * If attr_widths isn't NULL, it points to the zero-index entry of the
1060  * relation's attr_widths[] cache; use and update that cache as appropriate.
1061  *
1062  * Currently we ignore dropped columns. Ideally those should be included
1063  * in the result, but we haven't got any way to get info about them; and
1064  * since they might be mostly NULLs, treating them as zero-width is not
1065  * necessarily the wrong thing anyway.
1066  */
1067 static int32
1069 {
1070  int32 tuple_width = 0;
1071  int i;
1072 
1073  for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
1074  {
1075  Form_pg_attribute att = rel->rd_att->attrs[i - 1];
1076  int32 item_width;
1077 
1078  if (att->attisdropped)
1079  continue;
1080 
1081  /* use previously cached data, if any */
1082  if (attr_widths != NULL && attr_widths[i] > 0)
1083  {
1084  tuple_width += attr_widths[i];
1085  continue;
1086  }
1087 
1088  /* This should match set_rel_width() in costsize.c */
1089  item_width = get_attavgwidth(RelationGetRelid(rel), i);
1090  if (item_width <= 0)
1091  {
1092  item_width = get_typavgwidth(att->atttypid, att->atttypmod);
1093  Assert(item_width > 0);
1094  }
1095  if (attr_widths != NULL)
1096  attr_widths[i] = item_width;
1097  tuple_width += item_width;
1098  }
1099 
1100  return tuple_width;
1101 }
1102 
1103 /*
1104  * get_relation_data_width
1105  *
1106  * External API for get_rel_data_width: same behavior except we have to
1107  * open the relcache entry.
1108  */
1109 int32
1110 get_relation_data_width(Oid relid, int32 *attr_widths)
1111 {
1112  int32 result;
1113  Relation relation;
1114 
1115  /* As above, assume relation is already locked */
1116  relation = heap_open(relid, NoLock);
1117 
1118  result = get_rel_data_width(relation, attr_widths);
1119 
1120  heap_close(relation, NoLock);
1121 
1122  return result;
1123 }
1124 
1125 
1126 /*
1127  * get_relation_constraints
1128  *
1129  * Retrieve the validated CHECK constraint expressions of the given relation.
1130  *
1131  * Returns a List (possibly empty) of constraint expressions. Each one
1132  * has been canonicalized, and its Vars are changed to have the varno
1133  * indicated by rel->relid. This allows the expressions to be easily
1134  * compared to expressions taken from WHERE.
1135  *
1136  * If include_notnull is true, "col IS NOT NULL" expressions are generated
1137  * and added to the result for each column that's marked attnotnull.
1138  *
1139  * Note: at present this is invoked at most once per relation per planner
1140  * run, and in many cases it won't be invoked at all, so there seems no
1141  * point in caching the data in RelOptInfo.
1142  */
1143 static List *
1145  Oid relationObjectId, RelOptInfo *rel,
1146  bool include_notnull)
1147 {
1148  List *result = NIL;
1149  Index varno = rel->relid;
1150  Relation relation;
1151  TupleConstr *constr;
1152  List *pcqual;
1153 
1154  /*
1155  * We assume the relation has already been safely locked.
1156  */
1157  relation = heap_open(relationObjectId, NoLock);
1158 
1159  constr = relation->rd_att->constr;
1160  if (constr != NULL)
1161  {
1162  int num_check = constr->num_check;
1163  int i;
1164 
1165  for (i = 0; i < num_check; i++)
1166  {
1167  Node *cexpr;
1168 
1169  /*
1170  * If this constraint hasn't been fully validated yet, we must
1171  * ignore it here.
1172  */
1173  if (!constr->check[i].ccvalid)
1174  continue;
1175 
1176  cexpr = stringToNode(constr->check[i].ccbin);
1177 
1178  /*
1179  * Run each expression through const-simplification and
1180  * canonicalization. This is not just an optimization, but is
1181  * necessary, because we will be comparing it to
1182  * similarly-processed qual clauses, and may fail to detect valid
1183  * matches without this. This must match the processing done to
1184  * qual clauses in preprocess_expression()! (We can skip the
1185  * stuff involving subqueries, however, since we don't allow any
1186  * in check constraints.)
1187  */
1188  cexpr = eval_const_expressions(root, cexpr);
1189 
1190  cexpr = (Node *) canonicalize_qual((Expr *) cexpr);
1191 
1192  /* Fix Vars to have the desired varno */
1193  if (varno != 1)
1194  ChangeVarNodes(cexpr, 1, varno, 0);
1195 
1196  /*
1197  * Finally, convert to implicit-AND format (that is, a List) and
1198  * append the resulting item(s) to our output list.
1199  */
1200  result = list_concat(result,
1201  make_ands_implicit((Expr *) cexpr));
1202  }
1203 
1204  /* Add NOT NULL constraints in expression form, if requested */
1205  if (include_notnull && constr->has_not_null)
1206  {
1207  int natts = relation->rd_att->natts;
1208 
1209  for (i = 1; i <= natts; i++)
1210  {
1211  Form_pg_attribute att = relation->rd_att->attrs[i - 1];
1212 
1213  if (att->attnotnull && !att->attisdropped)
1214  {
1215  NullTest *ntest = makeNode(NullTest);
1216 
1217  ntest->arg = (Expr *) makeVar(varno,
1218  i,
1219  att->atttypid,
1220  att->atttypmod,
1221  att->attcollation,
1222  0);
1223  ntest->nulltesttype = IS_NOT_NULL;
1224 
1225  /*
1226  * argisrow=false is correct even for a composite column,
1227  * because attnotnull does not represent a SQL-spec IS NOT
1228  * NULL test in such a case, just IS DISTINCT FROM NULL.
1229  */
1230  ntest->argisrow = false;
1231  ntest->location = -1;
1232  result = lappend(result, ntest);
1233  }
1234  }
1235  }
1236  }
1237 
1238  /* Append partition predicates, if any */
1239  pcqual = RelationGetPartitionQual(relation);
1240  if (pcqual)
1241  {
1242  /*
1243  * Run each expression through const-simplification and
1244  * canonicalization similar to check constraints.
1245  */
1246  pcqual = (List *) eval_const_expressions(root, (Node *) pcqual);
1247  pcqual = (List *) canonicalize_qual((Expr *) pcqual);
1248 
1249  /* Fix Vars to have the desired varno */
1250  if (varno != 1)
1251  ChangeVarNodes((Node *) pcqual, 1, varno, 0);
1252 
1253  result = list_concat(result, pcqual);
1254  }
1255 
1256  heap_close(relation, NoLock);
1257 
1258  return result;
1259 }
1260 
1261 /*
1262  * get_relation_statistics
1263  * Retrieve extended statistics defined on the table.
1264  *
1265  * Returns a List (possibly empty) of StatisticExtInfo objects describing
1266  * the statistics. Note that this doesn't load the actual statistics data,
1267  * just the identifying metadata. Only stats actually built are considered.
1268  */
1269 static List *
1271 {
1272  List *statoidlist;
1273  List *stainfos = NIL;
1274  ListCell *l;
1275 
1276  statoidlist = RelationGetStatExtList(relation);
1277 
1278  foreach(l, statoidlist)
1279  {
1280  Oid statOid = lfirst_oid(l);
1281  Form_pg_statistic_ext staForm;
1282  HeapTuple htup;
1283  Bitmapset *keys = NULL;
1284  int i;
1285 
1286  htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
1287  if (!htup)
1288  elog(ERROR, "cache lookup failed for statistics object %u", statOid);
1289  staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
1290 
1291  /*
1292  * First, build the array of columns covered. This is ultimately
1293  * wasted if no stats within the object have actually been built, but
1294  * it doesn't seem worth troubling over that case.
1295  */
1296  for (i = 0; i < staForm->stxkeys.dim1; i++)
1297  keys = bms_add_member(keys, staForm->stxkeys.values[i]);
1298 
1299  /* add one StatisticExtInfo for each kind built */
1301  {
1303 
1304  info->statOid = statOid;
1305  info->rel = rel;
1306  info->kind = STATS_EXT_NDISTINCT;
1307  info->keys = bms_copy(keys);
1308 
1309  stainfos = lcons(info, stainfos);
1310  }
1311 
1313  {
1315 
1316  info->statOid = statOid;
1317  info->rel = rel;
1318  info->kind = STATS_EXT_DEPENDENCIES;
1319  info->keys = bms_copy(keys);
1320 
1321  stainfos = lcons(info, stainfos);
1322  }
1323 
1324  ReleaseSysCache(htup);
1325  bms_free(keys);
1326  }
1327 
1328  list_free(statoidlist);
1329 
1330  return stainfos;
1331 }
1332 
1333 /*
1334  * relation_excluded_by_constraints
1335  *
1336  * Detect whether the relation need not be scanned because it has either
1337  * self-inconsistent restrictions, or restrictions inconsistent with the
1338  * relation's validated CHECK constraints.
1339  *
1340  * Note: this examines only rel->relid, rel->reloptkind, and
1341  * rel->baserestrictinfo; therefore it can be called before filling in
1342  * other fields of the RelOptInfo.
1343  */
1344 bool
1346  RelOptInfo *rel, RangeTblEntry *rte)
1347 {
1348  List *safe_restrictions;
1349  List *constraint_pred;
1350  List *safe_constraints;
1351  ListCell *lc;
1352 
1353  /* As of now, constraint exclusion works only with simple relations. */
1354  Assert(IS_SIMPLE_REL(rel));
1355 
1356  /*
1357  * Regardless of the setting of constraint_exclusion, detect
1358  * constant-FALSE-or-NULL restriction clauses. Because const-folding will
1359  * reduce "anything AND FALSE" to just "FALSE", any such case should
1360  * result in exactly one baserestrictinfo entry. This doesn't fire very
1361  * often, but it seems cheap enough to be worth doing anyway. (Without
1362  * this, we'd miss some optimizations that 9.5 and earlier found via much
1363  * more roundabout methods.)
1364  */
1365  if (list_length(rel->baserestrictinfo) == 1)
1366  {
1368  Expr *clause = rinfo->clause;
1369 
1370  if (clause && IsA(clause, Const) &&
1371  (((Const *) clause)->constisnull ||
1372  !DatumGetBool(((Const *) clause)->constvalue)))
1373  return true;
1374  }
1375 
1376  /* Skip further tests if constraint exclusion is disabled for the rel */
1379  !(rel->reloptkind == RELOPT_OTHER_MEMBER_REL ||
1380  (root->hasInheritedTarget &&
1381  rel->reloptkind == RELOPT_BASEREL &&
1382  rel->relid == root->parse->resultRelation))))
1383  return false;
1384 
1385  /*
1386  * Check for self-contradictory restriction clauses. We dare not make
1387  * deductions with non-immutable functions, but any immutable clauses that
1388  * are self-contradictory allow us to conclude the scan is unnecessary.
1389  *
1390  * Note: strip off RestrictInfo because predicate_refuted_by() isn't
1391  * expecting to see any in its predicate argument.
1392  */
1393  safe_restrictions = NIL;
1394  foreach(lc, rel->baserestrictinfo)
1395  {
1396  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1397 
1398  if (!contain_mutable_functions((Node *) rinfo->clause))
1399  safe_restrictions = lappend(safe_restrictions, rinfo->clause);
1400  }
1401 
1402  if (predicate_refuted_by(safe_restrictions, safe_restrictions, false))
1403  return true;
1404 
1405  /* Only plain relations have constraints */
1406  if (rte->rtekind != RTE_RELATION || rte->inh)
1407  return false;
1408 
1409  /*
1410  * OK to fetch the constraint expressions. Include "col IS NOT NULL"
1411  * expressions for attnotnull columns, in case we can refute those.
1412  */
1413  constraint_pred = get_relation_constraints(root, rte->relid, rel, true);
1414 
1415  /*
1416  * We do not currently enforce that CHECK constraints contain only
1417  * immutable functions, so it's necessary to check here. We daren't draw
1418  * conclusions from plan-time evaluation of non-immutable functions. Since
1419  * they're ANDed, we can just ignore any mutable constraints in the list,
1420  * and reason about the rest.
1421  */
1422  safe_constraints = NIL;
1423  foreach(lc, constraint_pred)
1424  {
1425  Node *pred = (Node *) lfirst(lc);
1426 
1427  if (!contain_mutable_functions(pred))
1428  safe_constraints = lappend(safe_constraints, pred);
1429  }
1430 
1431  /*
1432  * The constraints are effectively ANDed together, so we can just try to
1433  * refute the entire collection at once. This may allow us to make proofs
1434  * that would fail if we took them individually.
1435  *
1436  * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
1437  * an obvious optimization. Some of the clauses might be OR clauses that
1438  * have volatile and nonvolatile subclauses, and it's OK to make
1439  * deductions with the nonvolatile parts.
1440  */
1441  if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
1442  return true;
1443 
1444  return false;
1445 }
1446 
1447 
1448 /*
1449  * build_physical_tlist
1450  *
1451  * Build a targetlist consisting of exactly the relation's user attributes,
1452  * in order. The executor can special-case such tlists to avoid a projection
1453  * step at runtime, so we use such tlists preferentially for scan nodes.
1454  *
1455  * Exception: if there are any dropped columns, we punt and return NIL.
1456  * Ideally we would like to handle the dropped-column case too. However this
1457  * creates problems for ExecTypeFromTL, which may be asked to build a tupdesc
1458  * for a tlist that includes vars of no-longer-existent types. In theory we
1459  * could dig out the required info from the pg_attribute entries of the
1460  * relation, but that data is not readily available to ExecTypeFromTL.
1461  * For now, we don't apply the physical-tlist optimization when there are
1462  * dropped cols.
1463  *
1464  * We also support building a "physical" tlist for subqueries, functions,
1465  * values lists, table expressions, and CTEs, since the same optimization can
1466  * occur in SubqueryScan, FunctionScan, ValuesScan, CteScan, TableFunc,
1467  * NamedTuplestoreScan, and WorkTableScan nodes.
1468  */
1469 List *
1471 {
1472  List *tlist = NIL;
1473  Index varno = rel->relid;
1474  RangeTblEntry *rte = planner_rt_fetch(varno, root);
1475  Relation relation;
1476  Query *subquery;
1477  Var *var;
1478  ListCell *l;
1479  int attrno,
1480  numattrs;
1481  List *colvars;
1482 
1483  switch (rte->rtekind)
1484  {
1485  case RTE_RELATION:
1486  /* Assume we already have adequate lock */
1487  relation = heap_open(rte->relid, NoLock);
1488 
1489  numattrs = RelationGetNumberOfAttributes(relation);
1490  for (attrno = 1; attrno <= numattrs; attrno++)
1491  {
1492  Form_pg_attribute att_tup = relation->rd_att->attrs[attrno - 1];
1493 
1494  if (att_tup->attisdropped)
1495  {
1496  /* found a dropped col, so punt */
1497  tlist = NIL;
1498  break;
1499  }
1500 
1501  var = makeVar(varno,
1502  attrno,
1503  att_tup->atttypid,
1504  att_tup->atttypmod,
1505  att_tup->attcollation,
1506  0);
1507 
1508  tlist = lappend(tlist,
1509  makeTargetEntry((Expr *) var,
1510  attrno,
1511  NULL,
1512  false));
1513  }
1514 
1515  heap_close(relation, NoLock);
1516  break;
1517 
1518  case RTE_SUBQUERY:
1519  subquery = rte->subquery;
1520  foreach(l, subquery->targetList)
1521  {
1522  TargetEntry *tle = (TargetEntry *) lfirst(l);
1523 
1524  /*
1525  * A resjunk column of the subquery can be reflected as
1526  * resjunk in the physical tlist; we need not punt.
1527  */
1528  var = makeVarFromTargetEntry(varno, tle);
1529 
1530  tlist = lappend(tlist,
1531  makeTargetEntry((Expr *) var,
1532  tle->resno,
1533  NULL,
1534  tle->resjunk));
1535  }
1536  break;
1537 
1538  case RTE_FUNCTION:
1539  case RTE_TABLEFUNC:
1540  case RTE_VALUES:
1541  case RTE_CTE:
1542  case RTE_NAMEDTUPLESTORE:
1543  /* Not all of these can have dropped cols, but share code anyway */
1544  expandRTE(rte, varno, 0, -1, true /* include dropped */ ,
1545  NULL, &colvars);
1546  foreach(l, colvars)
1547  {
1548  var = (Var *) lfirst(l);
1549 
1550  /*
1551  * A non-Var in expandRTE's output means a dropped column;
1552  * must punt.
1553  */
1554  if (!IsA(var, Var))
1555  {
1556  tlist = NIL;
1557  break;
1558  }
1559 
1560  tlist = lappend(tlist,
1561  makeTargetEntry((Expr *) var,
1562  var->varattno,
1563  NULL,
1564  false));
1565  }
1566  break;
1567 
1568  default:
1569  /* caller error */
1570  elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
1571  (int) rte->rtekind);
1572  break;
1573  }
1574 
1575  return tlist;
1576 }
1577 
1578 /*
1579  * build_index_tlist
1580  *
1581  * Build a targetlist representing the columns of the specified index.
1582  * Each column is represented by a Var for the corresponding base-relation
1583  * column, or an expression in base-relation Vars, as appropriate.
1584  *
1585  * There are never any dropped columns in indexes, so unlike
1586  * build_physical_tlist, we need no failure case.
1587  */
1588 static List *
1590  Relation heapRelation)
1591 {
1592  List *tlist = NIL;
1593  Index varno = index->rel->relid;
1594  ListCell *indexpr_item;
1595  int i;
1596 
1597  indexpr_item = list_head(index->indexprs);
1598  for (i = 0; i < index->ncolumns; i++)
1599  {
1600  int indexkey = index->indexkeys[i];
1601  Expr *indexvar;
1602 
1603  if (indexkey != 0)
1604  {
1605  /* simple column */
1606  Form_pg_attribute att_tup;
1607 
1608  if (indexkey < 0)
1609  att_tup = SystemAttributeDefinition(indexkey,
1610  heapRelation->rd_rel->relhasoids);
1611  else
1612  att_tup = heapRelation->rd_att->attrs[indexkey - 1];
1613 
1614  indexvar = (Expr *) makeVar(varno,
1615  indexkey,
1616  att_tup->atttypid,
1617  att_tup->atttypmod,
1618  att_tup->attcollation,
1619  0);
1620  }
1621  else
1622  {
1623  /* expression column */
1624  if (indexpr_item == NULL)
1625  elog(ERROR, "wrong number of index expressions");
1626  indexvar = (Expr *) lfirst(indexpr_item);
1627  indexpr_item = lnext(indexpr_item);
1628  }
1629 
1630  tlist = lappend(tlist,
1631  makeTargetEntry(indexvar,
1632  i + 1,
1633  NULL,
1634  false));
1635  }
1636  if (indexpr_item != NULL)
1637  elog(ERROR, "wrong number of index expressions");
1638 
1639  return tlist;
1640 }
1641 
1642 /*
1643  * restriction_selectivity
1644  *
1645  * Returns the selectivity of a specified restriction operator clause.
1646  * This code executes registered procedures stored in the
1647  * operator relation, by calling the function manager.
1648  *
1649  * See clause_selectivity() for the meaning of the additional parameters.
1650  */
1653  Oid operatorid,
1654  List *args,
1655  Oid inputcollid,
1656  int varRelid)
1657 {
1658  RegProcedure oprrest = get_oprrest(operatorid);
1659  float8 result;
1660 
1661  /*
1662  * if the oprrest procedure is missing for whatever reason, use a
1663  * selectivity of 0.5
1664  */
1665  if (!oprrest)
1666  return (Selectivity) 0.5;
1667 
1668  result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
1669  inputcollid,
1670  PointerGetDatum(root),
1671  ObjectIdGetDatum(operatorid),
1672  PointerGetDatum(args),
1673  Int32GetDatum(varRelid)));
1674 
1675  if (result < 0.0 || result > 1.0)
1676  elog(ERROR, "invalid restriction selectivity: %f", result);
1677 
1678  return (Selectivity) result;
1679 }
1680 
1681 /*
1682  * join_selectivity
1683  *
1684  * Returns the selectivity of a specified join operator clause.
1685  * This code executes registered procedures stored in the
1686  * operator relation, by calling the function manager.
1687  */
1690  Oid operatorid,
1691  List *args,
1692  Oid inputcollid,
1693  JoinType jointype,
1694  SpecialJoinInfo *sjinfo)
1695 {
1696  RegProcedure oprjoin = get_oprjoin(operatorid);
1697  float8 result;
1698 
1699  /*
1700  * if the oprjoin procedure is missing for whatever reason, use a
1701  * selectivity of 0.5
1702  */
1703  if (!oprjoin)
1704  return (Selectivity) 0.5;
1705 
1706  result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
1707  inputcollid,
1708  PointerGetDatum(root),
1709  ObjectIdGetDatum(operatorid),
1710  PointerGetDatum(args),
1711  Int16GetDatum(jointype),
1712  PointerGetDatum(sjinfo)));
1713 
1714  if (result < 0.0 || result > 1.0)
1715  elog(ERROR, "invalid join selectivity: %f", result);
1716 
1717  return (Selectivity) result;
1718 }
1719 
1720 /*
1721  * has_unique_index
1722  *
1723  * Detect whether there is a unique index on the specified attribute
1724  * of the specified relation, thus allowing us to conclude that all
1725  * the (non-null) values of the attribute are distinct.
1726  *
1727  * This function does not check the index's indimmediate property, which
1728  * means that uniqueness may transiently fail to hold intra-transaction.
1729  * That's appropriate when we are making statistical estimates, but beware
1730  * of using this for any correctness proofs.
1731  */
1732 bool
1734 {
1735  ListCell *ilist;
1736 
1737  foreach(ilist, rel->indexlist)
1738  {
1739  IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1740 
1741  /*
1742  * Note: ignore partial indexes, since they don't allow us to conclude
1743  * that all attr values are distinct, *unless* they are marked predOK
1744  * which means we know the index's predicate is satisfied by the
1745  * query. We don't take any interest in expressional indexes either.
1746  * Also, a multicolumn unique index doesn't allow us to conclude that
1747  * just the specified attr is unique.
1748  */
1749  if (index->unique &&
1750  index->ncolumns == 1 &&
1751  index->indexkeys[0] == attno &&
1752  (index->indpred == NIL || index->predOK))
1753  return true;
1754  }
1755  return false;
1756 }
1757 
1758 
1759 /*
1760  * has_row_triggers
1761  *
1762  * Detect whether the specified relation has any row-level triggers for event.
1763  */
1764 bool
1766 {
1767  RangeTblEntry *rte = planner_rt_fetch(rti, root);
1768  Relation relation;
1769  TriggerDesc *trigDesc;
1770  bool result = false;
1771 
1772  /* Assume we already have adequate lock */
1773  relation = heap_open(rte->relid, NoLock);
1774 
1775  trigDesc = relation->trigdesc;
1776  switch (event)
1777  {
1778  case CMD_INSERT:
1779  if (trigDesc &&
1780  (trigDesc->trig_insert_after_row ||
1781  trigDesc->trig_insert_before_row))
1782  result = true;
1783  break;
1784  case CMD_UPDATE:
1785  if (trigDesc &&
1786  (trigDesc->trig_update_after_row ||
1787  trigDesc->trig_update_before_row))
1788  result = true;
1789  break;
1790  case CMD_DELETE:
1791  if (trigDesc &&
1792  (trigDesc->trig_delete_after_row ||
1793  trigDesc->trig_delete_before_row))
1794  result = true;
1795  break;
1796  default:
1797  elog(ERROR, "unrecognized CmdType: %d", (int) event);
1798  break;
1799  }
1800 
1801  heap_close(relation, NoLock);
1802  return result;
1803 }
signed short int16
Definition: c.h:255
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
#define INDOPTION_NULLS_FIRST
Definition: pg_index.h:100
#define STATS_EXT_NDISTINCT
RegProcedure get_oprjoin(Oid opno)
Definition: lsyscache.c:1385
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
void * stringToNode(char *str)
Definition: read.c:38
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:155
List * statlist
Definition: relation.h:563
int16 * rd_indoption
Definition: rel.h:186
bool predOK
Definition: relation.h:664
static List * get_relation_statistics(RelOptInfo *rel, Relation relation)
Definition: plancat.c:1270
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:111
Oid * indexcollations
Definition: relation.h:643
RelOptKind reloptkind
Definition: relation.h:522
static int32 next
Definition: blutils.c:210
Relids * attr_needed
Definition: relation.h:558
bool IsSystemRelation(Relation relation)
Definition: catalog.c:63
#define IndexIsValid(indexForm)
Definition: pg_index.h:107
amgettuple_function amgettuple
Definition: amapi.h:210
int _bt_getrootheight(Relation rel)
Definition: nbtpage.c:435
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2962
int LOCKMODE
Definition: lockdefs.h:26
OnConflictExpr * onConflict
Definition: parsenodes.h:142
bool amcanorderbyop
Definition: amapi.h:173
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:422
ConstrCheck * check
Definition: tupdesc.h:40
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1652
List * indextlist
Definition: relation.h:656
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RelationGetForm(relation)
Definition: rel.h:410
char * ccbin
Definition: tupdesc.h:31
double tuples
Definition: relation.h:565
Oid reltablespace
Definition: relation.h:554
List * baserestrictinfo
Definition: relation.h:585
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: rel.h:243
int constraint_exclusion
Definition: plancat.c:54
regproc RegProcedure
Definition: c.h:395
#define BTREE_AM_OID
Definition: pg_am.h:70
int resultRelation
Definition: parsenodes.h:120
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define RELKIND_MATVIEW
Definition: pg_class.h:165
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1345
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:104
#define Int16GetDatum(X)
Definition: postgres.h:457
#define AccessShareLock
Definition: lockdefs.h:36
static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel, List *idxExprs)
Definition: plancat.c:826
Definition: nodes.h:509
Oid * sortopfamily
Definition: relation.h:646
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid reltablespace
Definition: relation.h:632
AttrNumber varattno
Definition: primnodes.h:168
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2400
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1633
bool IgnoreSystemIndexes
Definition: miscinit.c:73
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
uint32 BlockNumber
Definition: block.h:31
bool statext_is_kind_built(HeapTuple htup, char type)
bool hypothetical
Definition: relation.h:667
#define heap_close(r, l)
Definition: heapam.h:97
double Selectivity
Definition: nodes.h:639
bool immediate
Definition: relation.h:666
#define SizeOfPageHeaderData
Definition: bufpage.h:212
double tuples
Definition: relation.h:637
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:7872
Definition: primnodes.h:163
List * fkey_list
Definition: relation.h:260
int tree_height
Definition: relation.h:638
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:538
bool amoptionalkey
Definition: amapi.h:181
struct IndexAmRoutine * rd_amroutine
Definition: rel.h:181
int natts
Definition: tupdesc.h:73
#define IS_SIMPLE_REL(rel)
Definition: relation.h:505
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
double allvisfrac
Definition: relation.h:566
signed int int32
Definition: c.h:256
JoinType
Definition: nodes.h:673
List * targetList
Definition: parsenodes.h:138
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4764
List * arbiterElems
Definition: primnodes.h:1490
struct HeapTupleData * rd_indextuple
Definition: rel.h:161
TransactionId TransactionXmin
Definition: snapmgr.c:164
bool unique
Definition: relation.h:665
HeapTupleHeader t_data
Definition: htup.h:67
Definition: type.h:89
BlockNumber pages
Definition: relation.h:636
bool index_can_return(Relation indexRelation, int attno)
Definition: indexam.c:783
Form_pg_index rd_index
Definition: rel.h:159
static int32 get_rel_data_width(Relation rel, int32 *attr_widths)
Definition: plancat.c:1068
RelOptInfo * rel
Definition: relation.h:633
bool amoptionalkey
Definition: relation.h:671
amgetbitmap_function amgetbitmap
Definition: amapi.h:211
bool resjunk
Definition: primnodes.h:1375
#define linitial(l)
Definition: pg_list.h:111
#define planner_rt_fetch(rti, root)
Definition: relation.h:325
bool has_unique_index(RelOptInfo *rel, AttrNumber attno)
Definition: plancat.c:1733
List * rtable
Definition: parsenodes.h:135
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:378
Oid * rd_indcollation
Definition: rel.h:193
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:381
bool list_member(const List *list, const void *datum)
Definition: list.c:444
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: relation.h:699
Expr * arg
Definition: primnodes.h:1180
TriggerDesc * trigdesc
Definition: rel.h:120
amcostestimate_function amcostestimate
Definition: amapi.h:204
bool trig_delete_after_row
Definition: reltrigger.h:66
void * list_nth(const List *list, int n)
Definition: list.c:410
#define NoLock
Definition: lockdefs.h:34
bool amcanorderbyop
Definition: relation.h:670
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4701
PlannerGlobal * glob
Definition: relation.h:157
bool predicate_refuted_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:197
#define RowExclusiveLock
Definition: lockdefs.h:38
struct FdwRoutine * fdwroutine
Definition: relation.h:576
AttrNumber resno
Definition: primnodes.h:1369
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
#define DatumGetBool(X)
Definition: postgres.h:399
bool trig_update_before_row
Definition: reltrigger.h:60
get_relation_info_hook_type get_relation_info_hook
Definition: plancat.c:57
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
struct ItemIdData ItemIdData
Oid * rd_opfamily
Definition: rel.h:182
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
bool trig_insert_after_row
Definition: reltrigger.h:56
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:908
RelOptInfo * rel
Definition: relation.h:723
double rint(double x)
Definition: rint.c:22
int ncolumns
Definition: relation.h:641
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
bool amhasgetbitmap
Definition: relation.h:675
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
bool amcanparallel
Definition: amapi.h:193
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
Index relid
Definition: relation.h:553
bool has_not_null
Definition: tupdesc.h:43
bool trig_update_after_row
Definition: reltrigger.h:61
Bitmapset * Relids
Definition: relation.h:28
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1110
List * lappend(List *list, void *datum)
Definition: list.c:128
OnConflictAction action
Definition: primnodes.h:1487
List * build_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
Definition: plancat.c:1470
Expr * clause
Definition: relation.h:1747
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: relation.h:706
Oid serverid
Definition: relation.h:572
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
FormData_pg_index * Form_pg_index
Definition: pg_index.h:67
bool amsearchnulls
Definition: amapi.h:185
List * indrestrictinfo
Definition: relation.h:658
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1361
bool trig_insert_before_row
Definition: reltrigger.h:55
List * RelationGetPartitionQual(Relation rel)
Definition: partition.c:964
void * palloc0(Size size)
Definition: mcxt.c:878
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: relation.h:697
#define DatumGetFloat8(X)
Definition: postgres.h:734
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
int rel_parallel_workers
Definition: relation.h:569
Expr * canonicalize_qual(Expr *qual)
Definition: prepqual.c:286
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
unsigned int Index
Definition: c.h:365
TupleDesc rd_att
Definition: rel.h:115
NullTestType nulltesttype
Definition: primnodes.h:1181
List * indexlist
Definition: relation.h:562
bool amsearcharray
Definition: amapi.h:183
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2328
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:200
bool amhasgettuple
Definition: relation.h:674
#define InvalidOid
Definition: postgres_ext.h:36
List * lcons(void *datum, List *list)
Definition: list.c:259
void(* get_relation_info_hook_type)(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
Definition: plancat.h:21
void bms_free(Bitmapset *a)
Definition: bitmapset.c:201
#define makeNode(_type_)
Definition: nodes.h:557
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: rel.h:245
BlockNumber pages
Definition: relation.h:564
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel, Relation relation, bool inhparent)
Definition: plancat.c:445
#define INDOPTION_DESC
Definition: pg_index.h:99
bool hasInheritedTarget
Definition: relation.h:297
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
Oid GetForeignServerIdByRelId(Oid relid)
Definition: foreign.c:308
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:204
TupleConstr * constr
Definition: tupdesc.h:76
int location
Definition: primnodes.h:1183
Datum OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1425
List * infer_arbiter_indexes(PlannerInfo *root)
Definition: plancat.c:558
static int list_length(const List *l)
Definition: pg_list.h:89
#define STATS_EXT_DEPENDENCIES
bool amsearcharray
Definition: relation.h:672
#define MAXALIGN(LEN)
Definition: c.h:588
bool amcanorder
Definition: amapi.h:171
List * list_difference(const List *list1, const List *list2)
Definition: list.c:858
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
#define RelationNeedsWAL(relation)
Definition: rel.h:505
Oid get_opclass_family(Oid opclass)
Definition: lsyscache.c:1047
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4345
Datum OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4)
Definition: fmgr.c:1395
Oid * opcintype
Definition: relation.h:645
List * RelationGetStatExtList(Relation relation)
Definition: relcache.c:4485
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
Oid * opfamily
Definition: relation.h:644
RTEKind rtekind
Definition: parsenodes.h:936
Node * arbiterWhere
Definition: primnodes.h:1492
#define Int32GetDatum(X)
Definition: postgres.h:485
Query * subquery
Definition: parsenodes.h:959
Bitmapset * keys
Definition: relation.h:725
AttrNumber max_attr
Definition: relation.h:557
List * RelationGetFKeyList(Relation relation)
Definition: relcache.c:4182
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
bool ccvalid
Definition: tupdesc.h:32
void list_free(List *list)
Definition: list.c:1133
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: rel.h:244
int i
#define RELKIND_INDEX
Definition: pg_class.h:161
void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up)
Definition: rewriteManip.c:607
#define RelationGetParallelWorkers(relation, defaultpw)
Definition: rel.h:326
Oid get_constraint_index(Oid constraintId)
Definition: pg_depend.c:626
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:878
static List * build_index_tlist(PlannerInfo *root, IndexOptInfo *index, Relation heapRelation)
Definition: plancat.c:1589
bool argisrow
Definition: primnodes.h:1182
int * indexkeys
Definition: relation.h:642
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1689
uint16 num_check
Definition: tupdesc.h:42
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:631
bool * canreturn
Definition: relation.h:649
bool amsearchnulls
Definition: relation.h:673
Oid * rd_opcintype
Definition: rel.h:183
void(* amcostestimate)()
Definition: relation.h:678
bool * nulls_first
Definition: relation.h:648
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:2828
bool has_row_triggers(PlannerInfo *root, Index rti, CmdType event)
Definition: plancat.c:1765
bool * reverse_sort
Definition: relation.h:647
#define BTLessStrategyNumber
Definition: stratnum.h:29
List * indpred
Definition: relation.h:654
int32 * attr_widths
Definition: relation.h:559
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
Definition: pg_list.h:45
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: relation.h:698
static List * get_relation_constraints(PlannerInfo *root, Oid relationObjectId, RelOptInfo *rel, bool include_notnull)
Definition: plancat.c:1144
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:416
List * rinfos[INDEX_MAX_KEYS]
Definition: relation.h:708
CmdType
Definition: nodes.h:649
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
bool amcanparallel
Definition: relation.h:676
void get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent, RelOptInfo *rel)
Definition: plancat.c:101
FormData_pg_statistic_ext * Form_pg_statistic_ext
#define lfirst_oid(lc)
Definition: pg_list.h:108
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:131
List * indexprs
Definition: relation.h:653
bool transientPlan
Definition: relation.h:125
bool trig_delete_before_row
Definition: reltrigger.h:65
Oid get_opclass_input_type(Oid opclass)
Definition: lsyscache.c:1069
AttrNumber min_attr
Definition: relation.h:556