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