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