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