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