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