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