1 /*-------------------------------------------------------------------------
2  *
3  * indxpath.c
4  *	  Routines to determine which indexes are usable for scanning a
5  *	  given relation, and create Paths accordingly.
6  *
7  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *	  src/backend/optimizer/path/indxpath.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17 
18 #include <math.h>
19 
20 #include "access/stratnum.h"
21 #include "access/sysattr.h"
22 #include "catalog/pg_am.h"
23 #include "catalog/pg_operator.h"
24 #include "catalog/pg_opfamily.h"
25 #include "catalog/pg_type.h"
26 #include "nodes/makefuncs.h"
27 #include "nodes/nodeFuncs.h"
28 #include "nodes/supportnodes.h"
29 #include "optimizer/cost.h"
30 #include "optimizer/optimizer.h"
31 #include "optimizer/pathnode.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/prep.h"
34 #include "optimizer/restrictinfo.h"
35 #include "utils/lsyscache.h"
36 #include "utils/selfuncs.h"
37 
38 
39 /* source-code-compatibility hacks for pull_varnos() API change */
40 #define pull_varnos(a,b) pull_varnos_new(a,b)
41 #undef make_simple_restrictinfo
42 #define make_simple_restrictinfo(root, clause)  \
43 	make_restrictinfo_new(root, clause, true, false, false, 0, NULL, NULL, NULL)
44 
45 /* XXX see PartCollMatchesExprColl */
46 #define IndexCollMatchesExprColl(idxcollation, exprcollation) \
47 	((idxcollation) == InvalidOid || (idxcollation) == (exprcollation))
48 
49 /* Whether we are looking for plain indexscan, bitmap scan, or either */
50 typedef enum
51 {
52 	ST_INDEXSCAN,				/* must support amgettuple */
53 	ST_BITMAPSCAN,				/* must support amgetbitmap */
54 	ST_ANYSCAN					/* either is okay */
55 } ScanTypeControl;
56 
57 /* Data structure for collecting qual clauses that match an index */
58 typedef struct
59 {
60 	bool		nonempty;		/* True if lists are not all empty */
61 	/* Lists of IndexClause nodes, one list per index column */
62 	List	   *indexclauses[INDEX_MAX_KEYS];
63 } IndexClauseSet;
64 
65 /* Per-path data used within choose_bitmap_and() */
66 typedef struct
67 {
68 	Path	   *path;			/* IndexPath, BitmapAndPath, or BitmapOrPath */
69 	List	   *quals;			/* the WHERE clauses it uses */
70 	List	   *preds;			/* predicates of its partial index(es) */
71 	Bitmapset  *clauseids;		/* quals+preds represented as a bitmapset */
72 	bool		unclassifiable; /* has too many quals+preds to process? */
73 } PathClauseUsage;
74 
75 /* Callback argument for ec_member_matches_indexcol */
76 typedef struct
77 {
78 	IndexOptInfo *index;		/* index we're considering */
79 	int			indexcol;		/* index column we want to match to */
80 } ec_member_matches_arg;
81 
82 
83 static void consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel,
84 										IndexOptInfo *index,
85 										IndexClauseSet *rclauseset,
86 										IndexClauseSet *jclauseset,
87 										IndexClauseSet *eclauseset,
88 										List **bitindexpaths);
89 static void consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
90 										   IndexOptInfo *index,
91 										   IndexClauseSet *rclauseset,
92 										   IndexClauseSet *jclauseset,
93 										   IndexClauseSet *eclauseset,
94 										   List **bitindexpaths,
95 										   List *indexjoinclauses,
96 										   int considered_clauses,
97 										   List **considered_relids);
98 static void get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
99 								 IndexOptInfo *index,
100 								 IndexClauseSet *rclauseset,
101 								 IndexClauseSet *jclauseset,
102 								 IndexClauseSet *eclauseset,
103 								 List **bitindexpaths,
104 								 Relids relids,
105 								 List **considered_relids);
106 static bool eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
107 								List *indexjoinclauses);
108 static bool bms_equal_any(Relids relids, List *relids_list);
109 static void get_index_paths(PlannerInfo *root, RelOptInfo *rel,
110 							IndexOptInfo *index, IndexClauseSet *clauses,
111 							List **bitindexpaths);
112 static List *build_index_paths(PlannerInfo *root, RelOptInfo *rel,
113 							   IndexOptInfo *index, IndexClauseSet *clauses,
114 							   bool useful_predicate,
115 							   ScanTypeControl scantype,
116 							   bool *skip_nonnative_saop,
117 							   bool *skip_lower_saop);
118 static List *build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
119 								List *clauses, List *other_clauses);
120 static List *generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
121 									  List *clauses, List *other_clauses);
122 static Path *choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
123 							   List *paths);
124 static int	path_usage_comparator(const void *a, const void *b);
125 static Cost bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel,
126 								 Path *ipath);
127 static Cost bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
128 								List *paths);
129 static PathClauseUsage *classify_index_clause_usage(Path *path,
130 													List **clauselist);
131 static void find_indexpath_quals(Path *bitmapqual, List **quals, List **preds);
132 static int	find_list_position(Node *node, List **nodelist);
133 static bool check_index_only(RelOptInfo *rel, IndexOptInfo *index);
134 static double get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids);
135 static double adjust_rowcount_for_semijoins(PlannerInfo *root,
136 											Index cur_relid,
137 											Index outer_relid,
138 											double rowcount);
139 static double approximate_joinrel_size(PlannerInfo *root, Relids relids);
140 static void match_restriction_clauses_to_index(PlannerInfo *root,
141 											   IndexOptInfo *index,
142 											   IndexClauseSet *clauseset);
143 static void match_join_clauses_to_index(PlannerInfo *root,
144 										RelOptInfo *rel, IndexOptInfo *index,
145 										IndexClauseSet *clauseset,
146 										List **joinorclauses);
147 static void match_eclass_clauses_to_index(PlannerInfo *root,
148 										  IndexOptInfo *index,
149 										  IndexClauseSet *clauseset);
150 static void match_clauses_to_index(PlannerInfo *root,
151 								   List *clauses,
152 								   IndexOptInfo *index,
153 								   IndexClauseSet *clauseset);
154 static void match_clause_to_index(PlannerInfo *root,
155 								  RestrictInfo *rinfo,
156 								  IndexOptInfo *index,
157 								  IndexClauseSet *clauseset);
158 static IndexClause *match_clause_to_indexcol(PlannerInfo *root,
159 											 RestrictInfo *rinfo,
160 											 int indexcol,
161 											 IndexOptInfo *index);
162 static IndexClause *match_boolean_index_clause(PlannerInfo *root,
163 											   RestrictInfo *rinfo,
164 											   int indexcol, IndexOptInfo *index);
165 static IndexClause *match_opclause_to_indexcol(PlannerInfo *root,
166 											   RestrictInfo *rinfo,
167 											   int indexcol,
168 											   IndexOptInfo *index);
169 static IndexClause *match_funcclause_to_indexcol(PlannerInfo *root,
170 												 RestrictInfo *rinfo,
171 												 int indexcol,
172 												 IndexOptInfo *index);
173 static IndexClause *get_index_clause_from_support(PlannerInfo *root,
174 												  RestrictInfo *rinfo,
175 												  Oid funcid,
176 												  int indexarg,
177 												  int indexcol,
178 												  IndexOptInfo *index);
179 static IndexClause *match_saopclause_to_indexcol(PlannerInfo *root,
180 												 RestrictInfo *rinfo,
181 												 int indexcol,
182 												 IndexOptInfo *index);
183 static IndexClause *match_rowcompare_to_indexcol(PlannerInfo *root,
184 												 RestrictInfo *rinfo,
185 												 int indexcol,
186 												 IndexOptInfo *index);
187 static IndexClause *expand_indexqual_rowcompare(PlannerInfo *root,
188 												RestrictInfo *rinfo,
189 												int indexcol,
190 												IndexOptInfo *index,
191 												Oid expr_op,
192 												bool var_on_left);
193 static void match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
194 									List **orderby_clauses_p,
195 									List **clause_columns_p);
196 static Expr *match_clause_to_ordering_op(IndexOptInfo *index,
197 										 int indexcol, Expr *clause, Oid pk_opfamily);
198 static bool ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
199 									   EquivalenceClass *ec, EquivalenceMember *em,
200 									   void *arg);
201 
202 
203 /*
204  * create_index_paths()
205  *	  Generate all interesting index paths for the given relation.
206  *	  Candidate paths are added to the rel's pathlist (using add_path).
207  *
208  * To be considered for an index scan, an index must match one or more
209  * restriction clauses or join clauses from the query's qual condition,
210  * or match the query's ORDER BY condition, or have a predicate that
211  * matches the query's qual condition.
212  *
213  * There are two basic kinds of index scans.  A "plain" index scan uses
214  * only restriction clauses (possibly none at all) in its indexqual,
215  * so it can be applied in any context.  A "parameterized" index scan uses
216  * join clauses (plus restriction clauses, if available) in its indexqual.
217  * When joining such a scan to one of the relations supplying the other
218  * variables used in its indexqual, the parameterized scan must appear as
219  * the inner relation of a nestloop join; it can't be used on the outer side,
220  * nor in a merge or hash join.  In that context, values for the other rels'
221  * attributes are available and fixed during any one scan of the indexpath.
222  *
223  * An IndexPath is generated and submitted to add_path() for each plain or
224  * parameterized index scan this routine deems potentially interesting for
225  * the current query.
226  *
227  * 'rel' is the relation for which we want to generate index paths
228  *
229  * Note: check_index_predicates() must have been run previously for this rel.
230  *
231  * Note: in cases involving LATERAL references in the relation's tlist, it's
232  * possible that rel->lateral_relids is nonempty.  Currently, we include
233  * lateral_relids into the parameterization reported for each path, but don't
234  * take it into account otherwise.  The fact that any such rels *must* be
235  * available as parameter sources perhaps should influence our choices of
236  * index quals ... but for now, it doesn't seem worth troubling over.
237  * In particular, comments below about "unparameterized" paths should be read
238  * as meaning "unparameterized so far as the indexquals are concerned".
239  */
240 void
create_index_paths(PlannerInfo * root,RelOptInfo * rel)241 create_index_paths(PlannerInfo *root, RelOptInfo *rel)
242 {
243 	List	   *indexpaths;
244 	List	   *bitindexpaths;
245 	List	   *bitjoinpaths;
246 	List	   *joinorclauses;
247 	IndexClauseSet rclauseset;
248 	IndexClauseSet jclauseset;
249 	IndexClauseSet eclauseset;
250 	ListCell   *lc;
251 
252 	/* Skip the whole mess if no indexes */
253 	if (rel->indexlist == NIL)
254 		return;
255 
256 	/* Bitmap paths are collected and then dealt with at the end */
257 	bitindexpaths = bitjoinpaths = joinorclauses = NIL;
258 
259 	/* Examine each index in turn */
260 	foreach(lc, rel->indexlist)
261 	{
262 		IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
263 
264 		/* Protect limited-size array in IndexClauseSets */
265 		Assert(index->nkeycolumns <= INDEX_MAX_KEYS);
266 
267 		/*
268 		 * Ignore partial indexes that do not match the query.
269 		 * (generate_bitmap_or_paths() might be able to do something with
270 		 * them, but that's of no concern here.)
271 		 */
272 		if (index->indpred != NIL && !index->predOK)
273 			continue;
274 
275 		/*
276 		 * Identify the restriction clauses that can match the index.
277 		 */
278 		MemSet(&rclauseset, 0, sizeof(rclauseset));
279 		match_restriction_clauses_to_index(root, index, &rclauseset);
280 
281 		/*
282 		 * Build index paths from the restriction clauses.  These will be
283 		 * non-parameterized paths.  Plain paths go directly to add_path(),
284 		 * bitmap paths are added to bitindexpaths to be handled below.
285 		 */
286 		get_index_paths(root, rel, index, &rclauseset,
287 						&bitindexpaths);
288 
289 		/*
290 		 * Identify the join clauses that can match the index.  For the moment
291 		 * we keep them separate from the restriction clauses.  Note that this
292 		 * step finds only "loose" join clauses that have not been merged into
293 		 * EquivalenceClasses.  Also, collect join OR clauses for later.
294 		 */
295 		MemSet(&jclauseset, 0, sizeof(jclauseset));
296 		match_join_clauses_to_index(root, rel, index,
297 									&jclauseset, &joinorclauses);
298 
299 		/*
300 		 * Look for EquivalenceClasses that can generate joinclauses matching
301 		 * the index.
302 		 */
303 		MemSet(&eclauseset, 0, sizeof(eclauseset));
304 		match_eclass_clauses_to_index(root, index,
305 									  &eclauseset);
306 
307 		/*
308 		 * If we found any plain or eclass join clauses, build parameterized
309 		 * index paths using them.
310 		 */
311 		if (jclauseset.nonempty || eclauseset.nonempty)
312 			consider_index_join_clauses(root, rel, index,
313 										&rclauseset,
314 										&jclauseset,
315 										&eclauseset,
316 										&bitjoinpaths);
317 	}
318 
319 	/*
320 	 * Generate BitmapOrPaths for any suitable OR-clauses present in the
321 	 * restriction list.  Add these to bitindexpaths.
322 	 */
323 	indexpaths = generate_bitmap_or_paths(root, rel,
324 										  rel->baserestrictinfo, NIL);
325 	bitindexpaths = list_concat(bitindexpaths, indexpaths);
326 
327 	/*
328 	 * Likewise, generate BitmapOrPaths for any suitable OR-clauses present in
329 	 * the joinclause list.  Add these to bitjoinpaths.
330 	 */
331 	indexpaths = generate_bitmap_or_paths(root, rel,
332 										  joinorclauses, rel->baserestrictinfo);
333 	bitjoinpaths = list_concat(bitjoinpaths, indexpaths);
334 
335 	/*
336 	 * If we found anything usable, generate a BitmapHeapPath for the most
337 	 * promising combination of restriction bitmap index paths.  Note there
338 	 * will be only one such path no matter how many indexes exist.  This
339 	 * should be sufficient since there's basically only one figure of merit
340 	 * (total cost) for such a path.
341 	 */
342 	if (bitindexpaths != NIL)
343 	{
344 		Path	   *bitmapqual;
345 		BitmapHeapPath *bpath;
346 
347 		bitmapqual = choose_bitmap_and(root, rel, bitindexpaths);
348 		bpath = create_bitmap_heap_path(root, rel, bitmapqual,
349 										rel->lateral_relids, 1.0, 0);
350 		add_path(rel, (Path *) bpath);
351 
352 		/* create a partial bitmap heap path */
353 		if (rel->consider_parallel && rel->lateral_relids == NULL)
354 			create_partial_bitmap_paths(root, rel, bitmapqual);
355 	}
356 
357 	/*
358 	 * Likewise, if we found anything usable, generate BitmapHeapPaths for the
359 	 * most promising combinations of join bitmap index paths.  Our strategy
360 	 * is to generate one such path for each distinct parameterization seen
361 	 * among the available bitmap index paths.  This may look pretty
362 	 * expensive, but usually there won't be very many distinct
363 	 * parameterizations.  (This logic is quite similar to that in
364 	 * consider_index_join_clauses, but we're working with whole paths not
365 	 * individual clauses.)
366 	 */
367 	if (bitjoinpaths != NIL)
368 	{
369 		List	   *all_path_outers;
370 		ListCell   *lc;
371 
372 		/* Identify each distinct parameterization seen in bitjoinpaths */
373 		all_path_outers = NIL;
374 		foreach(lc, bitjoinpaths)
375 		{
376 			Path	   *path = (Path *) lfirst(lc);
377 			Relids		required_outer = PATH_REQ_OUTER(path);
378 
379 			if (!bms_equal_any(required_outer, all_path_outers))
380 				all_path_outers = lappend(all_path_outers, required_outer);
381 		}
382 
383 		/* Now, for each distinct parameterization set ... */
384 		foreach(lc, all_path_outers)
385 		{
386 			Relids		max_outers = (Relids) lfirst(lc);
387 			List	   *this_path_set;
388 			Path	   *bitmapqual;
389 			Relids		required_outer;
390 			double		loop_count;
391 			BitmapHeapPath *bpath;
392 			ListCell   *lcp;
393 
394 			/* Identify all the bitmap join paths needing no more than that */
395 			this_path_set = NIL;
396 			foreach(lcp, bitjoinpaths)
397 			{
398 				Path	   *path = (Path *) lfirst(lcp);
399 
400 				if (bms_is_subset(PATH_REQ_OUTER(path), max_outers))
401 					this_path_set = lappend(this_path_set, path);
402 			}
403 
404 			/*
405 			 * Add in restriction bitmap paths, since they can be used
406 			 * together with any join paths.
407 			 */
408 			this_path_set = list_concat(this_path_set, bitindexpaths);
409 
410 			/* Select best AND combination for this parameterization */
411 			bitmapqual = choose_bitmap_and(root, rel, this_path_set);
412 
413 			/* And push that path into the mix */
414 			required_outer = PATH_REQ_OUTER(bitmapqual);
415 			loop_count = get_loop_count(root, rel->relid, required_outer);
416 			bpath = create_bitmap_heap_path(root, rel, bitmapqual,
417 											required_outer, loop_count, 0);
418 			add_path(rel, (Path *) bpath);
419 		}
420 	}
421 }
422 
423 /*
424  * consider_index_join_clauses
425  *	  Given sets of join clauses for an index, decide which parameterized
426  *	  index paths to build.
427  *
428  * Plain indexpaths are sent directly to add_path, while potential
429  * bitmap indexpaths are added to *bitindexpaths for later processing.
430  *
431  * 'rel' is the index's heap relation
432  * 'index' is the index for which we want to generate paths
433  * 'rclauseset' is the collection of indexable restriction clauses
434  * 'jclauseset' is the collection of indexable simple join clauses
435  * 'eclauseset' is the collection of indexable clauses from EquivalenceClasses
436  * '*bitindexpaths' is the list to add bitmap paths to
437  */
438 static void
consider_index_join_clauses(PlannerInfo * root,RelOptInfo * rel,IndexOptInfo * index,IndexClauseSet * rclauseset,IndexClauseSet * jclauseset,IndexClauseSet * eclauseset,List ** bitindexpaths)439 consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel,
440 							IndexOptInfo *index,
441 							IndexClauseSet *rclauseset,
442 							IndexClauseSet *jclauseset,
443 							IndexClauseSet *eclauseset,
444 							List **bitindexpaths)
445 {
446 	int			considered_clauses = 0;
447 	List	   *considered_relids = NIL;
448 	int			indexcol;
449 
450 	/*
451 	 * The strategy here is to identify every potentially useful set of outer
452 	 * rels that can provide indexable join clauses.  For each such set,
453 	 * select all the join clauses available from those outer rels, add on all
454 	 * the indexable restriction clauses, and generate plain and/or bitmap
455 	 * index paths for that set of clauses.  This is based on the assumption
456 	 * that it's always better to apply a clause as an indexqual than as a
457 	 * filter (qpqual); which is where an available clause would end up being
458 	 * applied if we omit it from the indexquals.
459 	 *
460 	 * This looks expensive, but in most practical cases there won't be very
461 	 * many distinct sets of outer rels to consider.  As a safety valve when
462 	 * that's not true, we use a heuristic: limit the number of outer rel sets
463 	 * considered to a multiple of the number of clauses considered.  (We'll
464 	 * always consider using each individual join clause, though.)
465 	 *
466 	 * For simplicity in selecting relevant clauses, we represent each set of
467 	 * outer rels as a maximum set of clause_relids --- that is, the indexed
468 	 * relation itself is also included in the relids set.  considered_relids
469 	 * lists all relids sets we've already tried.
470 	 */
471 	for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
472 	{
473 		/* Consider each applicable simple join clause */
474 		considered_clauses += list_length(jclauseset->indexclauses[indexcol]);
475 		consider_index_join_outer_rels(root, rel, index,
476 									   rclauseset, jclauseset, eclauseset,
477 									   bitindexpaths,
478 									   jclauseset->indexclauses[indexcol],
479 									   considered_clauses,
480 									   &considered_relids);
481 		/* Consider each applicable eclass join clause */
482 		considered_clauses += list_length(eclauseset->indexclauses[indexcol]);
483 		consider_index_join_outer_rels(root, rel, index,
484 									   rclauseset, jclauseset, eclauseset,
485 									   bitindexpaths,
486 									   eclauseset->indexclauses[indexcol],
487 									   considered_clauses,
488 									   &considered_relids);
489 	}
490 }
491 
492 /*
493  * consider_index_join_outer_rels
494  *	  Generate parameterized paths based on clause relids in the clause list.
495  *
496  * Workhorse for consider_index_join_clauses; see notes therein for rationale.
497  *
498  * 'rel', 'index', 'rclauseset', 'jclauseset', 'eclauseset', and
499  *		'bitindexpaths' as above
500  * 'indexjoinclauses' is a list of IndexClauses for join clauses
501  * 'considered_clauses' is the total number of clauses considered (so far)
502  * '*considered_relids' is a list of all relids sets already considered
503  */
504 static void
consider_index_join_outer_rels(PlannerInfo * root,RelOptInfo * rel,IndexOptInfo * index,IndexClauseSet * rclauseset,IndexClauseSet * jclauseset,IndexClauseSet * eclauseset,List ** bitindexpaths,List * indexjoinclauses,int considered_clauses,List ** considered_relids)505 consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
506 							   IndexOptInfo *index,
507 							   IndexClauseSet *rclauseset,
508 							   IndexClauseSet *jclauseset,
509 							   IndexClauseSet *eclauseset,
510 							   List **bitindexpaths,
511 							   List *indexjoinclauses,
512 							   int considered_clauses,
513 							   List **considered_relids)
514 {
515 	ListCell   *lc;
516 
517 	/* Examine relids of each joinclause in the given list */
518 	foreach(lc, indexjoinclauses)
519 	{
520 		IndexClause *iclause = (IndexClause *) lfirst(lc);
521 		Relids		clause_relids = iclause->rinfo->clause_relids;
522 		EquivalenceClass *parent_ec = iclause->rinfo->parent_ec;
523 		int			num_considered_relids;
524 
525 		/* If we already tried its relids set, no need to do so again */
526 		if (bms_equal_any(clause_relids, *considered_relids))
527 			continue;
528 
529 		/*
530 		 * Generate the union of this clause's relids set with each
531 		 * previously-tried set.  This ensures we try this clause along with
532 		 * every interesting subset of previous clauses.  However, to avoid
533 		 * exponential growth of planning time when there are many clauses,
534 		 * limit the number of relid sets accepted to 10 * considered_clauses.
535 		 *
536 		 * Note: get_join_index_paths appends entries to *considered_relids,
537 		 * but we do not need to visit such newly-added entries within this
538 		 * loop, so we don't use foreach() here.  No real harm would be done
539 		 * if we did visit them, since the subset check would reject them; but
540 		 * it would waste some cycles.
541 		 */
542 		num_considered_relids = list_length(*considered_relids);
543 		for (int pos = 0; pos < num_considered_relids; pos++)
544 		{
545 			Relids		oldrelids = (Relids) list_nth(*considered_relids, pos);
546 
547 			/*
548 			 * If either is a subset of the other, no new set is possible.
549 			 * This isn't a complete test for redundancy, but it's easy and
550 			 * cheap.  get_join_index_paths will check more carefully if we
551 			 * already generated the same relids set.
552 			 */
553 			if (bms_subset_compare(clause_relids, oldrelids) != BMS_DIFFERENT)
554 				continue;
555 
556 			/*
557 			 * If this clause was derived from an equivalence class, the
558 			 * clause list may contain other clauses derived from the same
559 			 * eclass.  We should not consider that combining this clause with
560 			 * one of those clauses generates a usefully different
561 			 * parameterization; so skip if any clause derived from the same
562 			 * eclass would already have been included when using oldrelids.
563 			 */
564 			if (parent_ec &&
565 				eclass_already_used(parent_ec, oldrelids,
566 									indexjoinclauses))
567 				continue;
568 
569 			/*
570 			 * If the number of relid sets considered exceeds our heuristic
571 			 * limit, stop considering combinations of clauses.  We'll still
572 			 * consider the current clause alone, though (below this loop).
573 			 */
574 			if (list_length(*considered_relids) >= 10 * considered_clauses)
575 				break;
576 
577 			/* OK, try the union set */
578 			get_join_index_paths(root, rel, index,
579 								 rclauseset, jclauseset, eclauseset,
580 								 bitindexpaths,
581 								 bms_union(clause_relids, oldrelids),
582 								 considered_relids);
583 		}
584 
585 		/* Also try this set of relids by itself */
586 		get_join_index_paths(root, rel, index,
587 							 rclauseset, jclauseset, eclauseset,
588 							 bitindexpaths,
589 							 clause_relids,
590 							 considered_relids);
591 	}
592 }
593 
594 /*
595  * get_join_index_paths
596  *	  Generate index paths using clauses from the specified outer relations.
597  *	  In addition to generating paths, relids is added to *considered_relids
598  *	  if not already present.
599  *
600  * Workhorse for consider_index_join_clauses; see notes therein for rationale.
601  *
602  * 'rel', 'index', 'rclauseset', 'jclauseset', 'eclauseset',
603  *		'bitindexpaths', 'considered_relids' as above
604  * 'relids' is the current set of relids to consider (the target rel plus
605  *		one or more outer rels)
606  */
607 static void
get_join_index_paths(PlannerInfo * root,RelOptInfo * rel,IndexOptInfo * index,IndexClauseSet * rclauseset,IndexClauseSet * jclauseset,IndexClauseSet * eclauseset,List ** bitindexpaths,Relids relids,List ** considered_relids)608 get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
609 					 IndexOptInfo *index,
610 					 IndexClauseSet *rclauseset,
611 					 IndexClauseSet *jclauseset,
612 					 IndexClauseSet *eclauseset,
613 					 List **bitindexpaths,
614 					 Relids relids,
615 					 List **considered_relids)
616 {
617 	IndexClauseSet clauseset;
618 	int			indexcol;
619 
620 	/* If we already considered this relids set, don't repeat the work */
621 	if (bms_equal_any(relids, *considered_relids))
622 		return;
623 
624 	/* Identify indexclauses usable with this relids set */
625 	MemSet(&clauseset, 0, sizeof(clauseset));
626 
627 	for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
628 	{
629 		ListCell   *lc;
630 
631 		/* First find applicable simple join clauses */
632 		foreach(lc, jclauseset->indexclauses[indexcol])
633 		{
634 			IndexClause *iclause = (IndexClause *) lfirst(lc);
635 
636 			if (bms_is_subset(iclause->rinfo->clause_relids, relids))
637 				clauseset.indexclauses[indexcol] =
638 					lappend(clauseset.indexclauses[indexcol], iclause);
639 		}
640 
641 		/*
642 		 * Add applicable eclass join clauses.  The clauses generated for each
643 		 * column are redundant (cf generate_implied_equalities_for_column),
644 		 * so we need at most one.  This is the only exception to the general
645 		 * rule of using all available index clauses.
646 		 */
647 		foreach(lc, eclauseset->indexclauses[indexcol])
648 		{
649 			IndexClause *iclause = (IndexClause *) lfirst(lc);
650 
651 			if (bms_is_subset(iclause->rinfo->clause_relids, relids))
652 			{
653 				clauseset.indexclauses[indexcol] =
654 					lappend(clauseset.indexclauses[indexcol], iclause);
655 				break;
656 			}
657 		}
658 
659 		/* Add restriction clauses */
660 		clauseset.indexclauses[indexcol] =
661 			list_concat(clauseset.indexclauses[indexcol],
662 						rclauseset->indexclauses[indexcol]);
663 
664 		if (clauseset.indexclauses[indexcol] != NIL)
665 			clauseset.nonempty = true;
666 	}
667 
668 	/* We should have found something, else caller passed silly relids */
669 	Assert(clauseset.nonempty);
670 
671 	/* Build index path(s) using the collected set of clauses */
672 	get_index_paths(root, rel, index, &clauseset, bitindexpaths);
673 
674 	/*
675 	 * Remember we considered paths for this set of relids.
676 	 */
677 	*considered_relids = lappend(*considered_relids, relids);
678 }
679 
680 /*
681  * eclass_already_used
682  *		True if any join clause usable with oldrelids was generated from
683  *		the specified equivalence class.
684  */
685 static bool
eclass_already_used(EquivalenceClass * parent_ec,Relids oldrelids,List * indexjoinclauses)686 eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
687 					List *indexjoinclauses)
688 {
689 	ListCell   *lc;
690 
691 	foreach(lc, indexjoinclauses)
692 	{
693 		IndexClause *iclause = (IndexClause *) lfirst(lc);
694 		RestrictInfo *rinfo = iclause->rinfo;
695 
696 		if (rinfo->parent_ec == parent_ec &&
697 			bms_is_subset(rinfo->clause_relids, oldrelids))
698 			return true;
699 	}
700 	return false;
701 }
702 
703 /*
704  * bms_equal_any
705  *		True if relids is bms_equal to any member of relids_list
706  *
707  * Perhaps this should be in bitmapset.c someday.
708  */
709 static bool
bms_equal_any(Relids relids,List * relids_list)710 bms_equal_any(Relids relids, List *relids_list)
711 {
712 	ListCell   *lc;
713 
714 	foreach(lc, relids_list)
715 	{
716 		if (bms_equal(relids, (Relids) lfirst(lc)))
717 			return true;
718 	}
719 	return false;
720 }
721 
722 
723 /*
724  * get_index_paths
725  *	  Given an index and a set of index clauses for it, construct IndexPaths.
726  *
727  * Plain indexpaths are sent directly to add_path, while potential
728  * bitmap indexpaths are added to *bitindexpaths for later processing.
729  *
730  * This is a fairly simple frontend to build_index_paths().  Its reason for
731  * existence is mainly to handle ScalarArrayOpExpr quals properly.  If the
732  * index AM supports them natively, we should just include them in simple
733  * index paths.  If not, we should exclude them while building simple index
734  * paths, and then make a separate attempt to include them in bitmap paths.
735  * Furthermore, we should consider excluding lower-order ScalarArrayOpExpr
736  * quals so as to create ordered paths.
737  */
738 static void
get_index_paths(PlannerInfo * root,RelOptInfo * rel,IndexOptInfo * index,IndexClauseSet * clauses,List ** bitindexpaths)739 get_index_paths(PlannerInfo *root, RelOptInfo *rel,
740 				IndexOptInfo *index, IndexClauseSet *clauses,
741 				List **bitindexpaths)
742 {
743 	List	   *indexpaths;
744 	bool		skip_nonnative_saop = false;
745 	bool		skip_lower_saop = false;
746 	ListCell   *lc;
747 
748 	/*
749 	 * Build simple index paths using the clauses.  Allow ScalarArrayOpExpr
750 	 * clauses only if the index AM supports them natively, and skip any such
751 	 * clauses for index columns after the first (so that we produce ordered
752 	 * paths if possible).
753 	 */
754 	indexpaths = build_index_paths(root, rel,
755 								   index, clauses,
756 								   index->predOK,
757 								   ST_ANYSCAN,
758 								   &skip_nonnative_saop,
759 								   &skip_lower_saop);
760 
761 	/*
762 	 * If we skipped any lower-order ScalarArrayOpExprs on an index with an AM
763 	 * that supports them, then try again including those clauses.  This will
764 	 * produce paths with more selectivity but no ordering.
765 	 */
766 	if (skip_lower_saop)
767 	{
768 		indexpaths = list_concat(indexpaths,
769 								 build_index_paths(root, rel,
770 												   index, clauses,
771 												   index->predOK,
772 												   ST_ANYSCAN,
773 												   &skip_nonnative_saop,
774 												   NULL));
775 	}
776 
777 	/*
778 	 * Submit all the ones that can form plain IndexScan plans to add_path. (A
779 	 * plain IndexPath can represent either a plain IndexScan or an
780 	 * IndexOnlyScan, but for our purposes here that distinction does not
781 	 * matter.  However, some of the indexes might support only bitmap scans,
782 	 * and those we mustn't submit to add_path here.)
783 	 *
784 	 * Also, pick out the ones that are usable as bitmap scans.  For that, we
785 	 * must discard indexes that don't support bitmap scans, and we also are
786 	 * only interested in paths that have some selectivity; we should discard
787 	 * anything that was generated solely for ordering purposes.
788 	 */
789 	foreach(lc, indexpaths)
790 	{
791 		IndexPath  *ipath = (IndexPath *) lfirst(lc);
792 
793 		if (index->amhasgettuple)
794 			add_path(rel, (Path *) ipath);
795 
796 		if (index->amhasgetbitmap &&
797 			(ipath->path.pathkeys == NIL ||
798 			 ipath->indexselectivity < 1.0))
799 			*bitindexpaths = lappend(*bitindexpaths, ipath);
800 	}
801 
802 	/*
803 	 * If there were ScalarArrayOpExpr clauses that the index can't handle
804 	 * natively, generate bitmap scan paths relying on executor-managed
805 	 * ScalarArrayOpExpr.
806 	 */
807 	if (skip_nonnative_saop)
808 	{
809 		indexpaths = build_index_paths(root, rel,
810 									   index, clauses,
811 									   false,
812 									   ST_BITMAPSCAN,
813 									   NULL,
814 									   NULL);
815 		*bitindexpaths = list_concat(*bitindexpaths, indexpaths);
816 	}
817 }
818 
819 /*
820  * build_index_paths
821  *	  Given an index and a set of index clauses for it, construct zero
822  *	  or more IndexPaths. It also constructs zero or more partial IndexPaths.
823  *
824  * We return a list of paths because (1) this routine checks some cases
825  * that should cause us to not generate any IndexPath, and (2) in some
826  * cases we want to consider both a forward and a backward scan, so as
827  * to obtain both sort orders.  Note that the paths are just returned
828  * to the caller and not immediately fed to add_path().
829  *
830  * At top level, useful_predicate should be exactly the index's predOK flag
831  * (ie, true if it has a predicate that was proven from the restriction
832  * clauses).  When working on an arm of an OR clause, useful_predicate
833  * should be true if the predicate required the current OR list to be proven.
834  * Note that this routine should never be called at all if the index has an
835  * unprovable predicate.
836  *
837  * scantype indicates whether we want to create plain indexscans, bitmap
838  * indexscans, or both.  When it's ST_BITMAPSCAN, we will not consider
839  * index ordering while deciding if a Path is worth generating.
840  *
841  * If skip_nonnative_saop is non-NULL, we ignore ScalarArrayOpExpr clauses
842  * unless the index AM supports them directly, and we set *skip_nonnative_saop
843  * to true if we found any such clauses (caller must initialize the variable
844  * to false).  If it's NULL, we do not ignore ScalarArrayOpExpr clauses.
845  *
846  * If skip_lower_saop is non-NULL, we ignore ScalarArrayOpExpr clauses for
847  * non-first index columns, and we set *skip_lower_saop to true if we found
848  * any such clauses (caller must initialize the variable to false).  If it's
849  * NULL, we do not ignore non-first ScalarArrayOpExpr clauses, but they will
850  * result in considering the scan's output to be unordered.
851  *
852  * 'rel' is the index's heap relation
853  * 'index' is the index for which we want to generate paths
854  * 'clauses' is the collection of indexable clauses (IndexClause nodes)
855  * 'useful_predicate' indicates whether the index has a useful predicate
856  * 'scantype' indicates whether we need plain or bitmap scan support
857  * 'skip_nonnative_saop' indicates whether to accept SAOP if index AM doesn't
858  * 'skip_lower_saop' indicates whether to accept non-first-column SAOP
859  */
860 static List *
build_index_paths(PlannerInfo * root,RelOptInfo * rel,IndexOptInfo * index,IndexClauseSet * clauses,bool useful_predicate,ScanTypeControl scantype,bool * skip_nonnative_saop,bool * skip_lower_saop)861 build_index_paths(PlannerInfo *root, RelOptInfo *rel,
862 				  IndexOptInfo *index, IndexClauseSet *clauses,
863 				  bool useful_predicate,
864 				  ScanTypeControl scantype,
865 				  bool *skip_nonnative_saop,
866 				  bool *skip_lower_saop)
867 {
868 	List	   *result = NIL;
869 	IndexPath  *ipath;
870 	List	   *index_clauses;
871 	Relids		outer_relids;
872 	double		loop_count;
873 	List	   *orderbyclauses;
874 	List	   *orderbyclausecols;
875 	List	   *index_pathkeys;
876 	List	   *useful_pathkeys;
877 	bool		found_lower_saop_clause;
878 	bool		pathkeys_possibly_useful;
879 	bool		index_is_ordered;
880 	bool		index_only_scan;
881 	int			indexcol;
882 
883 	/*
884 	 * Check that index supports the desired scan type(s)
885 	 */
886 	switch (scantype)
887 	{
888 		case ST_INDEXSCAN:
889 			if (!index->amhasgettuple)
890 				return NIL;
891 			break;
892 		case ST_BITMAPSCAN:
893 			if (!index->amhasgetbitmap)
894 				return NIL;
895 			break;
896 		case ST_ANYSCAN:
897 			/* either or both are OK */
898 			break;
899 	}
900 
901 	/*
902 	 * 1. Combine the per-column IndexClause lists into an overall list.
903 	 *
904 	 * In the resulting list, clauses are ordered by index key, so that the
905 	 * column numbers form a nondecreasing sequence.  (This order is depended
906 	 * on by btree and possibly other places.)  The list can be empty, if the
907 	 * index AM allows that.
908 	 *
909 	 * found_lower_saop_clause is set true if we accept a ScalarArrayOpExpr
910 	 * index clause for a non-first index column.  This prevents us from
911 	 * assuming that the scan result is ordered.  (Actually, the result is
912 	 * still ordered if there are equality constraints for all earlier
913 	 * columns, but it seems too expensive and non-modular for this code to be
914 	 * aware of that refinement.)
915 	 *
916 	 * We also build a Relids set showing which outer rels are required by the
917 	 * selected clauses.  Any lateral_relids are included in that, but not
918 	 * otherwise accounted for.
919 	 */
920 	index_clauses = NIL;
921 	found_lower_saop_clause = false;
922 	outer_relids = bms_copy(rel->lateral_relids);
923 	for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
924 	{
925 		ListCell   *lc;
926 
927 		foreach(lc, clauses->indexclauses[indexcol])
928 		{
929 			IndexClause *iclause = (IndexClause *) lfirst(lc);
930 			RestrictInfo *rinfo = iclause->rinfo;
931 
932 			/* We might need to omit ScalarArrayOpExpr clauses */
933 			if (IsA(rinfo->clause, ScalarArrayOpExpr))
934 			{
935 				if (!index->amsearcharray)
936 				{
937 					if (skip_nonnative_saop)
938 					{
939 						/* Ignore because not supported by index */
940 						*skip_nonnative_saop = true;
941 						continue;
942 					}
943 					/* Caller had better intend this only for bitmap scan */
944 					Assert(scantype == ST_BITMAPSCAN);
945 				}
946 				if (indexcol > 0)
947 				{
948 					if (skip_lower_saop)
949 					{
950 						/* Caller doesn't want to lose index ordering */
951 						*skip_lower_saop = true;
952 						continue;
953 					}
954 					found_lower_saop_clause = true;
955 				}
956 			}
957 
958 			/* OK to include this clause */
959 			index_clauses = lappend(index_clauses, iclause);
960 			outer_relids = bms_add_members(outer_relids,
961 										   rinfo->clause_relids);
962 		}
963 
964 		/*
965 		 * If no clauses match the first index column, check for amoptionalkey
966 		 * restriction.  We can't generate a scan over an index with
967 		 * amoptionalkey = false unless there's at least one index clause.
968 		 * (When working on columns after the first, this test cannot fail. It
969 		 * is always okay for columns after the first to not have any
970 		 * clauses.)
971 		 */
972 		if (index_clauses == NIL && !index->amoptionalkey)
973 			return NIL;
974 	}
975 
976 	/* We do not want the index's rel itself listed in outer_relids */
977 	outer_relids = bms_del_member(outer_relids, rel->relid);
978 	/* Enforce convention that outer_relids is exactly NULL if empty */
979 	if (bms_is_empty(outer_relids))
980 		outer_relids = NULL;
981 
982 	/* Compute loop_count for cost estimation purposes */
983 	loop_count = get_loop_count(root, rel->relid, outer_relids);
984 
985 	/*
986 	 * 2. Compute pathkeys describing index's ordering, if any, then see how
987 	 * many of them are actually useful for this query.  This is not relevant
988 	 * if we are only trying to build bitmap indexscans, nor if we have to
989 	 * assume the scan is unordered.
990 	 */
991 	pathkeys_possibly_useful = (scantype != ST_BITMAPSCAN &&
992 								!found_lower_saop_clause &&
993 								has_useful_pathkeys(root, rel));
994 	index_is_ordered = (index->sortopfamily != NULL);
995 	if (index_is_ordered && pathkeys_possibly_useful)
996 	{
997 		index_pathkeys = build_index_pathkeys(root, index,
998 											  ForwardScanDirection);
999 		useful_pathkeys = truncate_useless_pathkeys(root, rel,
1000 													index_pathkeys);
1001 		orderbyclauses = NIL;
1002 		orderbyclausecols = NIL;
1003 	}
1004 	else if (index->amcanorderbyop && pathkeys_possibly_useful)
1005 	{
1006 		/* see if we can generate ordering operators for query_pathkeys */
1007 		match_pathkeys_to_index(index, root->query_pathkeys,
1008 								&orderbyclauses,
1009 								&orderbyclausecols);
1010 		if (orderbyclauses)
1011 			useful_pathkeys = root->query_pathkeys;
1012 		else
1013 			useful_pathkeys = NIL;
1014 	}
1015 	else
1016 	{
1017 		useful_pathkeys = NIL;
1018 		orderbyclauses = NIL;
1019 		orderbyclausecols = NIL;
1020 	}
1021 
1022 	/*
1023 	 * 3. Check if an index-only scan is possible.  If we're not building
1024 	 * plain indexscans, this isn't relevant since bitmap scans don't support
1025 	 * index data retrieval anyway.
1026 	 */
1027 	index_only_scan = (scantype != ST_BITMAPSCAN &&
1028 					   check_index_only(rel, index));
1029 
1030 	/*
1031 	 * 4. Generate an indexscan path if there are relevant restriction clauses
1032 	 * in the current clauses, OR the index ordering is potentially useful for
1033 	 * later merging or final output ordering, OR the index has a useful
1034 	 * predicate, OR an index-only scan is possible.
1035 	 */
1036 	if (index_clauses != NIL || useful_pathkeys != NIL || useful_predicate ||
1037 		index_only_scan)
1038 	{
1039 		ipath = create_index_path(root, index,
1040 								  index_clauses,
1041 								  orderbyclauses,
1042 								  orderbyclausecols,
1043 								  useful_pathkeys,
1044 								  index_is_ordered ?
1045 								  ForwardScanDirection :
1046 								  NoMovementScanDirection,
1047 								  index_only_scan,
1048 								  outer_relids,
1049 								  loop_count,
1050 								  false);
1051 		result = lappend(result, ipath);
1052 
1053 		/*
1054 		 * If appropriate, consider parallel index scan.  We don't allow
1055 		 * parallel index scan for bitmap index scans.
1056 		 */
1057 		if (index->amcanparallel &&
1058 			rel->consider_parallel && outer_relids == NULL &&
1059 			scantype != ST_BITMAPSCAN)
1060 		{
1061 			ipath = create_index_path(root, index,
1062 									  index_clauses,
1063 									  orderbyclauses,
1064 									  orderbyclausecols,
1065 									  useful_pathkeys,
1066 									  index_is_ordered ?
1067 									  ForwardScanDirection :
1068 									  NoMovementScanDirection,
1069 									  index_only_scan,
1070 									  outer_relids,
1071 									  loop_count,
1072 									  true);
1073 
1074 			/*
1075 			 * if, after costing the path, we find that it's not worth using
1076 			 * parallel workers, just free it.
1077 			 */
1078 			if (ipath->path.parallel_workers > 0)
1079 				add_partial_path(rel, (Path *) ipath);
1080 			else
1081 				pfree(ipath);
1082 		}
1083 	}
1084 
1085 	/*
1086 	 * 5. If the index is ordered, a backwards scan might be interesting.
1087 	 */
1088 	if (index_is_ordered && pathkeys_possibly_useful)
1089 	{
1090 		index_pathkeys = build_index_pathkeys(root, index,
1091 											  BackwardScanDirection);
1092 		useful_pathkeys = truncate_useless_pathkeys(root, rel,
1093 													index_pathkeys);
1094 		if (useful_pathkeys != NIL)
1095 		{
1096 			ipath = create_index_path(root, index,
1097 									  index_clauses,
1098 									  NIL,
1099 									  NIL,
1100 									  useful_pathkeys,
1101 									  BackwardScanDirection,
1102 									  index_only_scan,
1103 									  outer_relids,
1104 									  loop_count,
1105 									  false);
1106 			result = lappend(result, ipath);
1107 
1108 			/* If appropriate, consider parallel index scan */
1109 			if (index->amcanparallel &&
1110 				rel->consider_parallel && outer_relids == NULL &&
1111 				scantype != ST_BITMAPSCAN)
1112 			{
1113 				ipath = create_index_path(root, index,
1114 										  index_clauses,
1115 										  NIL,
1116 										  NIL,
1117 										  useful_pathkeys,
1118 										  BackwardScanDirection,
1119 										  index_only_scan,
1120 										  outer_relids,
1121 										  loop_count,
1122 										  true);
1123 
1124 				/*
1125 				 * if, after costing the path, we find that it's not worth
1126 				 * using parallel workers, just free it.
1127 				 */
1128 				if (ipath->path.parallel_workers > 0)
1129 					add_partial_path(rel, (Path *) ipath);
1130 				else
1131 					pfree(ipath);
1132 			}
1133 		}
1134 	}
1135 
1136 	return result;
1137 }
1138 
1139 /*
1140  * build_paths_for_OR
1141  *	  Given a list of restriction clauses from one arm of an OR clause,
1142  *	  construct all matching IndexPaths for the relation.
1143  *
1144  * Here we must scan all indexes of the relation, since a bitmap OR tree
1145  * can use multiple indexes.
1146  *
1147  * The caller actually supplies two lists of restriction clauses: some
1148  * "current" ones and some "other" ones.  Both lists can be used freely
1149  * to match keys of the index, but an index must use at least one of the
1150  * "current" clauses to be considered usable.  The motivation for this is
1151  * examples like
1152  *		WHERE (x = 42) AND (... OR (y = 52 AND z = 77) OR ....)
1153  * While we are considering the y/z subclause of the OR, we can use "x = 42"
1154  * as one of the available index conditions; but we shouldn't match the
1155  * subclause to any index on x alone, because such a Path would already have
1156  * been generated at the upper level.  So we could use an index on x,y,z
1157  * or an index on x,y for the OR subclause, but not an index on just x.
1158  * When dealing with a partial index, a match of the index predicate to
1159  * one of the "current" clauses also makes the index usable.
1160  *
1161  * 'rel' is the relation for which we want to generate index paths
1162  * 'clauses' is the current list of clauses (RestrictInfo nodes)
1163  * 'other_clauses' is the list of additional upper-level clauses
1164  */
1165 static List *
build_paths_for_OR(PlannerInfo * root,RelOptInfo * rel,List * clauses,List * other_clauses)1166 build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
1167 				   List *clauses, List *other_clauses)
1168 {
1169 	List	   *result = NIL;
1170 	List	   *all_clauses = NIL;	/* not computed till needed */
1171 	ListCell   *lc;
1172 
1173 	foreach(lc, rel->indexlist)
1174 	{
1175 		IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
1176 		IndexClauseSet clauseset;
1177 		List	   *indexpaths;
1178 		bool		useful_predicate;
1179 
1180 		/* Ignore index if it doesn't support bitmap scans */
1181 		if (!index->amhasgetbitmap)
1182 			continue;
1183 
1184 		/*
1185 		 * Ignore partial indexes that do not match the query.  If a partial
1186 		 * index is marked predOK then we know it's OK.  Otherwise, we have to
1187 		 * test whether the added clauses are sufficient to imply the
1188 		 * predicate. If so, we can use the index in the current context.
1189 		 *
1190 		 * We set useful_predicate to true iff the predicate was proven using
1191 		 * the current set of clauses.  This is needed to prevent matching a
1192 		 * predOK index to an arm of an OR, which would be a legal but
1193 		 * pointlessly inefficient plan.  (A better plan will be generated by
1194 		 * just scanning the predOK index alone, no OR.)
1195 		 */
1196 		useful_predicate = false;
1197 		if (index->indpred != NIL)
1198 		{
1199 			if (index->predOK)
1200 			{
1201 				/* Usable, but don't set useful_predicate */
1202 			}
1203 			else
1204 			{
1205 				/* Form all_clauses if not done already */
1206 				if (all_clauses == NIL)
1207 					all_clauses = list_concat_copy(clauses, other_clauses);
1208 
1209 				if (!predicate_implied_by(index->indpred, all_clauses, false))
1210 					continue;	/* can't use it at all */
1211 
1212 				if (!predicate_implied_by(index->indpred, other_clauses, false))
1213 					useful_predicate = true;
1214 			}
1215 		}
1216 
1217 		/*
1218 		 * Identify the restriction clauses that can match the index.
1219 		 */
1220 		MemSet(&clauseset, 0, sizeof(clauseset));
1221 		match_clauses_to_index(root, clauses, index, &clauseset);
1222 
1223 		/*
1224 		 * If no matches so far, and the index predicate isn't useful, we
1225 		 * don't want it.
1226 		 */
1227 		if (!clauseset.nonempty && !useful_predicate)
1228 			continue;
1229 
1230 		/*
1231 		 * Add "other" restriction clauses to the clauseset.
1232 		 */
1233 		match_clauses_to_index(root, other_clauses, index, &clauseset);
1234 
1235 		/*
1236 		 * Construct paths if possible.
1237 		 */
1238 		indexpaths = build_index_paths(root, rel,
1239 									   index, &clauseset,
1240 									   useful_predicate,
1241 									   ST_BITMAPSCAN,
1242 									   NULL,
1243 									   NULL);
1244 		result = list_concat(result, indexpaths);
1245 	}
1246 
1247 	return result;
1248 }
1249 
1250 /*
1251  * generate_bitmap_or_paths
1252  *		Look through the list of clauses to find OR clauses, and generate
1253  *		a BitmapOrPath for each one we can handle that way.  Return a list
1254  *		of the generated BitmapOrPaths.
1255  *
1256  * other_clauses is a list of additional clauses that can be assumed true
1257  * for the purpose of generating indexquals, but are not to be searched for
1258  * ORs.  (See build_paths_for_OR() for motivation.)
1259  */
1260 static List *
generate_bitmap_or_paths(PlannerInfo * root,RelOptInfo * rel,List * clauses,List * other_clauses)1261 generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
1262 						 List *clauses, List *other_clauses)
1263 {
1264 	List	   *result = NIL;
1265 	List	   *all_clauses;
1266 	ListCell   *lc;
1267 
1268 	/*
1269 	 * We can use both the current and other clauses as context for
1270 	 * build_paths_for_OR; no need to remove ORs from the lists.
1271 	 */
1272 	all_clauses = list_concat_copy(clauses, other_clauses);
1273 
1274 	foreach(lc, clauses)
1275 	{
1276 		RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1277 		List	   *pathlist;
1278 		Path	   *bitmapqual;
1279 		ListCell   *j;
1280 
1281 		/* Ignore RestrictInfos that aren't ORs */
1282 		if (!restriction_is_or_clause(rinfo))
1283 			continue;
1284 
1285 		/*
1286 		 * We must be able to match at least one index to each of the arms of
1287 		 * the OR, else we can't use it.
1288 		 */
1289 		pathlist = NIL;
1290 		foreach(j, ((BoolExpr *) rinfo->orclause)->args)
1291 		{
1292 			Node	   *orarg = (Node *) lfirst(j);
1293 			List	   *indlist;
1294 
1295 			/* OR arguments should be ANDs or sub-RestrictInfos */
1296 			if (is_andclause(orarg))
1297 			{
1298 				List	   *andargs = ((BoolExpr *) orarg)->args;
1299 
1300 				indlist = build_paths_for_OR(root, rel,
1301 											 andargs,
1302 											 all_clauses);
1303 
1304 				/* Recurse in case there are sub-ORs */
1305 				indlist = list_concat(indlist,
1306 									  generate_bitmap_or_paths(root, rel,
1307 															   andargs,
1308 															   all_clauses));
1309 			}
1310 			else
1311 			{
1312 				RestrictInfo *rinfo = castNode(RestrictInfo, orarg);
1313 				List	   *orargs;
1314 
1315 				Assert(!restriction_is_or_clause(rinfo));
1316 				orargs = list_make1(rinfo);
1317 
1318 				indlist = build_paths_for_OR(root, rel,
1319 											 orargs,
1320 											 all_clauses);
1321 			}
1322 
1323 			/*
1324 			 * If nothing matched this arm, we can't do anything with this OR
1325 			 * clause.
1326 			 */
1327 			if (indlist == NIL)
1328 			{
1329 				pathlist = NIL;
1330 				break;
1331 			}
1332 
1333 			/*
1334 			 * OK, pick the most promising AND combination, and add it to
1335 			 * pathlist.
1336 			 */
1337 			bitmapqual = choose_bitmap_and(root, rel, indlist);
1338 			pathlist = lappend(pathlist, bitmapqual);
1339 		}
1340 
1341 		/*
1342 		 * If we have a match for every arm, then turn them into a
1343 		 * BitmapOrPath, and add to result list.
1344 		 */
1345 		if (pathlist != NIL)
1346 		{
1347 			bitmapqual = (Path *) create_bitmap_or_path(root, rel, pathlist);
1348 			result = lappend(result, bitmapqual);
1349 		}
1350 	}
1351 
1352 	return result;
1353 }
1354 
1355 
1356 /*
1357  * choose_bitmap_and
1358  *		Given a nonempty list of bitmap paths, AND them into one path.
1359  *
1360  * This is a nontrivial decision since we can legally use any subset of the
1361  * given path set.  We want to choose a good tradeoff between selectivity
1362  * and cost of computing the bitmap.
1363  *
1364  * The result is either a single one of the inputs, or a BitmapAndPath
1365  * combining multiple inputs.
1366  */
1367 static Path *
choose_bitmap_and(PlannerInfo * root,RelOptInfo * rel,List * paths)1368 choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel, List *paths)
1369 {
1370 	int			npaths = list_length(paths);
1371 	PathClauseUsage **pathinfoarray;
1372 	PathClauseUsage *pathinfo;
1373 	List	   *clauselist;
1374 	List	   *bestpaths = NIL;
1375 	Cost		bestcost = 0;
1376 	int			i,
1377 				j;
1378 	ListCell   *l;
1379 
1380 	Assert(npaths > 0);			/* else caller error */
1381 	if (npaths == 1)
1382 		return (Path *) linitial(paths);	/* easy case */
1383 
1384 	/*
1385 	 * In theory we should consider every nonempty subset of the given paths.
1386 	 * In practice that seems like overkill, given the crude nature of the
1387 	 * estimates, not to mention the possible effects of higher-level AND and
1388 	 * OR clauses.  Moreover, it's completely impractical if there are a large
1389 	 * number of paths, since the work would grow as O(2^N).
1390 	 *
1391 	 * As a heuristic, we first check for paths using exactly the same sets of
1392 	 * WHERE clauses + index predicate conditions, and reject all but the
1393 	 * cheapest-to-scan in any such group.  This primarily gets rid of indexes
1394 	 * that include the interesting columns but also irrelevant columns.  (In
1395 	 * situations where the DBA has gone overboard on creating variant
1396 	 * indexes, this can make for a very large reduction in the number of
1397 	 * paths considered further.)
1398 	 *
1399 	 * We then sort the surviving paths with the cheapest-to-scan first, and
1400 	 * for each path, consider using that path alone as the basis for a bitmap
1401 	 * scan.  Then we consider bitmap AND scans formed from that path plus
1402 	 * each subsequent (higher-cost) path, adding on a subsequent path if it
1403 	 * results in a reduction in the estimated total scan cost. This means we
1404 	 * consider about O(N^2) rather than O(2^N) path combinations, which is
1405 	 * quite tolerable, especially given than N is usually reasonably small
1406 	 * because of the prefiltering step.  The cheapest of these is returned.
1407 	 *
1408 	 * We will only consider AND combinations in which no two indexes use the
1409 	 * same WHERE clause.  This is a bit of a kluge: it's needed because
1410 	 * costsize.c and clausesel.c aren't very smart about redundant clauses.
1411 	 * They will usually double-count the redundant clauses, producing a
1412 	 * too-small selectivity that makes a redundant AND step look like it
1413 	 * reduces the total cost.  Perhaps someday that code will be smarter and
1414 	 * we can remove this limitation.  (But note that this also defends
1415 	 * against flat-out duplicate input paths, which can happen because
1416 	 * match_join_clauses_to_index will find the same OR join clauses that
1417 	 * extract_restriction_or_clauses has pulled OR restriction clauses out
1418 	 * of.)
1419 	 *
1420 	 * For the same reason, we reject AND combinations in which an index
1421 	 * predicate clause duplicates another clause.  Here we find it necessary
1422 	 * to be even stricter: we'll reject a partial index if any of its
1423 	 * predicate clauses are implied by the set of WHERE clauses and predicate
1424 	 * clauses used so far.  This covers cases such as a condition "x = 42"
1425 	 * used with a plain index, followed by a clauseless scan of a partial
1426 	 * index "WHERE x >= 40 AND x < 50".  The partial index has been accepted
1427 	 * only because "x = 42" was present, and so allowing it would partially
1428 	 * double-count selectivity.  (We could use predicate_implied_by on
1429 	 * regular qual clauses too, to have a more intelligent, but much more
1430 	 * expensive, check for redundancy --- but in most cases simple equality
1431 	 * seems to suffice.)
1432 	 */
1433 
1434 	/*
1435 	 * Extract clause usage info and detect any paths that use exactly the
1436 	 * same set of clauses; keep only the cheapest-to-scan of any such groups.
1437 	 * The surviving paths are put into an array for qsort'ing.
1438 	 */
1439 	pathinfoarray = (PathClauseUsage **)
1440 		palloc(npaths * sizeof(PathClauseUsage *));
1441 	clauselist = NIL;
1442 	npaths = 0;
1443 	foreach(l, paths)
1444 	{
1445 		Path	   *ipath = (Path *) lfirst(l);
1446 
1447 		pathinfo = classify_index_clause_usage(ipath, &clauselist);
1448 
1449 		/* If it's unclassifiable, treat it as distinct from all others */
1450 		if (pathinfo->unclassifiable)
1451 		{
1452 			pathinfoarray[npaths++] = pathinfo;
1453 			continue;
1454 		}
1455 
1456 		for (i = 0; i < npaths; i++)
1457 		{
1458 			if (!pathinfoarray[i]->unclassifiable &&
1459 				bms_equal(pathinfo->clauseids, pathinfoarray[i]->clauseids))
1460 				break;
1461 		}
1462 		if (i < npaths)
1463 		{
1464 			/* duplicate clauseids, keep the cheaper one */
1465 			Cost		ncost;
1466 			Cost		ocost;
1467 			Selectivity nselec;
1468 			Selectivity oselec;
1469 
1470 			cost_bitmap_tree_node(pathinfo->path, &ncost, &nselec);
1471 			cost_bitmap_tree_node(pathinfoarray[i]->path, &ocost, &oselec);
1472 			if (ncost < ocost)
1473 				pathinfoarray[i] = pathinfo;
1474 		}
1475 		else
1476 		{
1477 			/* not duplicate clauseids, add to array */
1478 			pathinfoarray[npaths++] = pathinfo;
1479 		}
1480 	}
1481 
1482 	/* If only one surviving path, we're done */
1483 	if (npaths == 1)
1484 		return pathinfoarray[0]->path;
1485 
1486 	/* Sort the surviving paths by index access cost */
1487 	qsort(pathinfoarray, npaths, sizeof(PathClauseUsage *),
1488 		  path_usage_comparator);
1489 
1490 	/*
1491 	 * For each surviving index, consider it as an "AND group leader", and see
1492 	 * whether adding on any of the later indexes results in an AND path with
1493 	 * cheaper total cost than before.  Then take the cheapest AND group.
1494 	 *
1495 	 * Note: paths that are either clauseless or unclassifiable will have
1496 	 * empty clauseids, so that they will not be rejected by the clauseids
1497 	 * filter here, nor will they cause later paths to be rejected by it.
1498 	 */
1499 	for (i = 0; i < npaths; i++)
1500 	{
1501 		Cost		costsofar;
1502 		List	   *qualsofar;
1503 		Bitmapset  *clauseidsofar;
1504 
1505 		pathinfo = pathinfoarray[i];
1506 		paths = list_make1(pathinfo->path);
1507 		costsofar = bitmap_scan_cost_est(root, rel, pathinfo->path);
1508 		qualsofar = list_concat_copy(pathinfo->quals, pathinfo->preds);
1509 		clauseidsofar = bms_copy(pathinfo->clauseids);
1510 
1511 		for (j = i + 1; j < npaths; j++)
1512 		{
1513 			Cost		newcost;
1514 
1515 			pathinfo = pathinfoarray[j];
1516 			/* Check for redundancy */
1517 			if (bms_overlap(pathinfo->clauseids, clauseidsofar))
1518 				continue;		/* consider it redundant */
1519 			if (pathinfo->preds)
1520 			{
1521 				bool		redundant = false;
1522 
1523 				/* we check each predicate clause separately */
1524 				foreach(l, pathinfo->preds)
1525 				{
1526 					Node	   *np = (Node *) lfirst(l);
1527 
1528 					if (predicate_implied_by(list_make1(np), qualsofar, false))
1529 					{
1530 						redundant = true;
1531 						break;	/* out of inner foreach loop */
1532 					}
1533 				}
1534 				if (redundant)
1535 					continue;
1536 			}
1537 			/* tentatively add new path to paths, so we can estimate cost */
1538 			paths = lappend(paths, pathinfo->path);
1539 			newcost = bitmap_and_cost_est(root, rel, paths);
1540 			if (newcost < costsofar)
1541 			{
1542 				/* keep new path in paths, update subsidiary variables */
1543 				costsofar = newcost;
1544 				qualsofar = list_concat(qualsofar, pathinfo->quals);
1545 				qualsofar = list_concat(qualsofar, pathinfo->preds);
1546 				clauseidsofar = bms_add_members(clauseidsofar,
1547 												pathinfo->clauseids);
1548 			}
1549 			else
1550 			{
1551 				/* reject new path, remove it from paths list */
1552 				paths = list_truncate(paths, list_length(paths) - 1);
1553 			}
1554 		}
1555 
1556 		/* Keep the cheapest AND-group (or singleton) */
1557 		if (i == 0 || costsofar < bestcost)
1558 		{
1559 			bestpaths = paths;
1560 			bestcost = costsofar;
1561 		}
1562 
1563 		/* some easy cleanup (we don't try real hard though) */
1564 		list_free(qualsofar);
1565 	}
1566 
1567 	if (list_length(bestpaths) == 1)
1568 		return (Path *) linitial(bestpaths);	/* no need for AND */
1569 	return (Path *) create_bitmap_and_path(root, rel, bestpaths);
1570 }
1571 
1572 /* qsort comparator to sort in increasing index access cost order */
1573 static int
path_usage_comparator(const void * a,const void * b)1574 path_usage_comparator(const void *a, const void *b)
1575 {
1576 	PathClauseUsage *pa = *(PathClauseUsage *const *) a;
1577 	PathClauseUsage *pb = *(PathClauseUsage *const *) b;
1578 	Cost		acost;
1579 	Cost		bcost;
1580 	Selectivity aselec;
1581 	Selectivity bselec;
1582 
1583 	cost_bitmap_tree_node(pa->path, &acost, &aselec);
1584 	cost_bitmap_tree_node(pb->path, &bcost, &bselec);
1585 
1586 	/*
1587 	 * If costs are the same, sort by selectivity.
1588 	 */
1589 	if (acost < bcost)
1590 		return -1;
1591 	if (acost > bcost)
1592 		return 1;
1593 
1594 	if (aselec < bselec)
1595 		return -1;
1596 	if (aselec > bselec)
1597 		return 1;
1598 
1599 	return 0;
1600 }
1601 
1602 /*
1603  * Estimate the cost of actually executing a bitmap scan with a single
1604  * index path (which could be a BitmapAnd or BitmapOr node).
1605  */
1606 static Cost
bitmap_scan_cost_est(PlannerInfo * root,RelOptInfo * rel,Path * ipath)1607 bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel, Path *ipath)
1608 {
1609 	BitmapHeapPath bpath;
1610 
1611 	/* Set up a dummy BitmapHeapPath */
1612 	bpath.path.type = T_BitmapHeapPath;
1613 	bpath.path.pathtype = T_BitmapHeapScan;
1614 	bpath.path.parent = rel;
1615 	bpath.path.pathtarget = rel->reltarget;
1616 	bpath.path.param_info = ipath->param_info;
1617 	bpath.path.pathkeys = NIL;
1618 	bpath.bitmapqual = ipath;
1619 
1620 	/*
1621 	 * Check the cost of temporary path without considering parallelism.
1622 	 * Parallel bitmap heap path will be considered at later stage.
1623 	 */
1624 	bpath.path.parallel_workers = 0;
1625 
1626 	/* Now we can do cost_bitmap_heap_scan */
1627 	cost_bitmap_heap_scan(&bpath.path, root, rel,
1628 						  bpath.path.param_info,
1629 						  ipath,
1630 						  get_loop_count(root, rel->relid,
1631 										 PATH_REQ_OUTER(ipath)));
1632 
1633 	return bpath.path.total_cost;
1634 }
1635 
1636 /*
1637  * Estimate the cost of actually executing a BitmapAnd scan with the given
1638  * inputs.
1639  */
1640 static Cost
bitmap_and_cost_est(PlannerInfo * root,RelOptInfo * rel,List * paths)1641 bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel, List *paths)
1642 {
1643 	BitmapAndPath *apath;
1644 
1645 	/*
1646 	 * Might as well build a real BitmapAndPath here, as the work is slightly
1647 	 * too complicated to be worth repeating just to save one palloc.
1648 	 */
1649 	apath = create_bitmap_and_path(root, rel, paths);
1650 
1651 	return bitmap_scan_cost_est(root, rel, (Path *) apath);
1652 }
1653 
1654 
1655 /*
1656  * classify_index_clause_usage
1657  *		Construct a PathClauseUsage struct describing the WHERE clauses and
1658  *		index predicate clauses used by the given indexscan path.
1659  *		We consider two clauses the same if they are equal().
1660  *
1661  * At some point we might want to migrate this info into the Path data
1662  * structure proper, but for the moment it's only needed within
1663  * choose_bitmap_and().
1664  *
1665  * *clauselist is used and expanded as needed to identify all the distinct
1666  * clauses seen across successive calls.  Caller must initialize it to NIL
1667  * before first call of a set.
1668  */
1669 static PathClauseUsage *
classify_index_clause_usage(Path * path,List ** clauselist)1670 classify_index_clause_usage(Path *path, List **clauselist)
1671 {
1672 	PathClauseUsage *result;
1673 	Bitmapset  *clauseids;
1674 	ListCell   *lc;
1675 
1676 	result = (PathClauseUsage *) palloc(sizeof(PathClauseUsage));
1677 	result->path = path;
1678 
1679 	/* Recursively find the quals and preds used by the path */
1680 	result->quals = NIL;
1681 	result->preds = NIL;
1682 	find_indexpath_quals(path, &result->quals, &result->preds);
1683 
1684 	/*
1685 	 * Some machine-generated queries have outlandish numbers of qual clauses.
1686 	 * To avoid getting into O(N^2) behavior even in this preliminary
1687 	 * classification step, we want to limit the number of entries we can
1688 	 * accumulate in *clauselist.  Treat any path with more than 100 quals +
1689 	 * preds as unclassifiable, which will cause calling code to consider it
1690 	 * distinct from all other paths.
1691 	 */
1692 	if (list_length(result->quals) + list_length(result->preds) > 100)
1693 	{
1694 		result->clauseids = NULL;
1695 		result->unclassifiable = true;
1696 		return result;
1697 	}
1698 
1699 	/* Build up a bitmapset representing the quals and preds */
1700 	clauseids = NULL;
1701 	foreach(lc, result->quals)
1702 	{
1703 		Node	   *node = (Node *) lfirst(lc);
1704 
1705 		clauseids = bms_add_member(clauseids,
1706 								   find_list_position(node, clauselist));
1707 	}
1708 	foreach(lc, result->preds)
1709 	{
1710 		Node	   *node = (Node *) lfirst(lc);
1711 
1712 		clauseids = bms_add_member(clauseids,
1713 								   find_list_position(node, clauselist));
1714 	}
1715 	result->clauseids = clauseids;
1716 	result->unclassifiable = false;
1717 
1718 	return result;
1719 }
1720 
1721 
1722 /*
1723  * find_indexpath_quals
1724  *
1725  * Given the Path structure for a plain or bitmap indexscan, extract lists
1726  * of all the index clauses and index predicate conditions used in the Path.
1727  * These are appended to the initial contents of *quals and *preds (hence
1728  * caller should initialize those to NIL).
1729  *
1730  * Note we are not trying to produce an accurate representation of the AND/OR
1731  * semantics of the Path, but just find out all the base conditions used.
1732  *
1733  * The result lists contain pointers to the expressions used in the Path,
1734  * but all the list cells are freshly built, so it's safe to destructively
1735  * modify the lists (eg, by concat'ing with other lists).
1736  */
1737 static void
find_indexpath_quals(Path * bitmapqual,List ** quals,List ** preds)1738 find_indexpath_quals(Path *bitmapqual, List **quals, List **preds)
1739 {
1740 	if (IsA(bitmapqual, BitmapAndPath))
1741 	{
1742 		BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1743 		ListCell   *l;
1744 
1745 		foreach(l, apath->bitmapquals)
1746 		{
1747 			find_indexpath_quals((Path *) lfirst(l), quals, preds);
1748 		}
1749 	}
1750 	else if (IsA(bitmapqual, BitmapOrPath))
1751 	{
1752 		BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1753 		ListCell   *l;
1754 
1755 		foreach(l, opath->bitmapquals)
1756 		{
1757 			find_indexpath_quals((Path *) lfirst(l), quals, preds);
1758 		}
1759 	}
1760 	else if (IsA(bitmapqual, IndexPath))
1761 	{
1762 		IndexPath  *ipath = (IndexPath *) bitmapqual;
1763 		ListCell   *l;
1764 
1765 		foreach(l, ipath->indexclauses)
1766 		{
1767 			IndexClause *iclause = (IndexClause *) lfirst(l);
1768 
1769 			*quals = lappend(*quals, iclause->rinfo->clause);
1770 		}
1771 		*preds = list_concat(*preds, ipath->indexinfo->indpred);
1772 	}
1773 	else
1774 		elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1775 }
1776 
1777 
1778 /*
1779  * find_list_position
1780  *		Return the given node's position (counting from 0) in the given
1781  *		list of nodes.  If it's not equal() to any existing list member,
1782  *		add it at the end, and return that position.
1783  */
1784 static int
find_list_position(Node * node,List ** nodelist)1785 find_list_position(Node *node, List **nodelist)
1786 {
1787 	int			i;
1788 	ListCell   *lc;
1789 
1790 	i = 0;
1791 	foreach(lc, *nodelist)
1792 	{
1793 		Node	   *oldnode = (Node *) lfirst(lc);
1794 
1795 		if (equal(node, oldnode))
1796 			return i;
1797 		i++;
1798 	}
1799 
1800 	*nodelist = lappend(*nodelist, node);
1801 
1802 	return i;
1803 }
1804 
1805 
1806 /*
1807  * check_index_only
1808  *		Determine whether an index-only scan is possible for this index.
1809  */
1810 static bool
check_index_only(RelOptInfo * rel,IndexOptInfo * index)1811 check_index_only(RelOptInfo *rel, IndexOptInfo *index)
1812 {
1813 	bool		result;
1814 	Bitmapset  *attrs_used = NULL;
1815 	Bitmapset  *index_canreturn_attrs = NULL;
1816 	Bitmapset  *index_cannotreturn_attrs = NULL;
1817 	ListCell   *lc;
1818 	int			i;
1819 
1820 	/* Index-only scans must be enabled */
1821 	if (!enable_indexonlyscan)
1822 		return false;
1823 
1824 	/*
1825 	 * Check that all needed attributes of the relation are available from the
1826 	 * index.
1827 	 */
1828 
1829 	/*
1830 	 * First, identify all the attributes needed for joins or final output.
1831 	 * Note: we must look at rel's targetlist, not the attr_needed data,
1832 	 * because attr_needed isn't computed for inheritance child rels.
1833 	 */
1834 	pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
1835 
1836 	/*
1837 	 * Add all the attributes used by restriction clauses; but consider only
1838 	 * those clauses not implied by the index predicate, since ones that are
1839 	 * so implied don't need to be checked explicitly in the plan.
1840 	 *
1841 	 * Note: attributes used only in index quals would not be needed at
1842 	 * runtime either, if we are certain that the index is not lossy.  However
1843 	 * it'd be complicated to account for that accurately, and it doesn't
1844 	 * matter in most cases, since we'd conclude that such attributes are
1845 	 * available from the index anyway.
1846 	 */
1847 	foreach(lc, index->indrestrictinfo)
1848 	{
1849 		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1850 
1851 		pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
1852 	}
1853 
1854 	/*
1855 	 * Construct a bitmapset of columns that the index can return back in an
1856 	 * index-only scan.  If there are multiple index columns containing the
1857 	 * same attribute, all of them must be capable of returning the value,
1858 	 * since we might recheck operators on any of them.  (Potentially we could
1859 	 * be smarter about that, but it's such a weird situation that it doesn't
1860 	 * seem worth spending a lot of sweat on.)
1861 	 */
1862 	for (i = 0; i < index->ncolumns; i++)
1863 	{
1864 		int			attno = index->indexkeys[i];
1865 
1866 		/*
1867 		 * For the moment, we just ignore index expressions.  It might be nice
1868 		 * to do something with them, later.
1869 		 */
1870 		if (attno == 0)
1871 			continue;
1872 
1873 		if (index->canreturn[i])
1874 			index_canreturn_attrs =
1875 				bms_add_member(index_canreturn_attrs,
1876 							   attno - FirstLowInvalidHeapAttributeNumber);
1877 		else
1878 			index_cannotreturn_attrs =
1879 				bms_add_member(index_cannotreturn_attrs,
1880 							   attno - FirstLowInvalidHeapAttributeNumber);
1881 	}
1882 
1883 	index_canreturn_attrs = bms_del_members(index_canreturn_attrs,
1884 											index_cannotreturn_attrs);
1885 
1886 	/* Do we have all the necessary attributes? */
1887 	result = bms_is_subset(attrs_used, index_canreturn_attrs);
1888 
1889 	bms_free(attrs_used);
1890 	bms_free(index_canreturn_attrs);
1891 	bms_free(index_cannotreturn_attrs);
1892 
1893 	return result;
1894 }
1895 
1896 /*
1897  * get_loop_count
1898  *		Choose the loop count estimate to use for costing a parameterized path
1899  *		with the given set of outer relids.
1900  *
1901  * Since we produce parameterized paths before we've begun to generate join
1902  * relations, it's impossible to predict exactly how many times a parameterized
1903  * path will be iterated; we don't know the size of the relation that will be
1904  * on the outside of the nestloop.  However, we should try to account for
1905  * multiple iterations somehow in costing the path.  The heuristic embodied
1906  * here is to use the rowcount of the smallest other base relation needed in
1907  * the join clauses used by the path.  (We could alternatively consider the
1908  * largest one, but that seems too optimistic.)  This is of course the right
1909  * answer for single-other-relation cases, and it seems like a reasonable
1910  * zero-order approximation for multiway-join cases.
1911  *
1912  * In addition, we check to see if the other side of each join clause is on
1913  * the inside of some semijoin that the current relation is on the outside of.
1914  * If so, the only way that a parameterized path could be used is if the
1915  * semijoin RHS has been unique-ified, so we should use the number of unique
1916  * RHS rows rather than using the relation's raw rowcount.
1917  *
1918  * Note: for this to work, allpaths.c must establish all baserel size
1919  * estimates before it begins to compute paths, or at least before it
1920  * calls create_index_paths().
1921  */
1922 static double
get_loop_count(PlannerInfo * root,Index cur_relid,Relids outer_relids)1923 get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids)
1924 {
1925 	double		result;
1926 	int			outer_relid;
1927 
1928 	/* For a non-parameterized path, just return 1.0 quickly */
1929 	if (outer_relids == NULL)
1930 		return 1.0;
1931 
1932 	result = 0.0;
1933 	outer_relid = -1;
1934 	while ((outer_relid = bms_next_member(outer_relids, outer_relid)) >= 0)
1935 	{
1936 		RelOptInfo *outer_rel;
1937 		double		rowcount;
1938 
1939 		/* Paranoia: ignore bogus relid indexes */
1940 		if (outer_relid >= root->simple_rel_array_size)
1941 			continue;
1942 		outer_rel = root->simple_rel_array[outer_relid];
1943 		if (outer_rel == NULL)
1944 			continue;
1945 		Assert(outer_rel->relid == outer_relid);	/* sanity check on array */
1946 
1947 		/* Other relation could be proven empty, if so ignore */
1948 		if (IS_DUMMY_REL(outer_rel))
1949 			continue;
1950 
1951 		/* Otherwise, rel's rows estimate should be valid by now */
1952 		Assert(outer_rel->rows > 0);
1953 
1954 		/* Check to see if rel is on the inside of any semijoins */
1955 		rowcount = adjust_rowcount_for_semijoins(root,
1956 												 cur_relid,
1957 												 outer_relid,
1958 												 outer_rel->rows);
1959 
1960 		/* Remember smallest row count estimate among the outer rels */
1961 		if (result == 0.0 || result > rowcount)
1962 			result = rowcount;
1963 	}
1964 	/* Return 1.0 if we found no valid relations (shouldn't happen) */
1965 	return (result > 0.0) ? result : 1.0;
1966 }
1967 
1968 /*
1969  * Check to see if outer_relid is on the inside of any semijoin that cur_relid
1970  * is on the outside of.  If so, replace rowcount with the estimated number of
1971  * unique rows from the semijoin RHS (assuming that's smaller, which it might
1972  * not be).  The estimate is crude but it's the best we can do at this stage
1973  * of the proceedings.
1974  */
1975 static double
adjust_rowcount_for_semijoins(PlannerInfo * root,Index cur_relid,Index outer_relid,double rowcount)1976 adjust_rowcount_for_semijoins(PlannerInfo *root,
1977 							  Index cur_relid,
1978 							  Index outer_relid,
1979 							  double rowcount)
1980 {
1981 	ListCell   *lc;
1982 
1983 	foreach(lc, root->join_info_list)
1984 	{
1985 		SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
1986 
1987 		if (sjinfo->jointype == JOIN_SEMI &&
1988 			bms_is_member(cur_relid, sjinfo->syn_lefthand) &&
1989 			bms_is_member(outer_relid, sjinfo->syn_righthand))
1990 		{
1991 			/* Estimate number of unique-ified rows */
1992 			double		nraw;
1993 			double		nunique;
1994 
1995 			nraw = approximate_joinrel_size(root, sjinfo->syn_righthand);
1996 			nunique = estimate_num_groups(root,
1997 										  sjinfo->semi_rhs_exprs,
1998 										  nraw,
1999 										  NULL);
2000 			if (rowcount > nunique)
2001 				rowcount = nunique;
2002 		}
2003 	}
2004 	return rowcount;
2005 }
2006 
2007 /*
2008  * Make an approximate estimate of the size of a joinrel.
2009  *
2010  * We don't have enough info at this point to get a good estimate, so we
2011  * just multiply the base relation sizes together.  Fortunately, this is
2012  * the right answer anyway for the most common case with a single relation
2013  * on the RHS of a semijoin.  Also, estimate_num_groups() has only a weak
2014  * dependency on its input_rows argument (it basically uses it as a clamp).
2015  * So we might be able to get a fairly decent end result even with a severe
2016  * overestimate of the RHS's raw size.
2017  */
2018 static double
approximate_joinrel_size(PlannerInfo * root,Relids relids)2019 approximate_joinrel_size(PlannerInfo *root, Relids relids)
2020 {
2021 	double		rowcount = 1.0;
2022 	int			relid;
2023 
2024 	relid = -1;
2025 	while ((relid = bms_next_member(relids, relid)) >= 0)
2026 	{
2027 		RelOptInfo *rel;
2028 
2029 		/* Paranoia: ignore bogus relid indexes */
2030 		if (relid >= root->simple_rel_array_size)
2031 			continue;
2032 		rel = root->simple_rel_array[relid];
2033 		if (rel == NULL)
2034 			continue;
2035 		Assert(rel->relid == relid);	/* sanity check on array */
2036 
2037 		/* Relation could be proven empty, if so ignore */
2038 		if (IS_DUMMY_REL(rel))
2039 			continue;
2040 
2041 		/* Otherwise, rel's rows estimate should be valid by now */
2042 		Assert(rel->rows > 0);
2043 
2044 		/* Accumulate product */
2045 		rowcount *= rel->rows;
2046 	}
2047 	return rowcount;
2048 }
2049 
2050 
2051 /****************************************************************************
2052  *				----  ROUTINES TO CHECK QUERY CLAUSES  ----
2053  ****************************************************************************/
2054 
2055 /*
2056  * match_restriction_clauses_to_index
2057  *	  Identify restriction clauses for the rel that match the index.
2058  *	  Matching clauses are added to *clauseset.
2059  */
2060 static void
match_restriction_clauses_to_index(PlannerInfo * root,IndexOptInfo * index,IndexClauseSet * clauseset)2061 match_restriction_clauses_to_index(PlannerInfo *root,
2062 								   IndexOptInfo *index,
2063 								   IndexClauseSet *clauseset)
2064 {
2065 	/* We can ignore clauses that are implied by the index predicate */
2066 	match_clauses_to_index(root, index->indrestrictinfo, index, clauseset);
2067 }
2068 
2069 /*
2070  * match_join_clauses_to_index
2071  *	  Identify join clauses for the rel that match the index.
2072  *	  Matching clauses are added to *clauseset.
2073  *	  Also, add any potentially usable join OR clauses to *joinorclauses.
2074  */
2075 static void
match_join_clauses_to_index(PlannerInfo * root,RelOptInfo * rel,IndexOptInfo * index,IndexClauseSet * clauseset,List ** joinorclauses)2076 match_join_clauses_to_index(PlannerInfo *root,
2077 							RelOptInfo *rel, IndexOptInfo *index,
2078 							IndexClauseSet *clauseset,
2079 							List **joinorclauses)
2080 {
2081 	ListCell   *lc;
2082 
2083 	/* Scan the rel's join clauses */
2084 	foreach(lc, rel->joininfo)
2085 	{
2086 		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2087 
2088 		/* Check if clause can be moved to this rel */
2089 		if (!join_clause_is_movable_to(rinfo, rel))
2090 			continue;
2091 
2092 		/* Potentially usable, so see if it matches the index or is an OR */
2093 		if (restriction_is_or_clause(rinfo))
2094 			*joinorclauses = lappend(*joinorclauses, rinfo);
2095 		else
2096 			match_clause_to_index(root, rinfo, index, clauseset);
2097 	}
2098 }
2099 
2100 /*
2101  * match_eclass_clauses_to_index
2102  *	  Identify EquivalenceClass join clauses for the rel that match the index.
2103  *	  Matching clauses are added to *clauseset.
2104  */
2105 static void
match_eclass_clauses_to_index(PlannerInfo * root,IndexOptInfo * index,IndexClauseSet * clauseset)2106 match_eclass_clauses_to_index(PlannerInfo *root, IndexOptInfo *index,
2107 							  IndexClauseSet *clauseset)
2108 {
2109 	int			indexcol;
2110 
2111 	/* No work if rel is not in any such ECs */
2112 	if (!index->rel->has_eclass_joins)
2113 		return;
2114 
2115 	for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2116 	{
2117 		ec_member_matches_arg arg;
2118 		List	   *clauses;
2119 
2120 		/* Generate clauses, skipping any that join to lateral_referencers */
2121 		arg.index = index;
2122 		arg.indexcol = indexcol;
2123 		clauses = generate_implied_equalities_for_column(root,
2124 														 index->rel,
2125 														 ec_member_matches_indexcol,
2126 														 (void *) &arg,
2127 														 index->rel->lateral_referencers);
2128 
2129 		/*
2130 		 * We have to check whether the results actually do match the index,
2131 		 * since for non-btree indexes the EC's equality operators might not
2132 		 * be in the index opclass (cf ec_member_matches_indexcol).
2133 		 */
2134 		match_clauses_to_index(root, clauses, index, clauseset);
2135 	}
2136 }
2137 
2138 /*
2139  * match_clauses_to_index
2140  *	  Perform match_clause_to_index() for each clause in a list.
2141  *	  Matching clauses are added to *clauseset.
2142  */
2143 static void
match_clauses_to_index(PlannerInfo * root,List * clauses,IndexOptInfo * index,IndexClauseSet * clauseset)2144 match_clauses_to_index(PlannerInfo *root,
2145 					   List *clauses,
2146 					   IndexOptInfo *index,
2147 					   IndexClauseSet *clauseset)
2148 {
2149 	ListCell   *lc;
2150 
2151 	foreach(lc, clauses)
2152 	{
2153 		RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
2154 
2155 		match_clause_to_index(root, rinfo, index, clauseset);
2156 	}
2157 }
2158 
2159 /*
2160  * match_clause_to_index
2161  *	  Test whether a qual clause can be used with an index.
2162  *
2163  * If the clause is usable, add an IndexClause entry for it to the appropriate
2164  * list in *clauseset.  (*clauseset must be initialized to zeroes before first
2165  * call.)
2166  *
2167  * Note: in some circumstances we may find the same RestrictInfos coming from
2168  * multiple places.  Defend against redundant outputs by refusing to add a
2169  * clause twice (pointer equality should be a good enough check for this).
2170  *
2171  * Note: it's possible that a badly-defined index could have multiple matching
2172  * columns.  We always select the first match if so; this avoids scenarios
2173  * wherein we get an inflated idea of the index's selectivity by using the
2174  * same clause multiple times with different index columns.
2175  */
2176 static void
match_clause_to_index(PlannerInfo * root,RestrictInfo * rinfo,IndexOptInfo * index,IndexClauseSet * clauseset)2177 match_clause_to_index(PlannerInfo *root,
2178 					  RestrictInfo *rinfo,
2179 					  IndexOptInfo *index,
2180 					  IndexClauseSet *clauseset)
2181 {
2182 	int			indexcol;
2183 
2184 	/*
2185 	 * Never match pseudoconstants to indexes.  (Normally a match could not
2186 	 * happen anyway, since a pseudoconstant clause couldn't contain a Var,
2187 	 * but what if someone builds an expression index on a constant? It's not
2188 	 * totally unreasonable to do so with a partial index, either.)
2189 	 */
2190 	if (rinfo->pseudoconstant)
2191 		return;
2192 
2193 	/*
2194 	 * If clause can't be used as an indexqual because it must wait till after
2195 	 * some lower-security-level restriction clause, reject it.
2196 	 */
2197 	if (!restriction_is_securely_promotable(rinfo, index->rel))
2198 		return;
2199 
2200 	/* OK, check each index key column for a match */
2201 	for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2202 	{
2203 		IndexClause *iclause;
2204 		ListCell   *lc;
2205 
2206 		/* Ignore duplicates */
2207 		foreach(lc, clauseset->indexclauses[indexcol])
2208 		{
2209 			IndexClause *iclause = (IndexClause *) lfirst(lc);
2210 
2211 			if (iclause->rinfo == rinfo)
2212 				return;
2213 		}
2214 
2215 		/* OK, try to match the clause to the index column */
2216 		iclause = match_clause_to_indexcol(root,
2217 										   rinfo,
2218 										   indexcol,
2219 										   index);
2220 		if (iclause)
2221 		{
2222 			/* Success, so record it */
2223 			clauseset->indexclauses[indexcol] =
2224 				lappend(clauseset->indexclauses[indexcol], iclause);
2225 			clauseset->nonempty = true;
2226 			return;
2227 		}
2228 	}
2229 }
2230 
2231 /*
2232  * match_clause_to_indexcol()
2233  *	  Determine whether a restriction clause matches a column of an index,
2234  *	  and if so, build an IndexClause node describing the details.
2235  *
2236  *	  To match an index normally, an operator clause:
2237  *
2238  *	  (1)  must be in the form (indexkey op const) or (const op indexkey);
2239  *		   and
2240  *	  (2)  must contain an operator which is in the index's operator family
2241  *		   for this column; and
2242  *	  (3)  must match the collation of the index, if collation is relevant.
2243  *
2244  *	  Our definition of "const" is exceedingly liberal: we allow anything that
2245  *	  doesn't involve a volatile function or a Var of the index's relation.
2246  *	  In particular, Vars belonging to other relations of the query are
2247  *	  accepted here, since a clause of that form can be used in a
2248  *	  parameterized indexscan.  It's the responsibility of higher code levels
2249  *	  to manage restriction and join clauses appropriately.
2250  *
2251  *	  Note: we do need to check for Vars of the index's relation on the
2252  *	  "const" side of the clause, since clauses like (a.f1 OP (b.f2 OP a.f3))
2253  *	  are not processable by a parameterized indexscan on a.f1, whereas
2254  *	  something like (a.f1 OP (b.f2 OP c.f3)) is.
2255  *
2256  *	  Presently, the executor can only deal with indexquals that have the
2257  *	  indexkey on the left, so we can only use clauses that have the indexkey
2258  *	  on the right if we can commute the clause to put the key on the left.
2259  *	  We handle that by generating an IndexClause with the correctly-commuted
2260  *	  opclause as a derived indexqual.
2261  *
2262  *	  If the index has a collation, the clause must have the same collation.
2263  *	  For collation-less indexes, we assume it doesn't matter; this is
2264  *	  necessary for cases like "hstore ? text", wherein hstore's operators
2265  *	  don't care about collation but the clause will get marked with a
2266  *	  collation anyway because of the text argument.  (This logic is
2267  *	  embodied in the macro IndexCollMatchesExprColl.)
2268  *
2269  *	  It is also possible to match RowCompareExpr clauses to indexes (but
2270  *	  currently, only btree indexes handle this).
2271  *
2272  *	  It is also possible to match ScalarArrayOpExpr clauses to indexes, when
2273  *	  the clause is of the form "indexkey op ANY (arrayconst)".
2274  *
2275  *	  For boolean indexes, it is also possible to match the clause directly
2276  *	  to the indexkey; or perhaps the clause is (NOT indexkey).
2277  *
2278  *	  And, last but not least, some operators and functions can be processed
2279  *	  to derive (typically lossy) indexquals from a clause that isn't in
2280  *	  itself indexable.  If we see that any operand of an OpExpr or FuncExpr
2281  *	  matches the index key, and the function has a planner support function
2282  *	  attached to it, we'll invoke the support function to see if such an
2283  *	  indexqual can be built.
2284  *
2285  * 'rinfo' is the clause to be tested (as a RestrictInfo node).
2286  * 'indexcol' is a column number of 'index' (counting from 0).
2287  * 'index' is the index of interest.
2288  *
2289  * Returns an IndexClause if the clause can be used with this index key,
2290  * or NULL if not.
2291  *
2292  * NOTE:  returns NULL if clause is an OR or AND clause; it is the
2293  * responsibility of higher-level routines to cope with those.
2294  */
2295 static IndexClause *
match_clause_to_indexcol(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index)2296 match_clause_to_indexcol(PlannerInfo *root,
2297 						 RestrictInfo *rinfo,
2298 						 int indexcol,
2299 						 IndexOptInfo *index)
2300 {
2301 	IndexClause *iclause;
2302 	Expr	   *clause = rinfo->clause;
2303 	Oid			opfamily;
2304 
2305 	Assert(indexcol < index->nkeycolumns);
2306 
2307 	/*
2308 	 * Historically this code has coped with NULL clauses.  That's probably
2309 	 * not possible anymore, but we might as well continue to cope.
2310 	 */
2311 	if (clause == NULL)
2312 		return NULL;
2313 
2314 	/* First check for boolean-index cases. */
2315 	opfamily = index->opfamily[indexcol];
2316 	if (IsBooleanOpfamily(opfamily))
2317 	{
2318 		iclause = match_boolean_index_clause(root, rinfo, indexcol, index);
2319 		if (iclause)
2320 			return iclause;
2321 	}
2322 
2323 	/*
2324 	 * Clause must be an opclause, funcclause, ScalarArrayOpExpr, or
2325 	 * RowCompareExpr.  Or, if the index supports it, we can handle IS
2326 	 * NULL/NOT NULL clauses.
2327 	 */
2328 	if (IsA(clause, OpExpr))
2329 	{
2330 		return match_opclause_to_indexcol(root, rinfo, indexcol, index);
2331 	}
2332 	else if (IsA(clause, FuncExpr))
2333 	{
2334 		return match_funcclause_to_indexcol(root, rinfo, indexcol, index);
2335 	}
2336 	else if (IsA(clause, ScalarArrayOpExpr))
2337 	{
2338 		return match_saopclause_to_indexcol(root, rinfo, indexcol, index);
2339 	}
2340 	else if (IsA(clause, RowCompareExpr))
2341 	{
2342 		return match_rowcompare_to_indexcol(root, rinfo, indexcol, index);
2343 	}
2344 	else if (index->amsearchnulls && IsA(clause, NullTest))
2345 	{
2346 		NullTest   *nt = (NullTest *) clause;
2347 
2348 		if (!nt->argisrow &&
2349 			match_index_to_operand((Node *) nt->arg, indexcol, index))
2350 		{
2351 			iclause = makeNode(IndexClause);
2352 			iclause->rinfo = rinfo;
2353 			iclause->indexquals = list_make1(rinfo);
2354 			iclause->lossy = false;
2355 			iclause->indexcol = indexcol;
2356 			iclause->indexcols = NIL;
2357 			return iclause;
2358 		}
2359 	}
2360 
2361 	return NULL;
2362 }
2363 
2364 /*
2365  * match_boolean_index_clause
2366  *	  Recognize restriction clauses that can be matched to a boolean index.
2367  *
2368  * The idea here is that, for an index on a boolean column that supports the
2369  * BooleanEqualOperator, we can transform a plain reference to the indexkey
2370  * into "indexkey = true", or "NOT indexkey" into "indexkey = false", etc,
2371  * so as to make the expression indexable using the index's "=" operator.
2372  * Since Postgres 8.1, we must do this because constant simplification does
2373  * the reverse transformation; without this code there'd be no way to use
2374  * such an index at all.
2375  *
2376  * This should be called only when IsBooleanOpfamily() recognizes the
2377  * index's operator family.  We check to see if the clause matches the
2378  * index's key, and if so, build a suitable IndexClause.
2379  */
2380 static IndexClause *
match_boolean_index_clause(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index)2381 match_boolean_index_clause(PlannerInfo *root,
2382 						   RestrictInfo *rinfo,
2383 						   int indexcol,
2384 						   IndexOptInfo *index)
2385 {
2386 	Node	   *clause = (Node *) rinfo->clause;
2387 	Expr	   *op = NULL;
2388 
2389 	/* Direct match? */
2390 	if (match_index_to_operand(clause, indexcol, index))
2391 	{
2392 		/* convert to indexkey = TRUE */
2393 		op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2394 						   (Expr *) clause,
2395 						   (Expr *) makeBoolConst(true, false),
2396 						   InvalidOid, InvalidOid);
2397 	}
2398 	/* NOT clause? */
2399 	else if (is_notclause(clause))
2400 	{
2401 		Node	   *arg = (Node *) get_notclausearg((Expr *) clause);
2402 
2403 		if (match_index_to_operand(arg, indexcol, index))
2404 		{
2405 			/* convert to indexkey = FALSE */
2406 			op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2407 							   (Expr *) arg,
2408 							   (Expr *) makeBoolConst(false, false),
2409 							   InvalidOid, InvalidOid);
2410 		}
2411 	}
2412 
2413 	/*
2414 	 * Since we only consider clauses at top level of WHERE, we can convert
2415 	 * indexkey IS TRUE and indexkey IS FALSE to index searches as well.  The
2416 	 * different meaning for NULL isn't important.
2417 	 */
2418 	else if (clause && IsA(clause, BooleanTest))
2419 	{
2420 		BooleanTest *btest = (BooleanTest *) clause;
2421 		Node	   *arg = (Node *) btest->arg;
2422 
2423 		if (btest->booltesttype == IS_TRUE &&
2424 			match_index_to_operand(arg, indexcol, index))
2425 		{
2426 			/* convert to indexkey = TRUE */
2427 			op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2428 							   (Expr *) arg,
2429 							   (Expr *) makeBoolConst(true, false),
2430 							   InvalidOid, InvalidOid);
2431 		}
2432 		else if (btest->booltesttype == IS_FALSE &&
2433 				 match_index_to_operand(arg, indexcol, index))
2434 		{
2435 			/* convert to indexkey = FALSE */
2436 			op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2437 							   (Expr *) arg,
2438 							   (Expr *) makeBoolConst(false, false),
2439 							   InvalidOid, InvalidOid);
2440 		}
2441 	}
2442 
2443 	/*
2444 	 * If we successfully made an operator clause from the given qual, we must
2445 	 * wrap it in an IndexClause.  It's not lossy.
2446 	 */
2447 	if (op)
2448 	{
2449 		IndexClause *iclause = makeNode(IndexClause);
2450 
2451 		iclause->rinfo = rinfo;
2452 		iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
2453 		iclause->lossy = false;
2454 		iclause->indexcol = indexcol;
2455 		iclause->indexcols = NIL;
2456 		return iclause;
2457 	}
2458 
2459 	return NULL;
2460 }
2461 
2462 /*
2463  * match_opclause_to_indexcol()
2464  *	  Handles the OpExpr case for match_clause_to_indexcol(),
2465  *	  which see for comments.
2466  */
2467 static IndexClause *
match_opclause_to_indexcol(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index)2468 match_opclause_to_indexcol(PlannerInfo *root,
2469 						   RestrictInfo *rinfo,
2470 						   int indexcol,
2471 						   IndexOptInfo *index)
2472 {
2473 	IndexClause *iclause;
2474 	OpExpr	   *clause = (OpExpr *) rinfo->clause;
2475 	Node	   *leftop,
2476 			   *rightop;
2477 	Oid			expr_op;
2478 	Oid			expr_coll;
2479 	Index		index_relid;
2480 	Oid			opfamily;
2481 	Oid			idxcollation;
2482 
2483 	/*
2484 	 * Only binary operators need apply.  (In theory, a planner support
2485 	 * function could do something with a unary operator, but it seems
2486 	 * unlikely to be worth the cycles to check.)
2487 	 */
2488 	if (list_length(clause->args) != 2)
2489 		return NULL;
2490 
2491 	leftop = (Node *) linitial(clause->args);
2492 	rightop = (Node *) lsecond(clause->args);
2493 	expr_op = clause->opno;
2494 	expr_coll = clause->inputcollid;
2495 
2496 	index_relid = index->rel->relid;
2497 	opfamily = index->opfamily[indexcol];
2498 	idxcollation = index->indexcollations[indexcol];
2499 
2500 	/*
2501 	 * Check for clauses of the form: (indexkey operator constant) or
2502 	 * (constant operator indexkey).  See match_clause_to_indexcol's notes
2503 	 * about const-ness.
2504 	 *
2505 	 * Note that we don't ask the support function about clauses that don't
2506 	 * have one of these forms.  Again, in principle it might be possible to
2507 	 * do something, but it seems unlikely to be worth the cycles to check.
2508 	 */
2509 	if (match_index_to_operand(leftop, indexcol, index) &&
2510 		!bms_is_member(index_relid, rinfo->right_relids) &&
2511 		!contain_volatile_functions(rightop))
2512 	{
2513 		if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
2514 			op_in_opfamily(expr_op, opfamily))
2515 		{
2516 			iclause = makeNode(IndexClause);
2517 			iclause->rinfo = rinfo;
2518 			iclause->indexquals = list_make1(rinfo);
2519 			iclause->lossy = false;
2520 			iclause->indexcol = indexcol;
2521 			iclause->indexcols = NIL;
2522 			return iclause;
2523 		}
2524 
2525 		/*
2526 		 * If we didn't find a member of the index's opfamily, try the support
2527 		 * function for the operator's underlying function.
2528 		 */
2529 		set_opfuncid(clause);	/* make sure we have opfuncid */
2530 		return get_index_clause_from_support(root,
2531 											 rinfo,
2532 											 clause->opfuncid,
2533 											 0, /* indexarg on left */
2534 											 indexcol,
2535 											 index);
2536 	}
2537 
2538 	if (match_index_to_operand(rightop, indexcol, index) &&
2539 		!bms_is_member(index_relid, rinfo->left_relids) &&
2540 		!contain_volatile_functions(leftop))
2541 	{
2542 		if (IndexCollMatchesExprColl(idxcollation, expr_coll))
2543 		{
2544 			Oid			comm_op = get_commutator(expr_op);
2545 
2546 			if (OidIsValid(comm_op) &&
2547 				op_in_opfamily(comm_op, opfamily))
2548 			{
2549 				RestrictInfo *commrinfo;
2550 
2551 				/* Build a commuted OpExpr and RestrictInfo */
2552 				commrinfo = commute_restrictinfo(rinfo, comm_op);
2553 
2554 				/* Make an IndexClause showing that as a derived qual */
2555 				iclause = makeNode(IndexClause);
2556 				iclause->rinfo = rinfo;
2557 				iclause->indexquals = list_make1(commrinfo);
2558 				iclause->lossy = false;
2559 				iclause->indexcol = indexcol;
2560 				iclause->indexcols = NIL;
2561 				return iclause;
2562 			}
2563 		}
2564 
2565 		/*
2566 		 * If we didn't find a member of the index's opfamily, try the support
2567 		 * function for the operator's underlying function.
2568 		 */
2569 		set_opfuncid(clause);	/* make sure we have opfuncid */
2570 		return get_index_clause_from_support(root,
2571 											 rinfo,
2572 											 clause->opfuncid,
2573 											 1, /* indexarg on right */
2574 											 indexcol,
2575 											 index);
2576 	}
2577 
2578 	return NULL;
2579 }
2580 
2581 /*
2582  * match_funcclause_to_indexcol()
2583  *	  Handles the FuncExpr case for match_clause_to_indexcol(),
2584  *	  which see for comments.
2585  */
2586 static IndexClause *
match_funcclause_to_indexcol(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index)2587 match_funcclause_to_indexcol(PlannerInfo *root,
2588 							 RestrictInfo *rinfo,
2589 							 int indexcol,
2590 							 IndexOptInfo *index)
2591 {
2592 	FuncExpr   *clause = (FuncExpr *) rinfo->clause;
2593 	int			indexarg;
2594 	ListCell   *lc;
2595 
2596 	/*
2597 	 * We have no built-in intelligence about function clauses, but if there's
2598 	 * a planner support function, it might be able to do something.  But, to
2599 	 * cut down on wasted planning cycles, only call the support function if
2600 	 * at least one argument matches the target index column.
2601 	 *
2602 	 * Note that we don't insist on the other arguments being pseudoconstants;
2603 	 * the support function has to check that.  This is to allow cases where
2604 	 * only some of the other arguments need to be included in the indexqual.
2605 	 */
2606 	indexarg = 0;
2607 	foreach(lc, clause->args)
2608 	{
2609 		Node	   *op = (Node *) lfirst(lc);
2610 
2611 		if (match_index_to_operand(op, indexcol, index))
2612 		{
2613 			return get_index_clause_from_support(root,
2614 												 rinfo,
2615 												 clause->funcid,
2616 												 indexarg,
2617 												 indexcol,
2618 												 index);
2619 		}
2620 
2621 		indexarg++;
2622 	}
2623 
2624 	return NULL;
2625 }
2626 
2627 /*
2628  * get_index_clause_from_support()
2629  *		If the function has a planner support function, try to construct
2630  *		an IndexClause using indexquals created by the support function.
2631  */
2632 static IndexClause *
get_index_clause_from_support(PlannerInfo * root,RestrictInfo * rinfo,Oid funcid,int indexarg,int indexcol,IndexOptInfo * index)2633 get_index_clause_from_support(PlannerInfo *root,
2634 							  RestrictInfo *rinfo,
2635 							  Oid funcid,
2636 							  int indexarg,
2637 							  int indexcol,
2638 							  IndexOptInfo *index)
2639 {
2640 	Oid			prosupport = get_func_support(funcid);
2641 	SupportRequestIndexCondition req;
2642 	List	   *sresult;
2643 
2644 	if (!OidIsValid(prosupport))
2645 		return NULL;
2646 
2647 	req.type = T_SupportRequestIndexCondition;
2648 	req.root = root;
2649 	req.funcid = funcid;
2650 	req.node = (Node *) rinfo->clause;
2651 	req.indexarg = indexarg;
2652 	req.index = index;
2653 	req.indexcol = indexcol;
2654 	req.opfamily = index->opfamily[indexcol];
2655 	req.indexcollation = index->indexcollations[indexcol];
2656 
2657 	req.lossy = true;			/* default assumption */
2658 
2659 	sresult = (List *)
2660 		DatumGetPointer(OidFunctionCall1(prosupport,
2661 										 PointerGetDatum(&req)));
2662 
2663 	if (sresult != NIL)
2664 	{
2665 		IndexClause *iclause = makeNode(IndexClause);
2666 		List	   *indexquals = NIL;
2667 		ListCell   *lc;
2668 
2669 		/*
2670 		 * The support function API says it should just give back bare
2671 		 * clauses, so here we must wrap each one in a RestrictInfo.
2672 		 */
2673 		foreach(lc, sresult)
2674 		{
2675 			Expr	   *clause = (Expr *) lfirst(lc);
2676 
2677 			indexquals = lappend(indexquals,
2678 								 make_simple_restrictinfo(root, clause));
2679 		}
2680 
2681 		iclause->rinfo = rinfo;
2682 		iclause->indexquals = indexquals;
2683 		iclause->lossy = req.lossy;
2684 		iclause->indexcol = indexcol;
2685 		iclause->indexcols = NIL;
2686 
2687 		return iclause;
2688 	}
2689 
2690 	return NULL;
2691 }
2692 
2693 /*
2694  * match_saopclause_to_indexcol()
2695  *	  Handles the ScalarArrayOpExpr case for match_clause_to_indexcol(),
2696  *	  which see for comments.
2697  */
2698 static IndexClause *
match_saopclause_to_indexcol(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index)2699 match_saopclause_to_indexcol(PlannerInfo *root,
2700 							 RestrictInfo *rinfo,
2701 							 int indexcol,
2702 							 IndexOptInfo *index)
2703 {
2704 	ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
2705 	Node	   *leftop,
2706 			   *rightop;
2707 	Relids		right_relids;
2708 	Oid			expr_op;
2709 	Oid			expr_coll;
2710 	Index		index_relid;
2711 	Oid			opfamily;
2712 	Oid			idxcollation;
2713 
2714 	/* We only accept ANY clauses, not ALL */
2715 	if (!saop->useOr)
2716 		return NULL;
2717 	leftop = (Node *) linitial(saop->args);
2718 	rightop = (Node *) lsecond(saop->args);
2719 	right_relids = pull_varnos(root, rightop);
2720 	expr_op = saop->opno;
2721 	expr_coll = saop->inputcollid;
2722 
2723 	index_relid = index->rel->relid;
2724 	opfamily = index->opfamily[indexcol];
2725 	idxcollation = index->indexcollations[indexcol];
2726 
2727 	/*
2728 	 * We must have indexkey on the left and a pseudo-constant array argument.
2729 	 */
2730 	if (match_index_to_operand(leftop, indexcol, index) &&
2731 		!bms_is_member(index_relid, right_relids) &&
2732 		!contain_volatile_functions(rightop))
2733 	{
2734 		if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
2735 			op_in_opfamily(expr_op, opfamily))
2736 		{
2737 			IndexClause *iclause = makeNode(IndexClause);
2738 
2739 			iclause->rinfo = rinfo;
2740 			iclause->indexquals = list_make1(rinfo);
2741 			iclause->lossy = false;
2742 			iclause->indexcol = indexcol;
2743 			iclause->indexcols = NIL;
2744 			return iclause;
2745 		}
2746 
2747 		/*
2748 		 * We do not currently ask support functions about ScalarArrayOpExprs,
2749 		 * though in principle we could.
2750 		 */
2751 	}
2752 
2753 	return NULL;
2754 }
2755 
2756 /*
2757  * match_rowcompare_to_indexcol()
2758  *	  Handles the RowCompareExpr case for match_clause_to_indexcol(),
2759  *	  which see for comments.
2760  *
2761  * In this routine we check whether the first column of the row comparison
2762  * matches the target index column.  This is sufficient to guarantee that some
2763  * index condition can be constructed from the RowCompareExpr --- the rest
2764  * is handled by expand_indexqual_rowcompare().
2765  */
2766 static IndexClause *
match_rowcompare_to_indexcol(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index)2767 match_rowcompare_to_indexcol(PlannerInfo *root,
2768 							 RestrictInfo *rinfo,
2769 							 int indexcol,
2770 							 IndexOptInfo *index)
2771 {
2772 	RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
2773 	Index		index_relid;
2774 	Oid			opfamily;
2775 	Oid			idxcollation;
2776 	Node	   *leftop,
2777 			   *rightop;
2778 	bool		var_on_left;
2779 	Oid			expr_op;
2780 	Oid			expr_coll;
2781 
2782 	/* Forget it if we're not dealing with a btree index */
2783 	if (index->relam != BTREE_AM_OID)
2784 		return NULL;
2785 
2786 	index_relid = index->rel->relid;
2787 	opfamily = index->opfamily[indexcol];
2788 	idxcollation = index->indexcollations[indexcol];
2789 
2790 	/*
2791 	 * We could do the matching on the basis of insisting that the opfamily
2792 	 * shown in the RowCompareExpr be the same as the index column's opfamily,
2793 	 * but that could fail in the presence of reverse-sort opfamilies: it'd be
2794 	 * a matter of chance whether RowCompareExpr had picked the forward or
2795 	 * reverse-sort family.  So look only at the operator, and match if it is
2796 	 * a member of the index's opfamily (after commutation, if the indexkey is
2797 	 * on the right).  We'll worry later about whether any additional
2798 	 * operators are matchable to the index.
2799 	 */
2800 	leftop = (Node *) linitial(clause->largs);
2801 	rightop = (Node *) linitial(clause->rargs);
2802 	expr_op = linitial_oid(clause->opnos);
2803 	expr_coll = linitial_oid(clause->inputcollids);
2804 
2805 	/* Collations must match, if relevant */
2806 	if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
2807 		return NULL;
2808 
2809 	/*
2810 	 * These syntactic tests are the same as in match_opclause_to_indexcol()
2811 	 */
2812 	if (match_index_to_operand(leftop, indexcol, index) &&
2813 		!bms_is_member(index_relid, pull_varnos(root, rightop)) &&
2814 		!contain_volatile_functions(rightop))
2815 	{
2816 		/* OK, indexkey is on left */
2817 		var_on_left = true;
2818 	}
2819 	else if (match_index_to_operand(rightop, indexcol, index) &&
2820 			 !bms_is_member(index_relid, pull_varnos(root, leftop)) &&
2821 			 !contain_volatile_functions(leftop))
2822 	{
2823 		/* indexkey is on right, so commute the operator */
2824 		expr_op = get_commutator(expr_op);
2825 		if (expr_op == InvalidOid)
2826 			return NULL;
2827 		var_on_left = false;
2828 	}
2829 	else
2830 		return NULL;
2831 
2832 	/* We're good if the operator is the right type of opfamily member */
2833 	switch (get_op_opfamily_strategy(expr_op, opfamily))
2834 	{
2835 		case BTLessStrategyNumber:
2836 		case BTLessEqualStrategyNumber:
2837 		case BTGreaterEqualStrategyNumber:
2838 		case BTGreaterStrategyNumber:
2839 			return expand_indexqual_rowcompare(root,
2840 											   rinfo,
2841 											   indexcol,
2842 											   index,
2843 											   expr_op,
2844 											   var_on_left);
2845 	}
2846 
2847 	return NULL;
2848 }
2849 
2850 /*
2851  * expand_indexqual_rowcompare --- expand a single indexqual condition
2852  *		that is a RowCompareExpr
2853  *
2854  * It's already known that the first column of the row comparison matches
2855  * the specified column of the index.  We can use additional columns of the
2856  * row comparison as index qualifications, so long as they match the index
2857  * in the "same direction", ie, the indexkeys are all on the same side of the
2858  * clause and the operators are all the same-type members of the opfamilies.
2859  *
2860  * If all the columns of the RowCompareExpr match in this way, we just use it
2861  * as-is, except for possibly commuting it to put the indexkeys on the left.
2862  *
2863  * Otherwise, we build a shortened RowCompareExpr (if more than one
2864  * column matches) or a simple OpExpr (if the first-column match is all
2865  * there is).  In these cases the modified clause is always "<=" or ">="
2866  * even when the original was "<" or ">" --- this is necessary to match all
2867  * the rows that could match the original.  (We are building a lossy version
2868  * of the row comparison when we do this, so we set lossy = true.)
2869  *
2870  * Note: this is really just the last half of match_rowcompare_to_indexcol,
2871  * but we split it out for comprehensibility.
2872  */
2873 static IndexClause *
expand_indexqual_rowcompare(PlannerInfo * root,RestrictInfo * rinfo,int indexcol,IndexOptInfo * index,Oid expr_op,bool var_on_left)2874 expand_indexqual_rowcompare(PlannerInfo *root,
2875 							RestrictInfo *rinfo,
2876 							int indexcol,
2877 							IndexOptInfo *index,
2878 							Oid expr_op,
2879 							bool var_on_left)
2880 {
2881 	IndexClause *iclause = makeNode(IndexClause);
2882 	RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
2883 	int			op_strategy;
2884 	Oid			op_lefttype;
2885 	Oid			op_righttype;
2886 	int			matching_cols;
2887 	List	   *expr_ops;
2888 	List	   *opfamilies;
2889 	List	   *lefttypes;
2890 	List	   *righttypes;
2891 	List	   *new_ops;
2892 	List	   *var_args;
2893 	List	   *non_var_args;
2894 
2895 	iclause->rinfo = rinfo;
2896 	iclause->indexcol = indexcol;
2897 
2898 	if (var_on_left)
2899 	{
2900 		var_args = clause->largs;
2901 		non_var_args = clause->rargs;
2902 	}
2903 	else
2904 	{
2905 		var_args = clause->rargs;
2906 		non_var_args = clause->largs;
2907 	}
2908 
2909 	get_op_opfamily_properties(expr_op, index->opfamily[indexcol], false,
2910 							   &op_strategy,
2911 							   &op_lefttype,
2912 							   &op_righttype);
2913 
2914 	/* Initialize returned list of which index columns are used */
2915 	iclause->indexcols = list_make1_int(indexcol);
2916 
2917 	/* Build lists of ops, opfamilies and operator datatypes in case needed */
2918 	expr_ops = list_make1_oid(expr_op);
2919 	opfamilies = list_make1_oid(index->opfamily[indexcol]);
2920 	lefttypes = list_make1_oid(op_lefttype);
2921 	righttypes = list_make1_oid(op_righttype);
2922 
2923 	/*
2924 	 * See how many of the remaining columns match some index column in the
2925 	 * same way.  As in match_clause_to_indexcol(), the "other" side of any
2926 	 * potential index condition is OK as long as it doesn't use Vars from the
2927 	 * indexed relation.
2928 	 */
2929 	matching_cols = 1;
2930 
2931 	while (matching_cols < list_length(var_args))
2932 	{
2933 		Node	   *varop = (Node *) list_nth(var_args, matching_cols);
2934 		Node	   *constop = (Node *) list_nth(non_var_args, matching_cols);
2935 		int			i;
2936 
2937 		expr_op = list_nth_oid(clause->opnos, matching_cols);
2938 		if (!var_on_left)
2939 		{
2940 			/* indexkey is on right, so commute the operator */
2941 			expr_op = get_commutator(expr_op);
2942 			if (expr_op == InvalidOid)
2943 				break;			/* operator is not usable */
2944 		}
2945 		if (bms_is_member(index->rel->relid, pull_varnos(root, constop)))
2946 			break;				/* no good, Var on wrong side */
2947 		if (contain_volatile_functions(constop))
2948 			break;				/* no good, volatile comparison value */
2949 
2950 		/*
2951 		 * The Var side can match any key column of the index.
2952 		 */
2953 		for (i = 0; i < index->nkeycolumns; i++)
2954 		{
2955 			if (match_index_to_operand(varop, i, index) &&
2956 				get_op_opfamily_strategy(expr_op,
2957 										 index->opfamily[i]) == op_strategy &&
2958 				IndexCollMatchesExprColl(index->indexcollations[i],
2959 										 list_nth_oid(clause->inputcollids,
2960 													  matching_cols)))
2961 				break;
2962 		}
2963 		if (i >= index->nkeycolumns)
2964 			break;				/* no match found */
2965 
2966 		/* Add column number to returned list */
2967 		iclause->indexcols = lappend_int(iclause->indexcols, i);
2968 
2969 		/* Add operator info to lists */
2970 		get_op_opfamily_properties(expr_op, index->opfamily[i], false,
2971 								   &op_strategy,
2972 								   &op_lefttype,
2973 								   &op_righttype);
2974 		expr_ops = lappend_oid(expr_ops, expr_op);
2975 		opfamilies = lappend_oid(opfamilies, index->opfamily[i]);
2976 		lefttypes = lappend_oid(lefttypes, op_lefttype);
2977 		righttypes = lappend_oid(righttypes, op_righttype);
2978 
2979 		/* This column matches, keep scanning */
2980 		matching_cols++;
2981 	}
2982 
2983 	/* Result is non-lossy if all columns are usable as index quals */
2984 	iclause->lossy = (matching_cols != list_length(clause->opnos));
2985 
2986 	/*
2987 	 * We can use rinfo->clause as-is if we have var on left and it's all
2988 	 * usable as index quals.
2989 	 */
2990 	if (var_on_left && !iclause->lossy)
2991 		iclause->indexquals = list_make1(rinfo);
2992 	else
2993 	{
2994 		/*
2995 		 * We have to generate a modified rowcompare (possibly just one
2996 		 * OpExpr).  The painful part of this is changing < to <= or > to >=,
2997 		 * so deal with that first.
2998 		 */
2999 		if (!iclause->lossy)
3000 		{
3001 			/* very easy, just use the commuted operators */
3002 			new_ops = expr_ops;
3003 		}
3004 		else if (op_strategy == BTLessEqualStrategyNumber ||
3005 				 op_strategy == BTGreaterEqualStrategyNumber)
3006 		{
3007 			/* easy, just use the same (possibly commuted) operators */
3008 			new_ops = list_truncate(expr_ops, matching_cols);
3009 		}
3010 		else
3011 		{
3012 			ListCell   *opfamilies_cell;
3013 			ListCell   *lefttypes_cell;
3014 			ListCell   *righttypes_cell;
3015 
3016 			if (op_strategy == BTLessStrategyNumber)
3017 				op_strategy = BTLessEqualStrategyNumber;
3018 			else if (op_strategy == BTGreaterStrategyNumber)
3019 				op_strategy = BTGreaterEqualStrategyNumber;
3020 			else
3021 				elog(ERROR, "unexpected strategy number %d", op_strategy);
3022 			new_ops = NIL;
3023 			forthree(opfamilies_cell, opfamilies,
3024 					 lefttypes_cell, lefttypes,
3025 					 righttypes_cell, righttypes)
3026 			{
3027 				Oid			opfam = lfirst_oid(opfamilies_cell);
3028 				Oid			lefttype = lfirst_oid(lefttypes_cell);
3029 				Oid			righttype = lfirst_oid(righttypes_cell);
3030 
3031 				expr_op = get_opfamily_member(opfam, lefttype, righttype,
3032 											  op_strategy);
3033 				if (!OidIsValid(expr_op))	/* should not happen */
3034 					elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3035 						 op_strategy, lefttype, righttype, opfam);
3036 				new_ops = lappend_oid(new_ops, expr_op);
3037 			}
3038 		}
3039 
3040 		/* If we have more than one matching col, create a subset rowcompare */
3041 		if (matching_cols > 1)
3042 		{
3043 			RowCompareExpr *rc = makeNode(RowCompareExpr);
3044 
3045 			rc->rctype = (RowCompareType) op_strategy;
3046 			rc->opnos = new_ops;
3047 			rc->opfamilies = list_truncate(list_copy(clause->opfamilies),
3048 										   matching_cols);
3049 			rc->inputcollids = list_truncate(list_copy(clause->inputcollids),
3050 											 matching_cols);
3051 			rc->largs = list_truncate(copyObject(var_args),
3052 									  matching_cols);
3053 			rc->rargs = list_truncate(copyObject(non_var_args),
3054 									  matching_cols);
3055 			iclause->indexquals = list_make1(make_simple_restrictinfo(root,
3056 																	  (Expr *) rc));
3057 		}
3058 		else
3059 		{
3060 			Expr	   *op;
3061 
3062 			/* We don't report an index column list in this case */
3063 			iclause->indexcols = NIL;
3064 
3065 			op = make_opclause(linitial_oid(new_ops), BOOLOID, false,
3066 							   copyObject(linitial(var_args)),
3067 							   copyObject(linitial(non_var_args)),
3068 							   InvalidOid,
3069 							   linitial_oid(clause->inputcollids));
3070 			iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
3071 		}
3072 	}
3073 
3074 	return iclause;
3075 }
3076 
3077 
3078 /****************************************************************************
3079  *				----  ROUTINES TO CHECK ORDERING OPERATORS	----
3080  ****************************************************************************/
3081 
3082 /*
3083  * match_pathkeys_to_index
3084  *		Test whether an index can produce output ordered according to the
3085  *		given pathkeys using "ordering operators".
3086  *
3087  * If it can, return a list of suitable ORDER BY expressions, each of the form
3088  * "indexedcol operator pseudoconstant", along with an integer list of the
3089  * index column numbers (zero based) that each clause would be used with.
3090  * NIL lists are returned if the ordering is not achievable this way.
3091  *
3092  * On success, the result list is ordered by pathkeys, and in fact is
3093  * one-to-one with the requested pathkeys.
3094  */
3095 static void
match_pathkeys_to_index(IndexOptInfo * index,List * pathkeys,List ** orderby_clauses_p,List ** clause_columns_p)3096 match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
3097 						List **orderby_clauses_p,
3098 						List **clause_columns_p)
3099 {
3100 	List	   *orderby_clauses = NIL;
3101 	List	   *clause_columns = NIL;
3102 	ListCell   *lc1;
3103 
3104 	*orderby_clauses_p = NIL;	/* set default results */
3105 	*clause_columns_p = NIL;
3106 
3107 	/* Only indexes with the amcanorderbyop property are interesting here */
3108 	if (!index->amcanorderbyop)
3109 		return;
3110 
3111 	foreach(lc1, pathkeys)
3112 	{
3113 		PathKey    *pathkey = (PathKey *) lfirst(lc1);
3114 		bool		found = false;
3115 		ListCell   *lc2;
3116 
3117 		/*
3118 		 * Note: for any failure to match, we just return NIL immediately.
3119 		 * There is no value in matching just some of the pathkeys.
3120 		 */
3121 
3122 		/* Pathkey must request default sort order for the target opfamily */
3123 		if (pathkey->pk_strategy != BTLessStrategyNumber ||
3124 			pathkey->pk_nulls_first)
3125 			return;
3126 
3127 		/* If eclass is volatile, no hope of using an indexscan */
3128 		if (pathkey->pk_eclass->ec_has_volatile)
3129 			return;
3130 
3131 		/*
3132 		 * Try to match eclass member expression(s) to index.  Note that child
3133 		 * EC members are considered, but only when they belong to the target
3134 		 * relation.  (Unlike regular members, the same expression could be a
3135 		 * child member of more than one EC.  Therefore, the same index could
3136 		 * be considered to match more than one pathkey list, which is OK
3137 		 * here.  See also get_eclass_for_sort_expr.)
3138 		 */
3139 		foreach(lc2, pathkey->pk_eclass->ec_members)
3140 		{
3141 			EquivalenceMember *member = (EquivalenceMember *) lfirst(lc2);
3142 			int			indexcol;
3143 
3144 			/* No possibility of match if it references other relations */
3145 			if (!bms_equal(member->em_relids, index->rel->relids))
3146 				continue;
3147 
3148 			/*
3149 			 * We allow any column of the index to match each pathkey; they
3150 			 * don't have to match left-to-right as you might expect.  This is
3151 			 * correct for GiST, and it doesn't matter for SP-GiST because
3152 			 * that doesn't handle multiple columns anyway, and no other
3153 			 * existing AMs support amcanorderbyop.  We might need different
3154 			 * logic in future for other implementations.
3155 			 */
3156 			for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
3157 			{
3158 				Expr	   *expr;
3159 
3160 				expr = match_clause_to_ordering_op(index,
3161 												   indexcol,
3162 												   member->em_expr,
3163 												   pathkey->pk_opfamily);
3164 				if (expr)
3165 				{
3166 					orderby_clauses = lappend(orderby_clauses, expr);
3167 					clause_columns = lappend_int(clause_columns, indexcol);
3168 					found = true;
3169 					break;
3170 				}
3171 			}
3172 
3173 			if (found)			/* don't want to look at remaining members */
3174 				break;
3175 		}
3176 
3177 		if (!found)				/* fail if no match for this pathkey */
3178 			return;
3179 	}
3180 
3181 	*orderby_clauses_p = orderby_clauses;	/* success! */
3182 	*clause_columns_p = clause_columns;
3183 }
3184 
3185 /*
3186  * match_clause_to_ordering_op
3187  *	  Determines whether an ordering operator expression matches an
3188  *	  index column.
3189  *
3190  *	  This is similar to, but simpler than, match_clause_to_indexcol.
3191  *	  We only care about simple OpExpr cases.  The input is a bare
3192  *	  expression that is being ordered by, which must be of the form
3193  *	  (indexkey op const) or (const op indexkey) where op is an ordering
3194  *	  operator for the column's opfamily.
3195  *
3196  * 'index' is the index of interest.
3197  * 'indexcol' is a column number of 'index' (counting from 0).
3198  * 'clause' is the ordering expression to be tested.
3199  * 'pk_opfamily' is the btree opfamily describing the required sort order.
3200  *
3201  * Note that we currently do not consider the collation of the ordering
3202  * operator's result.  In practical cases the result type will be numeric
3203  * and thus have no collation, and it's not very clear what to match to
3204  * if it did have a collation.  The index's collation should match the
3205  * ordering operator's input collation, not its result.
3206  *
3207  * If successful, return 'clause' as-is if the indexkey is on the left,
3208  * otherwise a commuted copy of 'clause'.  If no match, return NULL.
3209  */
3210 static Expr *
match_clause_to_ordering_op(IndexOptInfo * index,int indexcol,Expr * clause,Oid pk_opfamily)3211 match_clause_to_ordering_op(IndexOptInfo *index,
3212 							int indexcol,
3213 							Expr *clause,
3214 							Oid pk_opfamily)
3215 {
3216 	Oid			opfamily;
3217 	Oid			idxcollation;
3218 	Node	   *leftop,
3219 			   *rightop;
3220 	Oid			expr_op;
3221 	Oid			expr_coll;
3222 	Oid			sortfamily;
3223 	bool		commuted;
3224 
3225 	Assert(indexcol < index->nkeycolumns);
3226 
3227 	opfamily = index->opfamily[indexcol];
3228 	idxcollation = index->indexcollations[indexcol];
3229 
3230 	/*
3231 	 * Clause must be a binary opclause.
3232 	 */
3233 	if (!is_opclause(clause))
3234 		return NULL;
3235 	leftop = get_leftop(clause);
3236 	rightop = get_rightop(clause);
3237 	if (!leftop || !rightop)
3238 		return NULL;
3239 	expr_op = ((OpExpr *) clause)->opno;
3240 	expr_coll = ((OpExpr *) clause)->inputcollid;
3241 
3242 	/*
3243 	 * We can forget the whole thing right away if wrong collation.
3244 	 */
3245 	if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
3246 		return NULL;
3247 
3248 	/*
3249 	 * Check for clauses of the form: (indexkey operator constant) or
3250 	 * (constant operator indexkey).
3251 	 */
3252 	if (match_index_to_operand(leftop, indexcol, index) &&
3253 		!contain_var_clause(rightop) &&
3254 		!contain_volatile_functions(rightop))
3255 	{
3256 		commuted = false;
3257 	}
3258 	else if (match_index_to_operand(rightop, indexcol, index) &&
3259 			 !contain_var_clause(leftop) &&
3260 			 !contain_volatile_functions(leftop))
3261 	{
3262 		/* Might match, but we need a commuted operator */
3263 		expr_op = get_commutator(expr_op);
3264 		if (expr_op == InvalidOid)
3265 			return NULL;
3266 		commuted = true;
3267 	}
3268 	else
3269 		return NULL;
3270 
3271 	/*
3272 	 * Is the (commuted) operator an ordering operator for the opfamily? And
3273 	 * if so, does it yield the right sorting semantics?
3274 	 */
3275 	sortfamily = get_op_opfamily_sortfamily(expr_op, opfamily);
3276 	if (sortfamily != pk_opfamily)
3277 		return NULL;
3278 
3279 	/* We have a match.  Return clause or a commuted version thereof. */
3280 	if (commuted)
3281 	{
3282 		OpExpr	   *newclause = makeNode(OpExpr);
3283 
3284 		/* flat-copy all the fields of clause */
3285 		memcpy(newclause, clause, sizeof(OpExpr));
3286 
3287 		/* commute it */
3288 		newclause->opno = expr_op;
3289 		newclause->opfuncid = InvalidOid;
3290 		newclause->args = list_make2(rightop, leftop);
3291 
3292 		clause = (Expr *) newclause;
3293 	}
3294 
3295 	return clause;
3296 }
3297 
3298 
3299 /****************************************************************************
3300  *				----  ROUTINES TO DO PARTIAL INDEX PREDICATE TESTS	----
3301  ****************************************************************************/
3302 
3303 /*
3304  * check_index_predicates
3305  *		Set the predicate-derived IndexOptInfo fields for each index
3306  *		of the specified relation.
3307  *
3308  * predOK is set true if the index is partial and its predicate is satisfied
3309  * for this query, ie the query's WHERE clauses imply the predicate.
3310  *
3311  * indrestrictinfo is set to the relation's baserestrictinfo list less any
3312  * conditions that are implied by the index's predicate.  (Obviously, for a
3313  * non-partial index, this is the same as baserestrictinfo.)  Such conditions
3314  * can be dropped from the plan when using the index, in certain cases.
3315  *
3316  * At one time it was possible for this to get re-run after adding more
3317  * restrictions to the rel, thus possibly letting us prove more indexes OK.
3318  * That doesn't happen any more (at least not in the core code's usage),
3319  * but this code still supports it in case extensions want to mess with the
3320  * baserestrictinfo list.  We assume that adding more restrictions can't make
3321  * an index not predOK.  We must recompute indrestrictinfo each time, though,
3322  * to make sure any newly-added restrictions get into it if needed.
3323  */
3324 void
check_index_predicates(PlannerInfo * root,RelOptInfo * rel)3325 check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
3326 {
3327 	List	   *clauselist;
3328 	bool		have_partial;
3329 	bool		is_target_rel;
3330 	Relids		otherrels;
3331 	ListCell   *lc;
3332 
3333 	/* Indexes are available only on base or "other" member relations. */
3334 	Assert(IS_SIMPLE_REL(rel));
3335 
3336 	/*
3337 	 * Initialize the indrestrictinfo lists to be identical to
3338 	 * baserestrictinfo, and check whether there are any partial indexes.  If
3339 	 * not, this is all we need to do.
3340 	 */
3341 	have_partial = false;
3342 	foreach(lc, rel->indexlist)
3343 	{
3344 		IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
3345 
3346 		index->indrestrictinfo = rel->baserestrictinfo;
3347 		if (index->indpred)
3348 			have_partial = true;
3349 	}
3350 	if (!have_partial)
3351 		return;
3352 
3353 	/*
3354 	 * Construct a list of clauses that we can assume true for the purpose of
3355 	 * proving the index(es) usable.  Restriction clauses for the rel are
3356 	 * always usable, and so are any join clauses that are "movable to" this
3357 	 * rel.  Also, we can consider any EC-derivable join clauses (which must
3358 	 * be "movable to" this rel, by definition).
3359 	 */
3360 	clauselist = list_copy(rel->baserestrictinfo);
3361 
3362 	/* Scan the rel's join clauses */
3363 	foreach(lc, rel->joininfo)
3364 	{
3365 		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3366 
3367 		/* Check if clause can be moved to this rel */
3368 		if (!join_clause_is_movable_to(rinfo, rel))
3369 			continue;
3370 
3371 		clauselist = lappend(clauselist, rinfo);
3372 	}
3373 
3374 	/*
3375 	 * Add on any equivalence-derivable join clauses.  Computing the correct
3376 	 * relid sets for generate_join_implied_equalities is slightly tricky
3377 	 * because the rel could be a child rel rather than a true baserel, and in
3378 	 * that case we must remove its parents' relid(s) from all_baserels.
3379 	 */
3380 	if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3381 		otherrels = bms_difference(root->all_baserels,
3382 								   find_childrel_parents(root, rel));
3383 	else
3384 		otherrels = bms_difference(root->all_baserels, rel->relids);
3385 
3386 	if (!bms_is_empty(otherrels))
3387 		clauselist =
3388 			list_concat(clauselist,
3389 						generate_join_implied_equalities(root,
3390 														 bms_union(rel->relids,
3391 																   otherrels),
3392 														 otherrels,
3393 														 rel));
3394 
3395 	/*
3396 	 * Normally we remove quals that are implied by a partial index's
3397 	 * predicate from indrestrictinfo, indicating that they need not be
3398 	 * checked explicitly by an indexscan plan using this index.  However, if
3399 	 * the rel is a target relation of UPDATE/DELETE/SELECT FOR UPDATE, we
3400 	 * cannot remove such quals from the plan, because they need to be in the
3401 	 * plan so that they will be properly rechecked by EvalPlanQual testing.
3402 	 * Some day we might want to remove such quals from the main plan anyway
3403 	 * and pass them through to EvalPlanQual via a side channel; but for now,
3404 	 * we just don't remove implied quals at all for target relations.
3405 	 */
3406 	is_target_rel = (rel->relid == root->parse->resultRelation ||
3407 					 get_plan_rowmark(root->rowMarks, rel->relid) != NULL);
3408 
3409 	/*
3410 	 * Now try to prove each index predicate true, and compute the
3411 	 * indrestrictinfo lists for partial indexes.  Note that we compute the
3412 	 * indrestrictinfo list even for non-predOK indexes; this might seem
3413 	 * wasteful, but we may be able to use such indexes in OR clauses, cf
3414 	 * generate_bitmap_or_paths().
3415 	 */
3416 	foreach(lc, rel->indexlist)
3417 	{
3418 		IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
3419 		ListCell   *lcr;
3420 
3421 		if (index->indpred == NIL)
3422 			continue;			/* ignore non-partial indexes here */
3423 
3424 		if (!index->predOK)		/* don't repeat work if already proven OK */
3425 			index->predOK = predicate_implied_by(index->indpred, clauselist,
3426 												 false);
3427 
3428 		/* If rel is an update target, leave indrestrictinfo as set above */
3429 		if (is_target_rel)
3430 			continue;
3431 
3432 		/* Else compute indrestrictinfo as the non-implied quals */
3433 		index->indrestrictinfo = NIL;
3434 		foreach(lcr, rel->baserestrictinfo)
3435 		{
3436 			RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcr);
3437 
3438 			/* predicate_implied_by() assumes first arg is immutable */
3439 			if (contain_mutable_functions((Node *) rinfo->clause) ||
3440 				!predicate_implied_by(list_make1(rinfo->clause),
3441 									  index->indpred, false))
3442 				index->indrestrictinfo = lappend(index->indrestrictinfo, rinfo);
3443 		}
3444 	}
3445 }
3446 
3447 /****************************************************************************
3448  *				----  ROUTINES TO CHECK EXTERNALLY-VISIBLE CONDITIONS  ----
3449  ****************************************************************************/
3450 
3451 /*
3452  * ec_member_matches_indexcol
3453  *	  Test whether an EquivalenceClass member matches an index column.
3454  *
3455  * This is a callback for use by generate_implied_equalities_for_column.
3456  */
3457 static bool
ec_member_matches_indexcol(PlannerInfo * root,RelOptInfo * rel,EquivalenceClass * ec,EquivalenceMember * em,void * arg)3458 ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
3459 						   EquivalenceClass *ec, EquivalenceMember *em,
3460 						   void *arg)
3461 {
3462 	IndexOptInfo *index = ((ec_member_matches_arg *) arg)->index;
3463 	int			indexcol = ((ec_member_matches_arg *) arg)->indexcol;
3464 	Oid			curFamily;
3465 	Oid			curCollation;
3466 
3467 	Assert(indexcol < index->nkeycolumns);
3468 
3469 	curFamily = index->opfamily[indexcol];
3470 	curCollation = index->indexcollations[indexcol];
3471 
3472 	/*
3473 	 * If it's a btree index, we can reject it if its opfamily isn't
3474 	 * compatible with the EC, since no clause generated from the EC could be
3475 	 * used with the index.  For non-btree indexes, we can't easily tell
3476 	 * whether clauses generated from the EC could be used with the index, so
3477 	 * don't check the opfamily.  This might mean we return "true" for a
3478 	 * useless EC, so we have to recheck the results of
3479 	 * generate_implied_equalities_for_column; see
3480 	 * match_eclass_clauses_to_index.
3481 	 */
3482 	if (index->relam == BTREE_AM_OID &&
3483 		!list_member_oid(ec->ec_opfamilies, curFamily))
3484 		return false;
3485 
3486 	/* We insist on collation match for all index types, though */
3487 	if (!IndexCollMatchesExprColl(curCollation, ec->ec_collation))
3488 		return false;
3489 
3490 	return match_index_to_operand((Node *) em->em_expr, indexcol, index);
3491 }
3492 
3493 /*
3494  * relation_has_unique_index_for
3495  *	  Determine whether the relation provably has at most one row satisfying
3496  *	  a set of equality conditions, because the conditions constrain all
3497  *	  columns of some unique index.
3498  *
3499  * The conditions can be represented in either or both of two ways:
3500  * 1. A list of RestrictInfo nodes, where the caller has already determined
3501  * that each condition is a mergejoinable equality with an expression in
3502  * this relation on one side, and an expression not involving this relation
3503  * on the other.  The transient outer_is_left flag is used to identify which
3504  * side we should look at: left side if outer_is_left is false, right side
3505  * if it is true.
3506  * 2. A list of expressions in this relation, and a corresponding list of
3507  * equality operators. The caller must have already checked that the operators
3508  * represent equality.  (Note: the operators could be cross-type; the
3509  * expressions should correspond to their RHS inputs.)
3510  *
3511  * The caller need only supply equality conditions arising from joins;
3512  * this routine automatically adds in any usable baserestrictinfo clauses.
3513  * (Note that the passed-in restrictlist will be destructively modified!)
3514  */
3515 bool
relation_has_unique_index_for(PlannerInfo * root,RelOptInfo * rel,List * restrictlist,List * exprlist,List * oprlist)3516 relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel,
3517 							  List *restrictlist,
3518 							  List *exprlist, List *oprlist)
3519 {
3520 	ListCell   *ic;
3521 
3522 	Assert(list_length(exprlist) == list_length(oprlist));
3523 
3524 	/* Short-circuit if no indexes... */
3525 	if (rel->indexlist == NIL)
3526 		return false;
3527 
3528 	/*
3529 	 * Examine the rel's restriction clauses for usable var = const clauses
3530 	 * that we can add to the restrictlist.
3531 	 */
3532 	foreach(ic, rel->baserestrictinfo)
3533 	{
3534 		RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(ic);
3535 
3536 		/*
3537 		 * Note: can_join won't be set for a restriction clause, but
3538 		 * mergeopfamilies will be if it has a mergejoinable operator and
3539 		 * doesn't contain volatile functions.
3540 		 */
3541 		if (restrictinfo->mergeopfamilies == NIL)
3542 			continue;			/* not mergejoinable */
3543 
3544 		/*
3545 		 * The clause certainly doesn't refer to anything but the given rel.
3546 		 * If either side is pseudoconstant then we can use it.
3547 		 */
3548 		if (bms_is_empty(restrictinfo->left_relids))
3549 		{
3550 			/* righthand side is inner */
3551 			restrictinfo->outer_is_left = true;
3552 		}
3553 		else if (bms_is_empty(restrictinfo->right_relids))
3554 		{
3555 			/* lefthand side is inner */
3556 			restrictinfo->outer_is_left = false;
3557 		}
3558 		else
3559 			continue;
3560 
3561 		/* OK, add to list */
3562 		restrictlist = lappend(restrictlist, restrictinfo);
3563 	}
3564 
3565 	/* Short-circuit the easy case */
3566 	if (restrictlist == NIL && exprlist == NIL)
3567 		return false;
3568 
3569 	/* Examine each index of the relation ... */
3570 	foreach(ic, rel->indexlist)
3571 	{
3572 		IndexOptInfo *ind = (IndexOptInfo *) lfirst(ic);
3573 		int			c;
3574 
3575 		/*
3576 		 * If the index is not unique, or not immediately enforced, or if it's
3577 		 * a partial index that doesn't match the query, it's useless here.
3578 		 */
3579 		if (!ind->unique || !ind->immediate ||
3580 			(ind->indpred != NIL && !ind->predOK))
3581 			continue;
3582 
3583 		/*
3584 		 * Try to find each index column in the lists of conditions.  This is
3585 		 * O(N^2) or worse, but we expect all the lists to be short.
3586 		 */
3587 		for (c = 0; c < ind->nkeycolumns; c++)
3588 		{
3589 			bool		matched = false;
3590 			ListCell   *lc;
3591 			ListCell   *lc2;
3592 
3593 			foreach(lc, restrictlist)
3594 			{
3595 				RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3596 				Node	   *rexpr;
3597 
3598 				/*
3599 				 * The condition's equality operator must be a member of the
3600 				 * index opfamily, else it is not asserting the right kind of
3601 				 * equality behavior for this index.  We check this first
3602 				 * since it's probably cheaper than match_index_to_operand().
3603 				 */
3604 				if (!list_member_oid(rinfo->mergeopfamilies, ind->opfamily[c]))
3605 					continue;
3606 
3607 				/*
3608 				 * XXX at some point we may need to check collations here too.
3609 				 * For the moment we assume all collations reduce to the same
3610 				 * notion of equality.
3611 				 */
3612 
3613 				/* OK, see if the condition operand matches the index key */
3614 				if (rinfo->outer_is_left)
3615 					rexpr = get_rightop(rinfo->clause);
3616 				else
3617 					rexpr = get_leftop(rinfo->clause);
3618 
3619 				if (match_index_to_operand(rexpr, c, ind))
3620 				{
3621 					matched = true; /* column is unique */
3622 					break;
3623 				}
3624 			}
3625 
3626 			if (matched)
3627 				continue;
3628 
3629 			forboth(lc, exprlist, lc2, oprlist)
3630 			{
3631 				Node	   *expr = (Node *) lfirst(lc);
3632 				Oid			opr = lfirst_oid(lc2);
3633 
3634 				/* See if the expression matches the index key */
3635 				if (!match_index_to_operand(expr, c, ind))
3636 					continue;
3637 
3638 				/*
3639 				 * The equality operator must be a member of the index
3640 				 * opfamily, else it is not asserting the right kind of
3641 				 * equality behavior for this index.  We assume the caller
3642 				 * determined it is an equality operator, so we don't need to
3643 				 * check any more tightly than this.
3644 				 */
3645 				if (!op_in_opfamily(opr, ind->opfamily[c]))
3646 					continue;
3647 
3648 				/*
3649 				 * XXX at some point we may need to check collations here too.
3650 				 * For the moment we assume all collations reduce to the same
3651 				 * notion of equality.
3652 				 */
3653 
3654 				matched = true; /* column is unique */
3655 				break;
3656 			}
3657 
3658 			if (!matched)
3659 				break;			/* no match; this index doesn't help us */
3660 		}
3661 
3662 		/* Matched all key columns of this index? */
3663 		if (c == ind->nkeycolumns)
3664 			return true;
3665 	}
3666 
3667 	return false;
3668 }
3669 
3670 /*
3671  * indexcol_is_bool_constant_for_query
3672  *
3673  * If an index column is constrained to have a constant value by the query's
3674  * WHERE conditions, then it's irrelevant for sort-order considerations.
3675  * Usually that means we have a restriction clause WHERE indexcol = constant,
3676  * which gets turned into an EquivalenceClass containing a constant, which
3677  * is recognized as redundant by build_index_pathkeys().  But if the index
3678  * column is a boolean variable (or expression), then we are not going to
3679  * see WHERE indexcol = constant, because expression preprocessing will have
3680  * simplified that to "WHERE indexcol" or "WHERE NOT indexcol".  So we are not
3681  * going to have a matching EquivalenceClass (unless the query also contains
3682  * "ORDER BY indexcol").  To allow such cases to work the same as they would
3683  * for non-boolean values, this function is provided to detect whether the
3684  * specified index column matches a boolean restriction clause.
3685  */
3686 bool
indexcol_is_bool_constant_for_query(PlannerInfo * root,IndexOptInfo * index,int indexcol)3687 indexcol_is_bool_constant_for_query(PlannerInfo *root,
3688 									IndexOptInfo *index,
3689 									int indexcol)
3690 {
3691 	ListCell   *lc;
3692 
3693 	/* If the index isn't boolean, we can't possibly get a match */
3694 	if (!IsBooleanOpfamily(index->opfamily[indexcol]))
3695 		return false;
3696 
3697 	/* Check each restriction clause for the index's rel */
3698 	foreach(lc, index->rel->baserestrictinfo)
3699 	{
3700 		RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3701 
3702 		/*
3703 		 * As in match_clause_to_indexcol, never match pseudoconstants to
3704 		 * indexes.  (It might be semantically okay to do so here, but the
3705 		 * odds of getting a match are negligible, so don't waste the cycles.)
3706 		 */
3707 		if (rinfo->pseudoconstant)
3708 			continue;
3709 
3710 		/* See if we can match the clause's expression to the index column */
3711 		if (match_boolean_index_clause(root, rinfo, indexcol, index))
3712 			return true;
3713 	}
3714 
3715 	return false;
3716 }
3717 
3718 
3719 /****************************************************************************
3720  *				----  ROUTINES TO CHECK OPERANDS  ----
3721  ****************************************************************************/
3722 
3723 /*
3724  * match_index_to_operand()
3725  *	  Generalized test for a match between an index's key
3726  *	  and the operand on one side of a restriction or join clause.
3727  *
3728  * operand: the nodetree to be compared to the index
3729  * indexcol: the column number of the index (counting from 0)
3730  * index: the index of interest
3731  *
3732  * Note that we aren't interested in collations here; the caller must check
3733  * for a collation match, if it's dealing with an operator where that matters.
3734  *
3735  * This is exported for use in selfuncs.c.
3736  */
3737 bool
match_index_to_operand(Node * operand,int indexcol,IndexOptInfo * index)3738 match_index_to_operand(Node *operand,
3739 					   int indexcol,
3740 					   IndexOptInfo *index)
3741 {
3742 	int			indkey;
3743 
3744 	/*
3745 	 * Ignore any RelabelType node above the operand.   This is needed to be
3746 	 * able to apply indexscanning in binary-compatible-operator cases. Note:
3747 	 * we can assume there is at most one RelabelType node;
3748 	 * eval_const_expressions() will have simplified if more than one.
3749 	 */
3750 	if (operand && IsA(operand, RelabelType))
3751 		operand = (Node *) ((RelabelType *) operand)->arg;
3752 
3753 	indkey = index->indexkeys[indexcol];
3754 	if (indkey != 0)
3755 	{
3756 		/*
3757 		 * Simple index column; operand must be a matching Var.
3758 		 */
3759 		if (operand && IsA(operand, Var) &&
3760 			index->rel->relid == ((Var *) operand)->varno &&
3761 			indkey == ((Var *) operand)->varattno)
3762 			return true;
3763 	}
3764 	else
3765 	{
3766 		/*
3767 		 * Index expression; find the correct expression.  (This search could
3768 		 * be avoided, at the cost of complicating all the callers of this
3769 		 * routine; doesn't seem worth it.)
3770 		 */
3771 		ListCell   *indexpr_item;
3772 		int			i;
3773 		Node	   *indexkey;
3774 
3775 		indexpr_item = list_head(index->indexprs);
3776 		for (i = 0; i < indexcol; i++)
3777 		{
3778 			if (index->indexkeys[i] == 0)
3779 			{
3780 				if (indexpr_item == NULL)
3781 					elog(ERROR, "wrong number of index expressions");
3782 				indexpr_item = lnext(index->indexprs, indexpr_item);
3783 			}
3784 		}
3785 		if (indexpr_item == NULL)
3786 			elog(ERROR, "wrong number of index expressions");
3787 		indexkey = (Node *) lfirst(indexpr_item);
3788 
3789 		/*
3790 		 * Does it match the operand?  Again, strip any relabeling.
3791 		 */
3792 		if (indexkey && IsA(indexkey, RelabelType))
3793 			indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3794 
3795 		if (equal(indexkey, operand))
3796 			return true;
3797 	}
3798 
3799 	return false;
3800 }
3801 
3802 /*
3803  * is_pseudo_constant_for_index()
3804  *	  Test whether the given expression can be used as an indexscan
3805  *	  comparison value.
3806  *
3807  * An indexscan comparison value must not contain any volatile functions,
3808  * and it can't contain any Vars of the index's own table.  Vars of
3809  * other tables are okay, though; in that case we'd be producing an
3810  * indexqual usable in a parameterized indexscan.  This is, therefore,
3811  * a weaker condition than is_pseudo_constant_clause().
3812  *
3813  * This function is exported for use by planner support functions,
3814  * which will have available the IndexOptInfo, but not any RestrictInfo
3815  * infrastructure.  It is making the same test made by functions above
3816  * such as match_opclause_to_indexcol(), but those rely where possible
3817  * on RestrictInfo information about variable membership.
3818  *
3819  * expr: the nodetree to be checked
3820  * index: the index of interest
3821  */
3822 bool
is_pseudo_constant_for_index(Node * expr,IndexOptInfo * index)3823 is_pseudo_constant_for_index(Node *expr, IndexOptInfo *index)
3824 {
3825 	return is_pseudo_constant_for_index_new(NULL, expr, index);
3826 }
3827 
3828 bool
is_pseudo_constant_for_index_new(PlannerInfo * root,Node * expr,IndexOptInfo * index)3829 is_pseudo_constant_for_index_new(PlannerInfo *root, Node *expr, IndexOptInfo *index)
3830 {
3831 	/* pull_varnos is cheaper than volatility check, so do that first */
3832 	if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
3833 		return false;			/* no good, contains Var of table */
3834 	if (contain_volatile_functions(expr))
3835 		return false;			/* no good, volatile comparison value */
3836 	return true;
3837 }
3838