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