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