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