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