Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * nbtpreprocesskeys.c
4 : : * Preprocessing for Postgres btree scan keys.
5 : : *
6 : : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/access/nbtree/nbtpreprocesskeys.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include "access/nbtree.h"
19 : : #include "access/relscan.h"
20 : : #include "common/int.h"
21 : : #include "lib/qunique.h"
22 : : #include "utils/array.h"
23 : : #include "utils/lsyscache.h"
24 : : #include "utils/memutils.h"
25 : : #include "utils/rel.h"
26 : :
27 : : typedef struct BTScanKeyPreproc
28 : : {
29 : : ScanKey inkey;
30 : : int inkeyi;
31 : : int arrayidx;
32 : : } BTScanKeyPreproc;
33 : :
34 : : typedef struct BTSortArrayContext
35 : : {
36 : : FmgrInfo *sortproc;
37 : : Oid collation;
38 : : bool reverse;
39 : : } BTSortArrayContext;
40 : :
41 : : static bool _bt_fix_scankey_strategy(ScanKey skey, int16 *indoption);
42 : : static void _bt_mark_scankey_required(ScanKey skey);
43 : : static bool _bt_compare_scankey_args(IndexScanDesc scan, ScanKey op,
44 : : ScanKey leftarg, ScanKey rightarg,
45 : : BTArrayKeyInfo *array, FmgrInfo *orderproc,
46 : : bool *result);
47 : : static bool _bt_compare_array_scankey_args(IndexScanDesc scan,
48 : : ScanKey arraysk, ScanKey skey,
49 : : FmgrInfo *orderproc, BTArrayKeyInfo *array,
50 : : bool *qual_ok);
51 : : static bool _bt_saoparray_shrink(IndexScanDesc scan, ScanKey arraysk,
52 : : ScanKey skey, FmgrInfo *orderproc,
53 : : BTArrayKeyInfo *array, bool *qual_ok);
54 : : static bool _bt_skiparray_shrink(IndexScanDesc scan, ScanKey skey,
55 : : BTArrayKeyInfo *array, bool *qual_ok);
56 : : static void _bt_skiparray_strat_adjust(IndexScanDesc scan, ScanKey arraysk,
57 : : BTArrayKeyInfo *array);
58 : : static void _bt_skiparray_strat_decrement(IndexScanDesc scan, ScanKey arraysk,
59 : : BTArrayKeyInfo *array);
60 : : static void _bt_skiparray_strat_increment(IndexScanDesc scan, ScanKey arraysk,
61 : : BTArrayKeyInfo *array);
62 : : static void _bt_unmark_keys(IndexScanDesc scan, int *keyDataMap);
63 : : static int _bt_reorder_array_cmp(const void *a, const void *b);
64 : : static ScanKey _bt_preprocess_array_keys(IndexScanDesc scan, int *new_numberOfKeys);
65 : : static void _bt_preprocess_array_keys_final(IndexScanDesc scan, int *keyDataMap);
66 : : static int _bt_num_array_keys(IndexScanDesc scan, Oid *skip_eq_ops_out,
67 : : int *numSkipArrayKeys_out);
68 : : static Datum _bt_find_extreme_element(IndexScanDesc scan, ScanKey skey,
69 : : Oid elemtype, StrategyNumber strat,
70 : : Datum *elems, int nelems);
71 : : static void _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
72 : : FmgrInfo *orderproc, FmgrInfo **sortprocp);
73 : : static int _bt_sort_array_elements(ScanKey skey, FmgrInfo *sortproc,
74 : : bool reverse, Datum *elems, int nelems);
75 : : static bool _bt_merge_arrays(IndexScanDesc scan, ScanKey skey,
76 : : FmgrInfo *sortproc, bool reverse,
77 : : Oid origelemtype, Oid nextelemtype,
78 : : Datum *elems_orig, int *nelems_orig,
79 : : Datum *elems_next, int nelems_next);
80 : : static int _bt_compare_array_elements(const void *a, const void *b, void *arg);
81 : :
82 : :
83 : : /*
84 : : * _bt_preprocess_keys() -- Preprocess scan keys
85 : : *
86 : : * The given search-type keys (taken from scan->keyData[])
87 : : * are copied to so->keyData[] with possible transformation.
88 : : * scan->numberOfKeys is the number of input keys, so->numberOfKeys gets
89 : : * the number of output keys. Calling here a second or subsequent time
90 : : * (during the same btrescan) is a no-op.
91 : : *
92 : : * The output keys are marked with additional sk_flags bits beyond the
93 : : * system-standard bits supplied by the caller. The DESC and NULLS_FIRST
94 : : * indoption bits for the relevant index attribute are copied into the flags.
95 : : * Also, for a DESC column, we commute (flip) all the sk_strategy numbers
96 : : * so that the index sorts in the desired direction.
97 : : *
98 : : * One key purpose of this routine is to discover which scan keys must be
99 : : * satisfied to continue the scan. It also attempts to eliminate redundant
100 : : * keys and detect contradictory keys. (If the index opfamily provides
101 : : * incomplete sets of cross-type operators, we may fail to detect redundant
102 : : * or contradictory keys, but we can survive that.)
103 : : *
104 : : * Required output keys are sorted by index attribute. Presently we expect
105 : : * (but verify) that the input keys are already so sorted --- this is done
106 : : * by match_clauses_to_index() in indxpath.c. Some reordering of the keys
107 : : * within each attribute may be done as a byproduct of the processing here.
108 : : * That process must leave array scan keys (within an attribute) in the same
109 : : * order as corresponding entries from the scan's BTArrayKeyInfo array info.
110 : : * We might also construct skip array scan keys that weren't present in the
111 : : * original input keys; these are also output in standard attribute order.
112 : : *
113 : : * The output keys are marked with flags SK_BT_REQFWD and/or SK_BT_REQBKWD
114 : : * if they must be satisfied in order to continue the scan forward or backward
115 : : * respectively. _bt_checkkeys uses these flags. For example, if the quals
116 : : * are "x = 1 AND y < 4 AND z < 5", then _bt_checkkeys will reject a tuple
117 : : * (1,2,7), but we must continue the scan in case there are tuples (1,3,z).
118 : : * But once we reach tuples like (1,4,z) we can stop scanning because no
119 : : * later tuples could match. This is reflected by marking the x and y keys,
120 : : * but not the z key, with SK_BT_REQFWD. In general, the keys for leading
121 : : * attributes with "=" keys are marked both SK_BT_REQFWD and SK_BT_REQBKWD.
122 : : * For the first attribute without an "=" key, any "<" and "<=" keys are
123 : : * marked SK_BT_REQFWD while any ">" and ">=" keys are marked SK_BT_REQBKWD.
124 : : * This can be seen to be correct by considering the above example.
125 : : *
126 : : * If we never generated skip array scan keys, it would be possible for "gaps"
127 : : * to appear that make it unsafe to mark any subsequent input scan keys
128 : : * (copied from scan->keyData[]) as required to continue the scan. Prior to
129 : : * Postgres 18, a qual like "WHERE y = 4" always resulted in a full scan.
130 : : * This qual now becomes "WHERE x = ANY('{every possible x value}') and y = 4"
131 : : * on output. In other words, preprocessing now adds a skip array on "x".
132 : : * This has the potential to be much more efficient than a full index scan
133 : : * (though it behaves like a full scan when there's many distinct "x" values).
134 : : *
135 : : * Typically, redundant keys are eliminated: we keep only the tightest
136 : : * >/>= bound and the tightest </<= bound, and if there's an = key then
137 : : * that's the only one returned. (So, we return either a single = key,
138 : : * or one or two boundary-condition keys for each attr.) However, if we
139 : : * cannot compare two keys for lack of a suitable cross-type operator,
140 : : * we cannot eliminate either key.
141 : : *
142 : : * When all redundant keys could not be eliminated, we'll output a key array
143 : : * that can more or less be treated as if it had no redundant keys. Suppose
144 : : * we have "x > 4::int AND x > 10::bigint AND x < 70", and we are unable to
145 : : * determine which > key is more restrictive for lack of a suitable cross-type
146 : : * operator. We'll arbitrarily pick one of the > keys; the other > key won't
147 : : * be marked required. Obviously, the scan will be less efficient if we
148 : : * choose x > 4 over x > 10 -- but it can still largely proceed as if there
149 : : * was only a single > condition. "x > 10" will be placed at the end of the
150 : : * so->keyData[] output array. It'll always be evaluated last, after the keys
151 : : * that could be marked required in the usual way (after "x > 4 AND x < 70").
152 : : * This can sometimes result in so->keyData[] keys that aren't even in index
153 : : * attribute order (if the qual involves multiple attributes). The scan's
154 : : * required keys will still be in attribute order, though, so it can't matter.
155 : : *
156 : : * This scheme ensures that _bt_first always uses the same set of keys at the
157 : : * start of a forwards scan as those _bt_checkkeys uses to determine when to
158 : : * end a similar backwards scan (and vice-versa). _bt_advance_array_keys
159 : : * depends on this: it expects to be able to reliably predict what the next
160 : : * _bt_first call will do by testing whether _bt_checkkeys' routines report
161 : : * that the final tuple on the page is past the end of matches for the scan's
162 : : * keys with the scan direction flipped. If it is (if continuescan=false),
163 : : * then it follows that calling _bt_first will, at a minimum, relocate the
164 : : * scan to the very next leaf page (in the current scan direction).
165 : : *
166 : : * As a byproduct of this work, we can detect contradictory quals such
167 : : * as "x = 1 AND x > 2". If we see that, we return so->qual_ok = false,
168 : : * indicating the scan need not be run at all since no tuples can match.
169 : : * (In this case we do not bother completing the output key array!)
170 : : * Again, missing cross-type operators might cause us to fail to prove the
171 : : * quals contradictory when they really are, but the scan will work correctly.
172 : : *
173 : : * Skip array = keys will even be generated in the presence of "contradictory"
174 : : * inequality quals when it'll enable marking later input quals as required.
175 : : * We'll merge any such inequalities into the generated skip array by setting
176 : : * its array.low_compare or array.high_compare key field. The resulting skip
177 : : * array will generate its array elements from a range that's constrained by
178 : : * any merged input inequalities (which won't get output in so->keyData[]).
179 : : *
180 : : * Row comparison keys currently have a couple of notable limitations.
181 : : * Right now we just transfer them into the preprocessed array without any
182 : : * editorialization. We can treat them the same as an ordinary inequality
183 : : * comparison on the row's first index column, for the purposes of the logic
184 : : * about required keys. Also, we are unable to merge a row comparison key
185 : : * into a skip array (only ordinary inequalities are merged). A key that
186 : : * comes after a Row comparison key is therefore never marked as required.
187 : : *
188 : : * Note: the reason we have to copy the preprocessed scan keys into private
189 : : * storage is that we are modifying the array based on comparisons of the
190 : : * key argument values, which could change on a rescan. Therefore we can't
191 : : * overwrite the source data.
192 : : */
193 : : void
236 pg@bowt.ie 194 :CBC 7007698 : _bt_preprocess_keys(IndexScanDesc scan)
195 : : {
196 : 7007698 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
197 : 7007698 : int numberOfKeys = scan->numberOfKeys;
198 : 7007698 : int16 *indoption = scan->indexRelation->rd_indoption;
199 : : int new_numberOfKeys;
200 : : int numberOfEqualCols;
201 : : ScanKey inkeys;
202 : : BTScanKeyPreproc xform[BTMaxStrategyNumber];
203 : : bool test_result,
66 204 : 7007698 : redundant_key_kept = false;
205 : : AttrNumber attno;
206 : : ScanKey arrayKeyData;
236 207 : 7007698 : int *keyDataMap = NULL;
208 : 7007698 : int arrayidx = 0;
209 : :
210 [ + + ]: 7007698 : if (so->numberOfKeys > 0)
211 : : {
212 : : /*
213 : : * Only need to do preprocessing once per btrescan, at most. All
214 : : * calls after the first are handled as no-ops.
215 : : */
216 : 3548228 : return;
217 : : }
218 : :
219 : : /* initialize result variables */
220 : 6998947 : so->qual_ok = true;
221 : 6998947 : so->numberOfKeys = 0;
222 : :
223 [ + + ]: 6998947 : if (numberOfKeys < 1)
224 : 6561 : return; /* done if qual-less scan */
225 : :
226 : : /* If any keys are SK_SEARCHARRAY type, set up array-key info */
227 : 6992386 : arrayKeyData = _bt_preprocess_array_keys(scan, &numberOfKeys);
228 [ + + ]: 6992386 : if (!so->qual_ok)
229 : : {
230 : : /* unmatchable array, so give up */
231 : 9 : return;
232 : : }
233 : :
234 : : /*
235 : : * Treat arrayKeyData[] (a partially preprocessed copy of scan->keyData[])
236 : : * as our input if _bt_preprocess_array_keys just allocated it, else just
237 : : * use scan->keyData[]
238 : : */
239 [ + + ]: 6992377 : if (arrayKeyData)
240 : : {
241 : 35522 : inkeys = arrayKeyData;
242 : :
243 : : /* Also maintain keyDataMap for remapping so->orderProcs[] later */
244 : 35522 : keyDataMap = MemoryContextAlloc(so->arrayContext,
245 : : numberOfKeys * sizeof(int));
246 : :
247 : : /*
248 : : * Also enlarge output array when it might otherwise not have room for
249 : : * a skip array's scan key
250 : : */
155 251 [ + + ]: 35522 : if (numberOfKeys > scan->numberOfKeys)
252 : 1875 : so->keyData = repalloc(so->keyData,
253 : : numberOfKeys * sizeof(ScanKeyData));
254 : : }
255 : : else
236 256 : 6956855 : inkeys = scan->keyData;
257 : :
258 : : /* we check that input keys are correctly ordered */
259 [ - + ]: 6992377 : if (inkeys[0].sk_attno < 1)
236 pg@bowt.ie 260 [ # # ]:UBC 0 : elog(ERROR, "btree index keys must be ordered by attribute");
261 : :
262 : : /* We can short-circuit most of the work if there's just one key */
236 pg@bowt.ie 263 [ + + ]:CBC 6992377 : if (numberOfKeys == 1)
264 : : {
265 : : /* Apply indoption to scankey (might change sk_strategy!) */
266 [ + + ]: 3532416 : if (!_bt_fix_scankey_strategy(&inkeys[0], indoption))
267 : 551 : so->qual_ok = false;
268 : 3532416 : memcpy(&so->keyData[0], &inkeys[0], sizeof(ScanKeyData));
269 : 3532416 : so->numberOfKeys = 1;
270 : : /* We can mark the qual as required if it's for first index col */
271 [ + - ]: 3532416 : if (inkeys[0].sk_attno == 1)
272 : 3532416 : _bt_mark_scankey_required(&so->keyData[0]);
273 [ + + ]: 3532416 : if (arrayKeyData)
274 : : {
275 : : /*
276 : : * Don't call _bt_preprocess_array_keys_final in this fast path
277 : : * (we'll miss out on the single value array transformation, but
278 : : * that's not nearly as important when there's only one scan key)
279 : : */
280 [ - + ]: 33377 : Assert(so->keyData[0].sk_flags & SK_SEARCHARRAY);
281 [ + + + - : 33377 : Assert(so->keyData[0].sk_strategy != BTEqualStrategyNumber ||
+ - - + ]
282 : : (so->arrayKeys[0].scan_key == 0 &&
283 : : !(so->keyData[0].sk_flags & SK_BT_SKIP) &&
284 : : OidIsValid(so->orderProcs[0].fn_oid)));
285 : : }
286 : :
287 : 3532416 : return;
288 : : }
289 : :
290 : : /*
291 : : * Otherwise, do the full set of pushups.
292 : : */
293 : 3459961 : new_numberOfKeys = 0;
294 : 3459961 : numberOfEqualCols = 0;
295 : :
296 : : /*
297 : : * Initialize for processing of keys for attr 1.
298 : : *
299 : : * xform[i] points to the currently best scan key of strategy type i+1; it
300 : : * is NULL if we haven't yet found such a key for this attr.
301 : : */
302 : 3459961 : attno = 1;
303 : 3459961 : memset(xform, 0, sizeof(xform));
304 : :
305 : : /*
306 : : * Loop iterates from 0 to numberOfKeys inclusive; we use the last pass to
307 : : * handle after-last-key processing. Actual exit from the loop is at the
308 : : * "break" statement below.
309 : : */
310 : 3459961 : for (int i = 0;; i++)
311 : 7722153 : {
312 : 11182114 : ScanKey inkey = inkeys + i;
313 : : int j;
314 : :
315 [ + + ]: 11182114 : if (i < numberOfKeys)
316 : : {
317 : : /* Apply indoption to scankey (might change sk_strategy!) */
318 [ + + ]: 7722626 : if (!_bt_fix_scankey_strategy(inkey, indoption))
319 : : {
320 : : /* NULL can't be matched, so give up */
321 : 470 : so->qual_ok = false;
322 : 470 : return;
323 : : }
324 : : }
325 : :
326 : : /*
327 : : * If we are at the end of the keys for a particular attr, finish up
328 : : * processing and emit the cleaned-up keys.
329 : : */
330 [ + + + + ]: 11181644 : if (i == numberOfKeys || inkey->sk_attno != attno)
331 : : {
332 : 7720967 : int priorNumberOfEqualCols = numberOfEqualCols;
333 : :
334 : : /* check input keys are correctly ordered */
335 [ + + - + ]: 7720967 : if (i < numberOfKeys && inkey->sk_attno < attno)
236 pg@bowt.ie 336 [ # # ]:UBC 0 : elog(ERROR, "btree index keys must be ordered by attribute");
337 : :
338 : : /*
339 : : * If = has been specified, all other keys can be eliminated as
340 : : * redundant. Note that this is no less true if the = key is
341 : : * SEARCHARRAY; the only real difference is that the inequality
342 : : * key _becomes_ redundant by making _bt_compare_scankey_args
343 : : * eliminate the subset of elements that won't need to be matched
344 : : * (with SAOP arrays and skip arrays alike).
345 : : *
346 : : * If we have a case like "key = 1 AND key > 2", we set qual_ok to
347 : : * false and abandon further processing. We'll do the same thing
348 : : * given a case like "key IN (0, 1) AND key > 2".
349 : : *
350 : : * We also have to deal with the case of "key IS NULL", which is
351 : : * unsatisfiable in combination with any other index condition. By
352 : : * the time we get here, that's been classified as an equality
353 : : * check, and we've rejected any combination of it with a regular
354 : : * equality condition; but not with other types of conditions.
355 : : */
236 pg@bowt.ie 356 [ + + ]:CBC 7720967 : if (xform[BTEqualStrategyNumber - 1].inkey)
357 : : {
358 : 7072988 : ScanKey eq = xform[BTEqualStrategyNumber - 1].inkey;
359 : 7072988 : BTArrayKeyInfo *array = NULL;
360 : 7072988 : FmgrInfo *orderproc = NULL;
361 : :
362 [ + + + + ]: 7072988 : if (arrayKeyData && (eq->sk_flags & SK_SEARCHARRAY))
363 : : {
364 : : int eq_in_ikey,
365 : : eq_arrayidx;
366 : :
367 : 2299 : eq_in_ikey = xform[BTEqualStrategyNumber - 1].inkeyi;
368 : 2299 : eq_arrayidx = xform[BTEqualStrategyNumber - 1].arrayidx;
369 : 2299 : array = &so->arrayKeys[eq_arrayidx - 1];
370 : 2299 : orderproc = so->orderProcs + eq_in_ikey;
371 : :
372 [ - + ]: 2299 : Assert(array->scan_key == eq_in_ikey);
373 [ - + ]: 2299 : Assert(OidIsValid(orderproc->fn_oid));
374 : : }
375 : :
376 [ + + ]: 42437850 : for (j = BTMaxStrategyNumber; --j >= 0;)
377 : : {
378 : 35364880 : ScanKey chk = xform[j].inkey;
379 : :
380 [ + + + + ]: 35364880 : if (!chk || j == (BTEqualStrategyNumber - 1))
381 : 35364659 : continue;
382 : :
383 [ + + ]: 221 : if (eq->sk_flags & SK_SEARCHNULL)
384 : : {
385 : : /* IS NULL is contradictory to anything else */
386 : 12 : so->qual_ok = false;
387 : 12 : return;
388 : : }
389 : :
390 [ + + ]: 209 : if (_bt_compare_scankey_args(scan, chk, eq, chk,
391 : : array, orderproc,
392 : : &test_result))
393 : : {
394 [ + + ]: 206 : if (!test_result)
395 : : {
396 : : /* keys proven mutually contradictory */
397 : 6 : so->qual_ok = false;
398 : 6 : return;
399 : : }
400 : : /* else discard the redundant non-equality key */
401 : 200 : xform[j].inkey = NULL;
402 : 200 : xform[j].inkeyi = -1;
403 : : }
404 : : else
66 405 : 3 : redundant_key_kept = true;
406 : : }
407 : : /* track number of attrs for which we have "=" keys */
236 408 : 7072970 : numberOfEqualCols++;
409 : : }
410 : :
411 : : /* try to keep only one of <, <= */
412 [ + + ]: 7720949 : if (xform[BTLessStrategyNumber - 1].inkey &&
413 [ + + ]: 956 : xform[BTLessEqualStrategyNumber - 1].inkey)
414 : : {
415 : 3 : ScanKey lt = xform[BTLessStrategyNumber - 1].inkey;
416 : 3 : ScanKey le = xform[BTLessEqualStrategyNumber - 1].inkey;
417 : :
418 [ + - ]: 3 : if (_bt_compare_scankey_args(scan, le, lt, le, NULL, NULL,
419 : : &test_result))
420 : : {
421 [ + - ]: 3 : if (test_result)
422 : 3 : xform[BTLessEqualStrategyNumber - 1].inkey = NULL;
423 : : else
236 pg@bowt.ie 424 :UBC 0 : xform[BTLessStrategyNumber - 1].inkey = NULL;
425 : : }
426 : : else
66 427 : 0 : redundant_key_kept = true;
428 : : }
429 : :
430 : : /* try to keep only one of >, >= */
236 pg@bowt.ie 431 [ + + ]:CBC 7720949 : if (xform[BTGreaterStrategyNumber - 1].inkey &&
432 [ + + ]: 645843 : xform[BTGreaterEqualStrategyNumber - 1].inkey)
433 : : {
434 : 3 : ScanKey gt = xform[BTGreaterStrategyNumber - 1].inkey;
435 : 3 : ScanKey ge = xform[BTGreaterEqualStrategyNumber - 1].inkey;
436 : :
437 [ + - ]: 3 : if (_bt_compare_scankey_args(scan, ge, gt, ge, NULL, NULL,
438 : : &test_result))
439 : : {
440 [ - + ]: 3 : if (test_result)
236 pg@bowt.ie 441 :UBC 0 : xform[BTGreaterEqualStrategyNumber - 1].inkey = NULL;
442 : : else
236 pg@bowt.ie 443 :CBC 3 : xform[BTGreaterStrategyNumber - 1].inkey = NULL;
444 : : }
445 : : else
66 pg@bowt.ie 446 :UBC 0 : redundant_key_kept = true;
447 : : }
448 : :
449 : : /*
450 : : * Emit the cleaned-up keys into the so->keyData[] array, and then
451 : : * mark them if they are required. They are required (possibly
452 : : * only in one direction) if all attrs before this one had "=".
453 : : *
454 : : * In practice we'll rarely output non-required scan keys here;
455 : : * typically, _bt_preprocess_array_keys has already added "=" keys
456 : : * sufficient to form an unbroken series of "=" constraints on all
457 : : * attrs prior to the attr from the final scan->keyData[] key.
458 : : */
236 pg@bowt.ie 459 [ + + ]:CBC 46325694 : for (j = BTMaxStrategyNumber; --j >= 0;)
460 : : {
461 [ + + ]: 38604745 : if (xform[j].inkey)
462 : : {
463 : 7721869 : ScanKey outkey = &so->keyData[new_numberOfKeys++];
464 : :
465 : 7721869 : memcpy(outkey, xform[j].inkey, sizeof(ScanKeyData));
466 [ + + ]: 7721869 : if (arrayKeyData)
467 : 4711 : keyDataMap[new_numberOfKeys - 1] = xform[j].inkeyi;
468 [ + - ]: 7721869 : if (priorNumberOfEqualCols == attno - 1)
469 : 7721869 : _bt_mark_scankey_required(outkey);
470 : : }
471 : : }
472 : :
473 : : /*
474 : : * Exit loop here if done.
475 : : */
476 [ + + ]: 7720949 : if (i == numberOfKeys)
477 : 3459470 : break;
478 : :
479 : : /* Re-initialize for new attno */
480 : 4261479 : attno = inkey->sk_attno;
481 : 4261479 : memset(xform, 0, sizeof(xform));
482 : : }
483 : :
484 : : /* check strategy this key's operator corresponds to */
485 : 7722156 : j = inkey->sk_strategy - 1;
486 : :
487 [ + + ]: 7722156 : if (inkey->sk_strategy == BTEqualStrategyNumber &&
488 [ + + ]: 7073012 : (inkey->sk_flags & SK_SEARCHARRAY))
489 : : {
490 : : /* must track how input scan keys map to arrays */
491 [ - + ]: 2302 : Assert(arrayKeyData);
492 : 2302 : arrayidx++;
493 : : }
494 : :
495 : : /*
496 : : * have we seen a scan key for this same attribute and using this same
497 : : * operator strategy before now?
498 : : */
499 [ + + ]: 7722156 : if (xform[j].inkey == NULL)
500 : : {
501 : : /* nope, so this scan key wins by default (at least for now) */
502 : 7722123 : xform[j].inkey = inkey;
503 : 7722123 : xform[j].inkeyi = i;
504 : 7722123 : xform[j].arrayidx = arrayidx;
505 : : }
506 : : else
507 : : {
508 : 33 : FmgrInfo *orderproc = NULL;
509 : 33 : BTArrayKeyInfo *array = NULL;
510 : :
511 : : /*
512 : : * Seen one of these before, so keep only the more restrictive key
513 : : * if possible
514 : : */
515 [ + + + + ]: 33 : if (j == (BTEqualStrategyNumber - 1) && arrayKeyData)
516 : : {
517 : : /*
518 : : * Have to set up array keys
519 : : */
520 [ - + ]: 9 : if (inkey->sk_flags & SK_SEARCHARRAY)
521 : : {
236 pg@bowt.ie 522 :UBC 0 : array = &so->arrayKeys[arrayidx - 1];
523 : 0 : orderproc = so->orderProcs + i;
524 : :
525 [ # # ]: 0 : Assert(array->scan_key == i);
526 [ # # ]: 0 : Assert(OidIsValid(orderproc->fn_oid));
155 527 [ # # ]: 0 : Assert(!(inkey->sk_flags & SK_BT_SKIP));
528 : : }
236 pg@bowt.ie 529 [ + + ]:CBC 9 : else if (xform[j].inkey->sk_flags & SK_SEARCHARRAY)
530 : : {
531 : 6 : array = &so->arrayKeys[xform[j].arrayidx - 1];
532 : 6 : orderproc = so->orderProcs + xform[j].inkeyi;
533 : :
534 [ - + ]: 6 : Assert(array->scan_key == xform[j].inkeyi);
535 [ - + ]: 6 : Assert(OidIsValid(orderproc->fn_oid));
155 536 [ - + ]: 6 : Assert(!(xform[j].inkey->sk_flags & SK_BT_SKIP));
537 : : }
538 : :
539 : : /*
540 : : * Both scan keys might have arrays, in which case we'll
541 : : * arbitrarily pass only one of the arrays. That won't
542 : : * matter, since _bt_compare_scankey_args is aware that two
543 : : * SEARCHARRAY scan keys mean that _bt_preprocess_array_keys
544 : : * failed to eliminate redundant arrays through array merging.
545 : : * _bt_compare_scankey_args just returns false when it sees
546 : : * this; it won't even try to examine either array.
547 : : */
548 : : }
549 : :
236 550 [ + - ]: 33 : if (_bt_compare_scankey_args(scan, inkey, inkey, xform[j].inkey,
551 : : array, orderproc, &test_result))
552 : : {
553 : : /* Have all we need to determine redundancy */
554 [ + + ]: 33 : if (test_result)
555 : : {
556 : : /*
557 : : * New key is more restrictive, and so replaces old key...
558 : : */
559 [ + + ]: 27 : if (j != (BTEqualStrategyNumber - 1) ||
560 [ + + ]: 9 : !(xform[j].inkey->sk_flags & SK_SEARCHARRAY))
561 : : {
562 : 24 : xform[j].inkey = inkey;
563 : 24 : xform[j].inkeyi = i;
564 : 24 : xform[j].arrayidx = arrayidx;
565 : : }
566 : : else
567 : : {
568 : : /*
569 : : * ...unless we have to keep the old key because it's
570 : : * an array that rendered the new key redundant. We
571 : : * need to make sure that we don't throw away an array
572 : : * scan key. _bt_preprocess_array_keys_final expects
573 : : * us to keep all of the arrays that weren't already
574 : : * eliminated by _bt_preprocess_array_keys earlier on.
575 : : */
576 [ - + ]: 3 : Assert(!(inkey->sk_flags & SK_SEARCHARRAY));
577 : : }
578 : : }
579 [ + + ]: 6 : else if (j == (BTEqualStrategyNumber - 1))
580 : : {
581 : : /* key == a && key == b, but a != b */
582 : 3 : so->qual_ok = false;
583 : 3 : return;
584 : : }
585 : : /* else old key is more restrictive, keep it */
586 : : }
587 : : else
588 : : {
589 : : /*
590 : : * We can't determine which key is more restrictive. Push
591 : : * xform[j] directly to the output array, then set xform[j] to
592 : : * the new scan key.
593 : : *
594 : : * Note: We do things this way around so that our arrays are
595 : : * always in the same order as their corresponding scan keys.
596 : : * _bt_preprocess_array_keys_final expects this.
597 : : */
236 pg@bowt.ie 598 :UBC 0 : ScanKey outkey = &so->keyData[new_numberOfKeys++];
599 : :
600 : 0 : memcpy(outkey, xform[j].inkey, sizeof(ScanKeyData));
601 [ # # ]: 0 : if (arrayKeyData)
602 : 0 : keyDataMap[new_numberOfKeys - 1] = xform[j].inkeyi;
603 [ # # ]: 0 : if (numberOfEqualCols == attno - 1)
604 : 0 : _bt_mark_scankey_required(outkey);
605 : 0 : xform[j].inkey = inkey;
606 : 0 : xform[j].inkeyi = i;
607 : 0 : xform[j].arrayidx = arrayidx;
66 608 : 0 : redundant_key_kept = true;
609 : : }
610 : : }
611 : : }
612 : :
236 pg@bowt.ie 613 :CBC 3459470 : so->numberOfKeys = new_numberOfKeys;
614 : :
615 : : /*
616 : : * Now that we've built a temporary mapping from so->keyData[] (output
617 : : * scan keys) to arrayKeyData[] (our input scan keys), fix array->scan_key
618 : : * references. Also consolidate the so->orderProcs[] array such that it
619 : : * can be subscripted using so->keyData[]-wise offsets.
620 : : */
621 [ + + ]: 3459470 : if (arrayKeyData)
622 : 2124 : _bt_preprocess_array_keys_final(scan, keyDataMap);
623 : :
624 : : /*
625 : : * If there are remaining redundant inequality keys, we must make sure
626 : : * that each index attribute has no more than one required >/>= key, and
627 : : * no more than one required </<= key. Attributes that have one or more
628 : : * required = keys now must keep only one required key (the first = key).
629 : : */
66 630 [ + + + - ]: 3459470 : if (unlikely(redundant_key_kept) && so->qual_ok)
631 : 3 : _bt_unmark_keys(scan, keyDataMap);
632 : :
633 : : /* Could pfree arrayKeyData/keyDataMap now, but not worth the cycles */
634 : : }
635 : :
636 : : /*
637 : : * Adjust a scankey's strategy and flags setting as needed for indoptions.
638 : : *
639 : : * We copy the appropriate indoption value into the scankey sk_flags
640 : : * (shifting to avoid clobbering system-defined flag bits). Also, if
641 : : * the DESC option is set, commute (flip) the operator strategy number.
642 : : *
643 : : * A secondary purpose is to check for IS NULL/NOT NULL scankeys and set up
644 : : * the strategy field correctly for them.
645 : : *
646 : : * Lastly, for ordinary scankeys (not IS NULL/NOT NULL), we check for a
647 : : * NULL comparison value. Since all btree operators are assumed strict,
648 : : * a NULL means that the qual cannot be satisfied. We return true if the
649 : : * comparison value isn't NULL, or false if the scan should be abandoned.
650 : : *
651 : : * This function is applied to the *input* scankey structure; therefore
652 : : * on a rescan we will be looking at already-processed scankeys. Hence
653 : : * we have to be careful not to re-commute the strategy if we already did it.
654 : : * It's a bit ugly to modify the caller's copy of the scankey but in practice
655 : : * there shouldn't be any problem, since the index's indoptions are certainly
656 : : * not going to change while the scankey survives.
657 : : */
658 : : static bool
236 659 : 11255042 : _bt_fix_scankey_strategy(ScanKey skey, int16 *indoption)
660 : : {
661 : : int addflags;
662 : :
663 : 11255042 : addflags = indoption[skey->sk_attno - 1] << SK_BT_INDOPTION_SHIFT;
664 : :
665 : : /*
666 : : * We treat all btree operators as strict (even if they're not so marked
667 : : * in pg_proc). This means that it is impossible for an operator condition
668 : : * with a NULL comparison constant to succeed, and we can reject it right
669 : : * away.
670 : : *
671 : : * However, we now also support "x IS NULL" clauses as search conditions,
672 : : * so in that case keep going. The planner has not filled in any
673 : : * particular strategy in this case, so set it to BTEqualStrategyNumber
674 : : * --- we can treat IS NULL as an equality operator for purposes of search
675 : : * strategy.
676 : : *
677 : : * Likewise, "x IS NOT NULL" is supported. We treat that as either "less
678 : : * than NULL" in a NULLS LAST index, or "greater than NULL" in a NULLS
679 : : * FIRST index.
680 : : *
681 : : * Note: someday we might have to fill in sk_collation from the index
682 : : * column's collation. At the moment this is a non-issue because we'll
683 : : * never actually call the comparison operator on a NULL.
684 : : */
685 [ + + ]: 11255042 : if (skey->sk_flags & SK_ISNULL)
686 : : {
687 : : /* SK_ISNULL shouldn't be set in a row header scankey */
688 [ - + ]: 64066 : Assert(!(skey->sk_flags & SK_ROW_HEADER));
689 : :
690 : : /* Set indoption flags in scankey (might be done already) */
691 : 64066 : skey->sk_flags |= addflags;
692 : :
693 : : /* Set correct strategy for IS NULL or NOT NULL search */
694 [ + + ]: 64066 : if (skey->sk_flags & SK_SEARCHNULL)
695 : : {
696 : 76 : skey->sk_strategy = BTEqualStrategyNumber;
697 : 76 : skey->sk_subtype = InvalidOid;
698 : 76 : skey->sk_collation = InvalidOid;
699 : : }
700 [ + + ]: 63990 : else if (skey->sk_flags & SK_SEARCHNOTNULL)
701 : : {
702 [ + + ]: 62972 : if (skey->sk_flags & SK_BT_NULLS_FIRST)
703 : 18 : skey->sk_strategy = BTGreaterStrategyNumber;
704 : : else
705 : 62954 : skey->sk_strategy = BTLessStrategyNumber;
706 : 62972 : skey->sk_subtype = InvalidOid;
707 : 62972 : skey->sk_collation = InvalidOid;
708 : : }
709 : : else
710 : : {
711 : : /* regular qual, so it cannot be satisfied */
712 : 1018 : return false;
713 : : }
714 : :
715 : : /* Needn't do the rest */
716 : 63048 : return true;
717 : : }
718 : :
719 : : /* Adjust strategy for DESC, if we didn't already */
720 [ + + + - ]: 11190976 : if ((addflags & SK_BT_DESC) && !(skey->sk_flags & SK_BT_DESC))
721 : 39 : skey->sk_strategy = BTCommuteStrategyNumber(skey->sk_strategy);
722 : 11190976 : skey->sk_flags |= addflags;
723 : :
724 : : /* If it's a row header, fix row member flags and strategies similarly */
725 [ + + ]: 11190976 : if (skey->sk_flags & SK_ROW_HEADER)
726 : : {
727 : 42 : ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
728 : :
729 [ + + ]: 42 : if (subkey->sk_flags & SK_ISNULL)
730 : : {
731 : : /* First row member is NULL, so RowCompare is unsatisfiable */
732 [ - + ]: 3 : Assert(subkey->sk_flags & SK_ROW_MEMBER);
733 : 3 : return false;
734 : : }
735 : :
736 : : for (;;)
737 : : {
738 [ - + ]: 78 : Assert(subkey->sk_flags & SK_ROW_MEMBER);
739 : 78 : addflags = indoption[subkey->sk_attno - 1] << SK_BT_INDOPTION_SHIFT;
740 [ - + - - ]: 78 : if ((addflags & SK_BT_DESC) && !(subkey->sk_flags & SK_BT_DESC))
236 pg@bowt.ie 741 :UBC 0 : subkey->sk_strategy = BTCommuteStrategyNumber(subkey->sk_strategy);
236 pg@bowt.ie 742 :CBC 78 : subkey->sk_flags |= addflags;
743 [ + + ]: 78 : if (subkey->sk_flags & SK_ROW_END)
744 : 39 : break;
745 : 39 : subkey++;
746 : : }
747 : : }
748 : :
749 : 11190973 : return true;
750 : : }
751 : :
752 : : /*
753 : : * Mark a scankey as "required to continue the scan".
754 : : *
755 : : * Depending on the operator type, the key may be required for both scan
756 : : * directions or just one. Also, if the key is a row comparison header,
757 : : * we have to mark the appropriate subsidiary ScanKeys as required. In such
758 : : * cases, the first subsidiary key is required, but subsequent ones are
759 : : * required only as long as they correspond to successive index columns and
760 : : * match the leading column as to sort direction. Otherwise the row
761 : : * comparison ordering is different from the index ordering and so we can't
762 : : * stop the scan on the basis of those lower-order columns.
763 : : *
764 : : * Note: when we set required-key flag bits in a subsidiary scankey, we are
765 : : * scribbling on a data structure belonging to the index AM's caller, not on
766 : : * our private copy. This should be OK because the marking will not change
767 : : * from scan to scan within a query, and so we'd just re-mark the same way
768 : : * anyway on a rescan. Something to keep an eye on though.
769 : : */
770 : : static void
771 : 11254285 : _bt_mark_scankey_required(ScanKey skey)
772 : : {
773 : : int addflags;
774 : :
775 [ + + + - ]: 11254285 : switch (skey->sk_strategy)
776 : : {
777 : 64407 : case BTLessStrategyNumber:
778 : : case BTLessEqualStrategyNumber:
779 : 64407 : addflags = SK_BT_REQFWD;
780 : 64407 : break;
781 : 10541316 : case BTEqualStrategyNumber:
782 : 10541316 : addflags = SK_BT_REQFWD | SK_BT_REQBKWD;
783 : 10541316 : break;
784 : 648562 : case BTGreaterEqualStrategyNumber:
785 : : case BTGreaterStrategyNumber:
786 : 648562 : addflags = SK_BT_REQBKWD;
787 : 648562 : break;
236 pg@bowt.ie 788 :UBC 0 : default:
789 [ # # ]: 0 : elog(ERROR, "unrecognized StrategyNumber: %d",
790 : : (int) skey->sk_strategy);
791 : : addflags = 0; /* keep compiler quiet */
792 : : break;
793 : : }
794 : :
236 pg@bowt.ie 795 :CBC 11254285 : skey->sk_flags |= addflags;
796 : :
797 [ + + ]: 11254285 : if (skey->sk_flags & SK_ROW_HEADER)
798 : : {
799 : 42 : ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
66 800 : 42 : AttrNumber attno = skey->sk_attno;
801 : :
802 : : /* First subkey should be same column/operator as the header */
803 [ - + ]: 42 : Assert(subkey->sk_attno == attno);
236 804 [ + - ]: 42 : Assert(subkey->sk_strategy == skey->sk_strategy);
805 : :
806 : : for (;;)
807 : : {
66 808 [ - + ]: 84 : Assert(subkey->sk_flags & SK_ROW_MEMBER);
809 [ + + ]: 84 : if (subkey->sk_attno != attno)
810 : 6 : break; /* non-adjacent key, so not required */
811 [ - + ]: 78 : if (subkey->sk_strategy != skey->sk_strategy)
66 pg@bowt.ie 812 :UBC 0 : break; /* wrong direction, so not required */
66 pg@bowt.ie 813 :CBC 78 : subkey->sk_flags |= addflags;
814 [ + + ]: 78 : if (subkey->sk_flags & SK_ROW_END)
815 : 36 : break;
816 : 42 : subkey++;
817 : 42 : attno++;
818 : : }
819 : : }
236 820 : 11254285 : }
821 : :
822 : : /*
823 : : * Compare two scankey values using a specified operator.
824 : : *
825 : : * The test we want to perform is logically "leftarg op rightarg", where
826 : : * leftarg and rightarg are the sk_argument values in those ScanKeys, and
827 : : * the comparison operator is the one in the op ScanKey. However, in
828 : : * cross-data-type situations we may need to look up the correct operator in
829 : : * the index's opfamily: it is the one having amopstrategy = op->sk_strategy
830 : : * and amoplefttype/amoprighttype equal to the two argument datatypes.
831 : : *
832 : : * If the opfamily doesn't supply a complete set of cross-type operators we
833 : : * may not be able to make the comparison. If we can make the comparison
834 : : * we store the operator result in *result and return true. We return false
835 : : * if the comparison could not be made.
836 : : *
837 : : * If either leftarg or rightarg are an array, we'll apply array-specific
838 : : * rules to determine which array elements are redundant on behalf of caller.
839 : : * It is up to our caller to save whichever of the two scan keys is the array,
840 : : * and discard the non-array scan key (the non-array scan key is guaranteed to
841 : : * be redundant with any complete opfamily). Caller isn't expected to call
842 : : * here with a pair of array scan keys provided we're dealing with a complete
843 : : * opfamily (_bt_preprocess_array_keys will merge array keys together to make
844 : : * sure of that).
845 : : *
846 : : * Note: we'll also shrink caller's array as needed to eliminate redundant
847 : : * array elements. One reason why caller should prefer to discard non-array
848 : : * scan keys is so that we'll have the opportunity to shrink the array
849 : : * multiple times, in multiple calls (for each of several other scan keys on
850 : : * the same index attribute).
851 : : *
852 : : * Note: op always points at the same ScanKey as either leftarg or rightarg.
853 : : * Since we don't scribble on the scankeys themselves, this aliasing should
854 : : * cause no trouble.
855 : : *
856 : : * Note: this routine needs to be insensitive to any DESC option applied
857 : : * to the index column. For example, "x < 4" is a tighter constraint than
858 : : * "x < 5" regardless of which way the index is sorted.
859 : : */
860 : : static bool
861 : 254 : _bt_compare_scankey_args(IndexScanDesc scan, ScanKey op,
862 : : ScanKey leftarg, ScanKey rightarg,
863 : : BTArrayKeyInfo *array, FmgrInfo *orderproc,
864 : : bool *result)
865 : : {
866 : 254 : Relation rel = scan->indexRelation;
867 : : Oid lefttype,
868 : : righttype,
869 : : optype,
870 : : opcintype,
871 : : cmp_op;
872 : : StrategyNumber strat;
873 : :
66 874 [ - + ]: 254 : Assert(!((leftarg->sk_flags | rightarg->sk_flags) & SK_ROW_MEMBER));
875 : :
876 : : /*
877 : : * First, deal with cases where one or both args are NULL. This should
878 : : * only happen when the scankeys represent IS NULL/NOT NULL conditions.
879 : : */
236 880 [ + + ]: 254 : if ((leftarg->sk_flags | rightarg->sk_flags) & SK_ISNULL)
881 : : {
882 : : bool leftnull,
883 : : rightnull;
884 : :
885 : : /* Handle skip array comparison with IS NOT NULL scan key */
155 886 [ + + ]: 87 : if ((leftarg->sk_flags | rightarg->sk_flags) & SK_BT_SKIP)
887 : : {
888 : : /* Shouldn't generate skip array in presence of IS NULL key */
889 [ - + ]: 18 : Assert(!((leftarg->sk_flags | rightarg->sk_flags) & SK_SEARCHNULL));
890 [ - + ]: 18 : Assert((leftarg->sk_flags | rightarg->sk_flags) & SK_SEARCHNOTNULL);
891 : :
892 : : /* Skip array will have no NULL element/IS NULL scan key */
893 [ - + ]: 18 : Assert(array->num_elems == -1);
894 : 18 : array->null_elem = false;
895 : :
896 : : /* IS NOT NULL key (could be leftarg or rightarg) now redundant */
897 : 18 : *result = true;
898 : 18 : return true;
899 : : }
900 : :
236 901 [ + + ]: 69 : if (leftarg->sk_flags & SK_ISNULL)
902 : : {
903 [ - + ]: 3 : Assert(leftarg->sk_flags & (SK_SEARCHNULL | SK_SEARCHNOTNULL));
904 : 3 : leftnull = true;
905 : : }
906 : : else
907 : 66 : leftnull = false;
908 [ + - ]: 69 : if (rightarg->sk_flags & SK_ISNULL)
909 : : {
910 [ - + ]: 69 : Assert(rightarg->sk_flags & (SK_SEARCHNULL | SK_SEARCHNOTNULL));
911 : 69 : rightnull = true;
912 : : }
913 : : else
236 pg@bowt.ie 914 :UBC 0 : rightnull = false;
915 : :
916 : : /*
917 : : * We treat NULL as either greater than or less than all other values.
918 : : * Since true > false, the tests below work correctly for NULLS LAST
919 : : * logic. If the index is NULLS FIRST, we need to flip the strategy.
920 : : */
236 pg@bowt.ie 921 :CBC 69 : strat = op->sk_strategy;
922 [ - + ]: 69 : if (op->sk_flags & SK_BT_NULLS_FIRST)
236 pg@bowt.ie 923 :UBC 0 : strat = BTCommuteStrategyNumber(strat);
924 : :
236 pg@bowt.ie 925 [ + - + - :CBC 69 : switch (strat)
- - ]
926 : : {
927 : 66 : case BTLessStrategyNumber:
928 : 66 : *result = (leftnull < rightnull);
929 : 66 : break;
236 pg@bowt.ie 930 :UBC 0 : case BTLessEqualStrategyNumber:
931 : 0 : *result = (leftnull <= rightnull);
932 : 0 : break;
236 pg@bowt.ie 933 :CBC 3 : case BTEqualStrategyNumber:
934 : 3 : *result = (leftnull == rightnull);
935 : 3 : break;
236 pg@bowt.ie 936 :UBC 0 : case BTGreaterEqualStrategyNumber:
937 : 0 : *result = (leftnull >= rightnull);
938 : 0 : break;
939 : 0 : case BTGreaterStrategyNumber:
940 : 0 : *result = (leftnull > rightnull);
941 : 0 : break;
942 : 0 : default:
943 [ # # ]: 0 : elog(ERROR, "unrecognized StrategyNumber: %d", (int) strat);
944 : : *result = false; /* keep compiler quiet */
945 : : break;
946 : : }
236 pg@bowt.ie 947 :CBC 69 : return true;
948 : : }
949 : :
950 : : /*
951 : : * We don't yet know how to determine redundancy when it involves a row
952 : : * compare key (barring simple cases involving IS NULL/IS NOT NULL)
953 : : */
66 954 [ + + ]: 167 : if ((leftarg->sk_flags | rightarg->sk_flags) & SK_ROW_HEADER)
955 : : {
956 [ - + ]: 3 : Assert(!((leftarg->sk_flags | rightarg->sk_flags) & SK_BT_SKIP));
957 : 3 : return false;
958 : : }
959 : :
960 : : /*
961 : : * If either leftarg or rightarg are equality-type array scankeys, we need
962 : : * specialized handling (since by now we know that IS NULL wasn't used)
963 : : */
236 964 [ + + ]: 164 : if (array)
965 : : {
966 : : bool leftarray,
967 : : rightarray;
968 : :
969 [ + + ]: 194 : leftarray = ((leftarg->sk_flags & SK_SEARCHARRAY) &&
970 [ + - ]: 94 : leftarg->sk_strategy == BTEqualStrategyNumber);
971 [ + + ]: 106 : rightarray = ((rightarg->sk_flags & SK_SEARCHARRAY) &&
972 [ + - ]: 6 : rightarg->sk_strategy == BTEqualStrategyNumber);
973 : :
974 : : /*
975 : : * _bt_preprocess_array_keys is responsible for merging together array
976 : : * scan keys, and will do so whenever the opfamily has the required
977 : : * cross-type support. If it failed to do that, we handle it just
978 : : * like the case where we can't make the comparison ourselves.
979 : : */
980 [ + + - + ]: 100 : if (leftarray && rightarray)
981 : : {
982 : : /* Can't make the comparison */
236 pg@bowt.ie 983 :UBC 0 : *result = false; /* suppress compiler warnings */
155 984 [ # # ]: 0 : Assert(!((leftarg->sk_flags | rightarg->sk_flags) & SK_BT_SKIP));
236 985 : 0 : return false;
986 : : }
987 : :
988 : : /*
989 : : * Otherwise we need to determine if either one of leftarg or rightarg
990 : : * uses an array, then pass this through to a dedicated helper
991 : : * function.
992 : : */
236 pg@bowt.ie 993 [ + + ]:CBC 100 : if (leftarray)
994 : 94 : return _bt_compare_array_scankey_args(scan, leftarg, rightarg,
995 : : orderproc, array, result);
996 [ + - ]: 6 : else if (rightarray)
997 : 6 : return _bt_compare_array_scankey_args(scan, rightarg, leftarg,
998 : : orderproc, array, result);
999 : :
1000 : : /* FALL THRU */
1001 : : }
1002 : :
1003 : : /*
1004 : : * The opfamily we need to worry about is identified by the index column.
1005 : : */
1006 [ - + ]: 64 : Assert(leftarg->sk_attno == rightarg->sk_attno);
1007 : :
1008 : 64 : opcintype = rel->rd_opcintype[leftarg->sk_attno - 1];
1009 : :
1010 : : /*
1011 : : * Determine the actual datatypes of the ScanKey arguments. We have to
1012 : : * support the convention that sk_subtype == InvalidOid means the opclass
1013 : : * input type; this is a hack to simplify life for ScanKeyInit().
1014 : : */
1015 : 64 : lefttype = leftarg->sk_subtype;
1016 [ - + ]: 64 : if (lefttype == InvalidOid)
236 pg@bowt.ie 1017 :UBC 0 : lefttype = opcintype;
236 pg@bowt.ie 1018 :CBC 64 : righttype = rightarg->sk_subtype;
1019 [ - + ]: 64 : if (righttype == InvalidOid)
236 pg@bowt.ie 1020 :UBC 0 : righttype = opcintype;
236 pg@bowt.ie 1021 :CBC 64 : optype = op->sk_subtype;
1022 [ - + ]: 64 : if (optype == InvalidOid)
236 pg@bowt.ie 1023 :UBC 0 : optype = opcintype;
1024 : :
1025 : : /*
1026 : : * If leftarg and rightarg match the types expected for the "op" scankey,
1027 : : * we can use its already-looked-up comparison function.
1028 : : */
236 pg@bowt.ie 1029 [ + + + - ]:CBC 64 : if (lefttype == opcintype && righttype == optype)
1030 : : {
1031 : 61 : *result = DatumGetBool(FunctionCall2Coll(&op->sk_func,
1032 : : op->sk_collation,
1033 : : leftarg->sk_argument,
1034 : : rightarg->sk_argument));
1035 : 61 : return true;
1036 : : }
1037 : :
1038 : : /*
1039 : : * Otherwise, we need to go to the syscache to find the appropriate
1040 : : * operator. (This cannot result in infinite recursion, since no
1041 : : * indexscan initiated by syscache lookup will use cross-data-type
1042 : : * operators.)
1043 : : *
1044 : : * If the sk_strategy was flipped by _bt_fix_scankey_strategy, we have to
1045 : : * un-flip it to get the correct opfamily member.
1046 : : */
1047 : 3 : strat = op->sk_strategy;
1048 [ - + ]: 3 : if (op->sk_flags & SK_BT_DESC)
236 pg@bowt.ie 1049 :UBC 0 : strat = BTCommuteStrategyNumber(strat);
1050 : :
236 pg@bowt.ie 1051 :CBC 3 : cmp_op = get_opfamily_member(rel->rd_opfamily[leftarg->sk_attno - 1],
1052 : : lefttype,
1053 : : righttype,
1054 : : strat);
1055 [ + - ]: 3 : if (OidIsValid(cmp_op))
1056 : : {
1057 : 3 : RegProcedure cmp_proc = get_opcode(cmp_op);
1058 : :
1059 [ + - ]: 3 : if (RegProcedureIsValid(cmp_proc))
1060 : : {
1061 : 3 : *result = DatumGetBool(OidFunctionCall2Coll(cmp_proc,
1062 : : op->sk_collation,
1063 : : leftarg->sk_argument,
1064 : : rightarg->sk_argument));
1065 : 3 : return true;
1066 : : }
1067 : : }
1068 : :
1069 : : /* Can't make the comparison */
236 pg@bowt.ie 1070 :UBC 0 : *result = false; /* suppress compiler warnings */
1071 : 0 : return false;
1072 : : }
1073 : :
1074 : : /*
1075 : : * Compare an array scan key to a scalar scan key, eliminating contradictory
1076 : : * array elements such that the scalar scan key becomes redundant.
1077 : : *
1078 : : * If the opfamily is incomplete we may not be able to determine which
1079 : : * elements are contradictory. When we return true we'll have validly set
1080 : : * *qual_ok, guaranteeing that at least the scalar scan key can be considered
1081 : : * redundant. We return false if the comparison could not be made (caller
1082 : : * must keep both scan keys when this happens).
1083 : : *
1084 : : * Note: it's up to caller to deal with IS [NOT] NULL scan keys, as well as
1085 : : * row comparison scan keys. We only deal with scalar scan keys.
1086 : : */
1087 : : static bool
155 pg@bowt.ie 1088 :CBC 100 : _bt_compare_array_scankey_args(IndexScanDesc scan, ScanKey arraysk, ScanKey skey,
1089 : : FmgrInfo *orderproc, BTArrayKeyInfo *array,
1090 : : bool *qual_ok)
1091 : : {
1092 [ - + ]: 100 : Assert(arraysk->sk_attno == skey->sk_attno);
1093 [ - + ]: 100 : Assert(!(arraysk->sk_flags & (SK_ISNULL | SK_ROW_HEADER | SK_ROW_MEMBER)));
1094 [ + - - + ]: 100 : Assert((arraysk->sk_flags & SK_SEARCHARRAY) &&
1095 : : arraysk->sk_strategy == BTEqualStrategyNumber);
1096 : : /* don't expect to have to deal with NULLs/row comparison scan keys */
1097 [ - + ]: 100 : Assert(!(skey->sk_flags & (SK_ISNULL | SK_ROW_HEADER | SK_ROW_MEMBER)));
1098 [ - + - - ]: 100 : Assert(!(skey->sk_flags & SK_SEARCHARRAY) ||
1099 : : skey->sk_strategy != BTEqualStrategyNumber);
1100 : :
1101 : : /*
1102 : : * Just call the appropriate helper function based on whether it's a SAOP
1103 : : * array or a skip array. Both helpers will set *qual_ok in passing.
1104 : : */
1105 [ + + ]: 100 : if (array->num_elems != -1)
1106 : 15 : return _bt_saoparray_shrink(scan, arraysk, skey, orderproc, array,
1107 : : qual_ok);
1108 : : else
1109 : 85 : return _bt_skiparray_shrink(scan, skey, array, qual_ok);
1110 : : }
1111 : :
1112 : : /*
1113 : : * Preprocessing of SAOP array scan key, used to determine which array
1114 : : * elements are eliminated as contradictory by a non-array scalar key.
1115 : : *
1116 : : * _bt_compare_array_scankey_args helper function.
1117 : : *
1118 : : * Array elements can be eliminated as contradictory when excluded by some
1119 : : * other operator on the same attribute. For example, with an index scan qual
1120 : : * "WHERE a IN (1, 2, 3) AND a < 2", all array elements except the value "1"
1121 : : * are eliminated, and the < scan key is eliminated as redundant. Cases where
1122 : : * every array element is eliminated by a redundant scalar scan key have an
1123 : : * unsatisfiable qual, which we handle by setting *qual_ok=false for caller.
1124 : : */
1125 : : static bool
1126 : 15 : _bt_saoparray_shrink(IndexScanDesc scan, ScanKey arraysk, ScanKey skey,
1127 : : FmgrInfo *orderproc, BTArrayKeyInfo *array, bool *qual_ok)
1128 : : {
236 1129 : 15 : Relation rel = scan->indexRelation;
1130 : 15 : Oid opcintype = rel->rd_opcintype[arraysk->sk_attno - 1];
1131 : 15 : int cmpresult = 0,
1132 : 15 : cmpexact = 0,
1133 : : matchelem,
1134 : 15 : new_nelems = 0;
1135 : : FmgrInfo crosstypeproc;
1136 : 15 : FmgrInfo *orderprocp = orderproc;
1137 : :
1138 [ - + ]: 15 : Assert(array->num_elems > 0);
155 1139 [ - + ]: 15 : Assert(!(arraysk->sk_flags & SK_BT_SKIP));
1140 : :
1141 : : /*
1142 : : * _bt_binsrch_array_skey searches an array for the entry best matching a
1143 : : * datum of opclass input type for the index's attribute (on-disk type).
1144 : : * We can reuse the array's ORDER proc whenever the non-array scan key's
1145 : : * type is a match for the corresponding attribute's input opclass type.
1146 : : * Otherwise, we have to do another ORDER proc lookup so that our call to
1147 : : * _bt_binsrch_array_skey applies the correct comparator.
1148 : : *
1149 : : * Note: we have to support the convention that sk_subtype == InvalidOid
1150 : : * means the opclass input type; this is a hack to simplify life for
1151 : : * ScanKeyInit().
1152 : : */
236 1153 [ + + + - ]: 15 : if (skey->sk_subtype != opcintype && skey->sk_subtype != InvalidOid)
1154 : : {
1155 : : RegProcedure cmp_proc;
1156 : : Oid arraysk_elemtype;
1157 : :
1158 : : /*
1159 : : * Need an ORDER proc lookup to detect redundancy/contradictoriness
1160 : : * with this pair of scankeys.
1161 : : *
1162 : : * Scalar scan key's argument will be passed to _bt_compare_array_skey
1163 : : * as its tupdatum/lefthand argument (rhs arg is for array elements).
1164 : : */
1165 : 3 : arraysk_elemtype = arraysk->sk_subtype;
1166 [ - + ]: 3 : if (arraysk_elemtype == InvalidOid)
236 pg@bowt.ie 1167 :UBC 0 : arraysk_elemtype = rel->rd_opcintype[arraysk->sk_attno - 1];
236 pg@bowt.ie 1168 :CBC 3 : cmp_proc = get_opfamily_proc(rel->rd_opfamily[arraysk->sk_attno - 1],
1169 : : skey->sk_subtype, arraysk_elemtype,
1170 : : BTORDER_PROC);
1171 [ - + ]: 3 : if (!RegProcedureIsValid(cmp_proc))
1172 : : {
1173 : : /* Can't make the comparison */
236 pg@bowt.ie 1174 :UBC 0 : *qual_ok = false; /* suppress compiler warnings */
1175 : 0 : return false;
1176 : : }
1177 : :
1178 : : /* We have all we need to determine redundancy/contradictoriness */
236 pg@bowt.ie 1179 :CBC 3 : orderprocp = &crosstypeproc;
1180 : 3 : fmgr_info(cmp_proc, orderprocp);
1181 : : }
1182 : :
1183 : 15 : matchelem = _bt_binsrch_array_skey(orderprocp, false,
1184 : : NoMovementScanDirection,
1185 : : skey->sk_argument, false, array,
1186 : : arraysk, &cmpresult);
1187 : :
1188 [ + - + + : 15 : switch (skey->sk_strategy)
+ - ]
1189 : : {
1190 : 3 : case BTLessStrategyNumber:
1191 : 3 : cmpexact = 1; /* exclude exact match, if any */
1192 : : /* FALL THRU */
1193 : 3 : case BTLessEqualStrategyNumber:
1194 [ - + ]: 3 : if (cmpresult >= cmpexact)
236 pg@bowt.ie 1195 :UBC 0 : matchelem++;
1196 : : /* Resize, keeping elements from the start of the array */
236 pg@bowt.ie 1197 :CBC 3 : new_nelems = matchelem;
1198 : 3 : break;
1199 : 6 : case BTEqualStrategyNumber:
1200 [ + + ]: 6 : if (cmpresult != 0)
1201 : : {
1202 : : /* qual is unsatisfiable */
1203 : 3 : new_nelems = 0;
1204 : : }
1205 : : else
1206 : : {
1207 : : /* Shift matching element to the start of the array, resize */
1208 : 3 : array->elem_values[0] = array->elem_values[matchelem];
1209 : 3 : new_nelems = 1;
1210 : : }
1211 : 6 : break;
1212 : 3 : case BTGreaterEqualStrategyNumber:
1213 : 3 : cmpexact = 1; /* include exact match, if any */
1214 : : /* FALL THRU */
1215 : 6 : case BTGreaterStrategyNumber:
1216 [ + + ]: 6 : if (cmpresult >= cmpexact)
1217 : 3 : matchelem++;
1218 : : /* Shift matching elements to the start of the array, resize */
1219 : 6 : new_nelems = array->num_elems - matchelem;
1220 : 6 : memmove(array->elem_values, array->elem_values + matchelem,
1221 : : sizeof(Datum) * new_nelems);
1222 : 6 : break;
236 pg@bowt.ie 1223 :UBC 0 : default:
1224 [ # # ]: 0 : elog(ERROR, "unrecognized StrategyNumber: %d",
1225 : : (int) skey->sk_strategy);
1226 : : break;
1227 : : }
1228 : :
236 pg@bowt.ie 1229 [ - + ]:CBC 15 : Assert(new_nelems >= 0);
1230 [ - + ]: 15 : Assert(new_nelems <= array->num_elems);
1231 : :
1232 : 15 : array->num_elems = new_nelems;
1233 : 15 : *qual_ok = new_nelems > 0;
1234 : :
1235 : 15 : return true;
1236 : : }
1237 : :
1238 : : /*
1239 : : * Preprocessing of skip array scan key, used to determine redundancy against
1240 : : * a non-array scalar scan key (must be an inequality).
1241 : : *
1242 : : * _bt_compare_array_scankey_args helper function.
1243 : : *
1244 : : * Skip arrays work by procedurally generating their elements as needed, so we
1245 : : * just store the inequality as the skip array's low_compare or high_compare
1246 : : * (except when there's already a more restrictive low_compare/high_compare).
1247 : : * The array's final elements are the range of values that still satisfy the
1248 : : * array's final low_compare and high_compare.
1249 : : */
1250 : : static bool
155 1251 : 85 : _bt_skiparray_shrink(IndexScanDesc scan, ScanKey skey, BTArrayKeyInfo *array,
1252 : : bool *qual_ok)
1253 : : {
1254 : : bool test_result;
1255 : :
1256 [ - + ]: 85 : Assert(array->num_elems == -1);
1257 : :
1258 : : /*
1259 : : * Array's index attribute will be constrained by a strict operator/key.
1260 : : * Array must not "contain a NULL element" (i.e. the scan must not apply
1261 : : * "IS NULL" qual when it reaches the end of the index that stores NULLs).
1262 : : */
1263 : 85 : array->null_elem = false;
1264 : 85 : *qual_ok = true;
1265 : :
1266 : : /*
1267 : : * Consider if we should treat caller's scalar scan key as the skip
1268 : : * array's high_compare or low_compare.
1269 : : *
1270 : : * In general the current array element must either be a copy of a value
1271 : : * taken from an index tuple, or a derivative value generated by opclass's
1272 : : * skip support function. That way the scan can always safely assume that
1273 : : * it's okay to use the only-input-opclass-type proc from so->orderProcs[]
1274 : : * (they can be cross-type with SAOP arrays, but never with skip arrays).
1275 : : *
1276 : : * This approach is enabled by MINVAL/MAXVAL sentinel key markings, which
1277 : : * can be thought of as representing either the lowest or highest matching
1278 : : * array element (excluding the NULL element, where applicable, though as
1279 : : * just discussed it isn't applicable to this range skip array anyway).
1280 : : * Array keys marked MINVAL/MAXVAL never have a valid datum in their
1281 : : * sk_argument field. The scan directly applies the array's low_compare
1282 : : * key when it encounters MINVAL in the array key proper (just as it
1283 : : * applies high_compare when it sees MAXVAL set in the array key proper).
1284 : : * The scan must never use the array's so->orderProcs[] proc against
1285 : : * low_compare's/high_compare's sk_argument, either (so->orderProcs[] is
1286 : : * only intended to be used with rhs datums from the array proper/index).
1287 : : */
1288 [ + + - ]: 85 : switch (skey->sk_strategy)
1289 : : {
1290 : 44 : case BTLessStrategyNumber:
1291 : : case BTLessEqualStrategyNumber:
1292 [ + + ]: 44 : if (array->high_compare)
1293 : : {
1294 : : /* replace existing high_compare with caller's key? */
1295 [ - + ]: 3 : if (!_bt_compare_scankey_args(scan, array->high_compare, skey,
1296 : : array->high_compare, NULL, NULL,
1297 : : &test_result))
155 pg@bowt.ie 1298 :UBC 0 : return false; /* can't determine more restrictive key */
1299 : :
155 pg@bowt.ie 1300 [ + - ]:CBC 3 : if (!test_result)
1301 : 3 : return true; /* no, just discard caller's key */
1302 : :
1303 : : /* yes, replace existing high_compare with caller's key */
1304 : : }
1305 : :
1306 : : /* caller's key becomes skip array's high_compare */
1307 : 41 : array->high_compare = skey;
1308 : 41 : break;
1309 : 41 : case BTGreaterEqualStrategyNumber:
1310 : : case BTGreaterStrategyNumber:
1311 [ + + ]: 41 : if (array->low_compare)
1312 : : {
1313 : : /* replace existing low_compare with caller's key? */
1314 [ - + ]: 3 : if (!_bt_compare_scankey_args(scan, array->low_compare, skey,
1315 : : array->low_compare, NULL, NULL,
1316 : : &test_result))
155 pg@bowt.ie 1317 :UBC 0 : return false; /* can't determine more restrictive key */
1318 : :
155 pg@bowt.ie 1319 [ - + ]:CBC 3 : if (!test_result)
155 pg@bowt.ie 1320 :UBC 0 : return true; /* no, just discard caller's key */
1321 : :
1322 : : /* yes, replace existing low_compare with caller's key */
1323 : : }
1324 : :
1325 : : /* caller's key becomes skip array's low_compare */
155 pg@bowt.ie 1326 :CBC 41 : array->low_compare = skey;
1327 : 41 : break;
155 pg@bowt.ie 1328 :UBC 0 : case BTEqualStrategyNumber:
1329 : : default:
1330 [ # # ]: 0 : elog(ERROR, "unrecognized StrategyNumber: %d",
1331 : : (int) skey->sk_strategy);
1332 : : break;
1333 : : }
1334 : :
155 pg@bowt.ie 1335 :CBC 82 : return true;
1336 : : }
1337 : :
1338 : : /*
1339 : : * Applies the opfamily's skip support routine to convert the skip array's >
1340 : : * low_compare key (if any) into a >= key, and to convert its < high_compare
1341 : : * key (if any) into a <= key. Decrements the high_compare key's sk_argument,
1342 : : * and/or increments the low_compare key's sk_argument (also adjusts their
1343 : : * operator strategies, while changing the operator as appropriate).
1344 : : *
1345 : : * This optional optimization reduces the number of descents required within
1346 : : * _bt_first. Whenever _bt_first is called with a skip array whose current
1347 : : * array element is the sentinel value MINVAL, using a transformed >= key
1348 : : * instead of using the original > key makes it safe to include lower-order
1349 : : * scan keys in the insertion scan key (there must be lower-order scan keys
1350 : : * after the skip array). We will avoid an extra _bt_first to find the first
1351 : : * value in the index > sk_argument -- at least when the first real matching
1352 : : * value in the index happens to be an exact match for the sk_argument value
1353 : : * that we produced here by incrementing the original input key's sk_argument.
1354 : : * (Backwards scans derive the same benefit when they encounter the sentinel
1355 : : * value MAXVAL, by converting the high_compare key from < to <=.)
1356 : : *
1357 : : * Note: The transformation is only correct when it cannot allow the scan to
1358 : : * overlook matching tuples, but we don't have enough semantic information to
1359 : : * safely make sure that can't happen during scans with cross-type operators.
1360 : : * That's why we'll never apply the transformation in cross-type scenarios.
1361 : : * For example, if we attempted to convert "sales_ts > '2024-01-01'::date"
1362 : : * into "sales_ts >= '2024-01-02'::date" given a "sales_ts" attribute whose
1363 : : * input opclass is timestamp_ops, the scan would overlook almost all (or all)
1364 : : * tuples for sales that fell on '2024-01-01'.
1365 : : *
1366 : : * Note: We can safely modify array->low_compare/array->high_compare in place
1367 : : * because they just point to copies of our scan->keyData[] input scan keys
1368 : : * (namely the copies returned by _bt_preprocess_array_keys to be used as
1369 : : * input into the standard preprocessing steps in _bt_preprocess_keys).
1370 : : * Everything will be reset if there's a rescan.
1371 : : */
1372 : : static void
1373 : 39 : _bt_skiparray_strat_adjust(IndexScanDesc scan, ScanKey arraysk,
1374 : : BTArrayKeyInfo *array)
1375 : : {
1376 : 39 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1377 : : MemoryContext oldContext;
1378 : :
1379 : : /*
1380 : : * Called last among all preprocessing steps, when the skip array's final
1381 : : * low_compare and high_compare have both been chosen
1382 : : */
1383 [ - + ]: 39 : Assert(arraysk->sk_flags & SK_BT_SKIP);
1384 [ + - + - : 39 : Assert(array->num_elems == -1 && !array->null_elem && array->sksup);
- + ]
1385 : :
1386 : 39 : oldContext = MemoryContextSwitchTo(so->arrayContext);
1387 : :
1388 [ + + ]: 39 : if (array->high_compare &&
1389 [ + + ]: 12 : array->high_compare->sk_strategy == BTLessStrategyNumber)
1390 : 9 : _bt_skiparray_strat_decrement(scan, arraysk, array);
1391 : :
1392 [ + + ]: 39 : if (array->low_compare &&
1393 [ + + ]: 9 : array->low_compare->sk_strategy == BTGreaterStrategyNumber)
1394 : 6 : _bt_skiparray_strat_increment(scan, arraysk, array);
1395 : :
1396 : 39 : MemoryContextSwitchTo(oldContext);
1397 : 39 : }
1398 : :
1399 : : /*
1400 : : * Convert skip array's > low_compare key into a >= key
1401 : : */
1402 : : static void
1403 : 9 : _bt_skiparray_strat_decrement(IndexScanDesc scan, ScanKey arraysk,
1404 : : BTArrayKeyInfo *array)
1405 : : {
1406 : 9 : Relation rel = scan->indexRelation;
1407 : 9 : Oid opfamily = rel->rd_opfamily[arraysk->sk_attno - 1],
1408 : 9 : opcintype = rel->rd_opcintype[arraysk->sk_attno - 1],
1409 : : leop;
1410 : : RegProcedure cmp_proc;
1411 : 9 : ScanKey high_compare = array->high_compare;
1412 : 9 : Datum orig_sk_argument = high_compare->sk_argument,
1413 : : new_sk_argument;
1414 : : bool uflow;
1415 : :
1416 [ - + ]: 9 : Assert(high_compare->sk_strategy == BTLessStrategyNumber);
1417 : :
1418 : : /*
1419 : : * Only perform the transformation when the operator type matches the
1420 : : * index attribute's input opclass type
1421 : : */
1422 [ - + ]: 9 : if (high_compare->sk_subtype != opcintype &&
155 pg@bowt.ie 1423 [ # # ]:UBC 0 : high_compare->sk_subtype != InvalidOid)
1424 : 0 : return;
1425 : :
1426 : : /* Decrement, handling underflow by marking the qual unsatisfiable */
155 pg@bowt.ie 1427 :CBC 9 : new_sk_argument = array->sksup->decrement(rel, orig_sk_argument, &uflow);
1428 [ - + ]: 9 : if (uflow)
1429 : : {
155 pg@bowt.ie 1430 :UBC 0 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1431 : :
1432 : 0 : so->qual_ok = false;
1433 : 0 : return;
1434 : : }
1435 : :
1436 : : /* Look up <= operator (might fail) */
155 pg@bowt.ie 1437 :CBC 9 : leop = get_opfamily_member(opfamily, opcintype, opcintype,
1438 : : BTLessEqualStrategyNumber);
1439 [ - + ]: 9 : if (!OidIsValid(leop))
155 pg@bowt.ie 1440 :UBC 0 : return;
155 pg@bowt.ie 1441 :CBC 9 : cmp_proc = get_opcode(leop);
1442 [ + - ]: 9 : if (RegProcedureIsValid(cmp_proc))
1443 : : {
1444 : : /* Transform < high_compare key into <= key */
1445 : 9 : fmgr_info(cmp_proc, &high_compare->sk_func);
1446 : 9 : high_compare->sk_argument = new_sk_argument;
1447 : 9 : high_compare->sk_strategy = BTLessEqualStrategyNumber;
1448 : : }
1449 : : }
1450 : :
1451 : : /*
1452 : : * Convert skip array's < low_compare key into a <= key
1453 : : */
1454 : : static void
1455 : 6 : _bt_skiparray_strat_increment(IndexScanDesc scan, ScanKey arraysk,
1456 : : BTArrayKeyInfo *array)
1457 : : {
1458 : 6 : Relation rel = scan->indexRelation;
1459 : 6 : Oid opfamily = rel->rd_opfamily[arraysk->sk_attno - 1],
1460 : 6 : opcintype = rel->rd_opcintype[arraysk->sk_attno - 1],
1461 : : geop;
1462 : : RegProcedure cmp_proc;
1463 : 6 : ScanKey low_compare = array->low_compare;
1464 : 6 : Datum orig_sk_argument = low_compare->sk_argument,
1465 : : new_sk_argument;
1466 : : bool oflow;
1467 : :
1468 [ - + ]: 6 : Assert(low_compare->sk_strategy == BTGreaterStrategyNumber);
1469 : :
1470 : : /*
1471 : : * Only perform the transformation when the operator type matches the
1472 : : * index attribute's input opclass type
1473 : : */
1474 [ - + ]: 6 : if (low_compare->sk_subtype != opcintype &&
155 pg@bowt.ie 1475 [ # # ]:UBC 0 : low_compare->sk_subtype != InvalidOid)
1476 : 0 : return;
1477 : :
1478 : : /* Increment, handling overflow by marking the qual unsatisfiable */
155 pg@bowt.ie 1479 :CBC 6 : new_sk_argument = array->sksup->increment(rel, orig_sk_argument, &oflow);
1480 [ - + ]: 6 : if (oflow)
1481 : : {
155 pg@bowt.ie 1482 :UBC 0 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1483 : :
1484 : 0 : so->qual_ok = false;
1485 : 0 : return;
1486 : : }
1487 : :
1488 : : /* Look up >= operator (might fail) */
155 pg@bowt.ie 1489 :CBC 6 : geop = get_opfamily_member(opfamily, opcintype, opcintype,
1490 : : BTGreaterEqualStrategyNumber);
1491 [ - + ]: 6 : if (!OidIsValid(geop))
155 pg@bowt.ie 1492 :UBC 0 : return;
155 pg@bowt.ie 1493 :CBC 6 : cmp_proc = get_opcode(geop);
1494 [ + - ]: 6 : if (RegProcedureIsValid(cmp_proc))
1495 : : {
1496 : : /* Transform > low_compare key into >= key */
1497 : 6 : fmgr_info(cmp_proc, &low_compare->sk_func);
1498 : 6 : low_compare->sk_argument = new_sk_argument;
1499 : 6 : low_compare->sk_strategy = BTGreaterEqualStrategyNumber;
1500 : : }
1501 : : }
1502 : :
1503 : : /*
1504 : : * _bt_unmark_keys() -- make superfluous required keys nonrequired after all
1505 : : *
1506 : : * When _bt_preprocess_keys fails to eliminate one or more redundant keys, it
1507 : : * calls here to make sure that no index attribute has more than one > or >=
1508 : : * key marked required, and no more than one required < or <= key. Attributes
1509 : : * with = keys will always get one = key as their required key. All other
1510 : : * keys that were initially marked required get "unmarked" here. That way,
1511 : : * _bt_first and _bt_checkkeys will reliably agree on which keys to use to
1512 : : * start and/or to end the scan.
1513 : : *
1514 : : * We also relocate keys that become/started out nonrequired to the end of
1515 : : * so->keyData[]. That way, _bt_first and _bt_checkkeys cannot fail to reach
1516 : : * a required key due to some earlier nonrequired key getting in the way.
1517 : : *
1518 : : * Only call here when _bt_compare_scankey_args returned false at least once
1519 : : * (otherwise, calling here will just waste cycles).
1520 : : */
1521 : : static void
66 1522 : 3 : _bt_unmark_keys(IndexScanDesc scan, int *keyDataMap)
1523 : : {
1524 : 3 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1525 : : AttrNumber attno;
1526 : : bool *unmarkikey;
1527 : : int nunmark,
1528 : : nunmarked,
1529 : : nkept,
1530 : : firsti;
1531 : : ScanKey keepKeys,
1532 : : unmarkKeys;
1533 : 3 : FmgrInfo *keepOrderProcs = NULL,
1534 : 3 : *unmarkOrderProcs = NULL;
1535 : : bool haveReqEquals,
1536 : : haveReqForward,
1537 : : haveReqBackward;
1538 : :
1539 : : /*
1540 : : * Do an initial pass over so->keyData[] that determines which keys to
1541 : : * keep as required. We expect so->keyData[] to still be in attribute
1542 : : * order when we're called (though we don't expect any particular order
1543 : : * among each attribute's keys).
1544 : : *
1545 : : * When both equality and inequality keys remain on a single attribute, we
1546 : : * *must* make sure that exactly one of the equalities remains required.
1547 : : * Any requiredness markings that we might leave on later keys/attributes
1548 : : * are predicated on there being required = keys on all prior columns.
1549 : : */
1550 : 3 : unmarkikey = palloc0(so->numberOfKeys * sizeof(bool));
1551 : 3 : nunmark = 0;
1552 : :
1553 : : /* Set things up for first key's attribute */
1554 : 3 : attno = so->keyData[0].sk_attno;
1555 : 3 : firsti = 0;
1556 : 3 : haveReqEquals = false;
1557 : 3 : haveReqForward = false;
1558 : 3 : haveReqBackward = false;
1559 [ + + ]: 15 : for (int i = 0; i < so->numberOfKeys; i++)
1560 : : {
1561 : 12 : ScanKey origkey = &so->keyData[i];
1562 : :
1563 [ + + ]: 12 : if (origkey->sk_attno != attno)
1564 : : {
1565 : : /* Reset for next attribute */
1566 : 6 : attno = origkey->sk_attno;
1567 : 6 : firsti = i;
1568 : :
1569 : 6 : haveReqEquals = false;
1570 : 6 : haveReqForward = false;
1571 : 6 : haveReqBackward = false;
1572 : : }
1573 : :
1574 : : /* Equalities get priority over inequalities */
1575 [ - + ]: 12 : if (haveReqEquals)
1576 : : {
1577 : : /*
1578 : : * We already found the first "=" key for this attribute. We've
1579 : : * already decided that all its other keys will be unmarked.
1580 : : */
66 pg@bowt.ie 1581 [ # # ]:UBC 0 : Assert(!(origkey->sk_flags & SK_SEARCHNULL));
1582 : 0 : unmarkikey[i] = true;
1583 : 0 : nunmark++;
1584 : 0 : continue;
1585 : : }
66 pg@bowt.ie 1586 [ + + ]:CBC 12 : else if ((origkey->sk_flags & SK_BT_REQFWD) &&
1587 [ + - ]: 9 : (origkey->sk_flags & SK_BT_REQBKWD))
1588 : : {
1589 : : /*
1590 : : * Found the first "=" key for attno. All other attno keys will
1591 : : * be unmarked.
1592 : : */
1593 [ - + ]: 9 : Assert(origkey->sk_strategy == BTEqualStrategyNumber);
1594 : :
1595 : 9 : haveReqEquals = true;
1596 [ + + ]: 12 : for (int j = firsti; j < i; j++)
1597 : : {
1598 : : /* Unmark any prior inequality keys on attno after all */
1599 [ + - ]: 3 : if (!unmarkikey[j])
1600 : : {
1601 : 3 : unmarkikey[j] = true;
1602 : 3 : nunmark++;
1603 : : }
1604 : : }
1605 : 9 : continue;
1606 : : }
1607 : :
1608 : : /* Deal with inequalities next */
1609 [ - + - - ]: 3 : if ((origkey->sk_flags & SK_BT_REQFWD) && !haveReqForward)
1610 : : {
66 pg@bowt.ie 1611 :UBC 0 : haveReqForward = true;
1612 : 0 : continue;
1613 : : }
66 pg@bowt.ie 1614 [ + - + - ]:CBC 3 : else if ((origkey->sk_flags & SK_BT_REQBKWD) && !haveReqBackward)
1615 : : {
1616 : 3 : haveReqBackward = true;
1617 : 3 : continue;
1618 : : }
1619 : :
1620 : : /*
1621 : : * We have either a redundant inequality key that will be unmarked, or
1622 : : * we have a key that wasn't marked required in the first place
1623 : : */
66 pg@bowt.ie 1624 :UBC 0 : unmarkikey[i] = true;
1625 : 0 : nunmark++;
1626 : : }
1627 : :
1628 : : /* Should only be called when _bt_compare_scankey_args reported failure */
66 pg@bowt.ie 1629 [ - + ]:CBC 3 : Assert(nunmark > 0);
1630 : :
1631 : : /*
1632 : : * Next, allocate temp arrays: one for required keys that'll remain
1633 : : * required, the other for all remaining keys
1634 : : */
1635 : 3 : unmarkKeys = palloc(nunmark * sizeof(ScanKeyData));
1636 : 3 : keepKeys = palloc((so->numberOfKeys - nunmark) * sizeof(ScanKeyData));
1637 : 3 : nunmarked = 0;
1638 : 3 : nkept = 0;
1639 [ + - ]: 3 : if (so->numArrayKeys)
1640 : : {
1641 : 3 : unmarkOrderProcs = palloc(nunmark * sizeof(FmgrInfo));
1642 : 3 : keepOrderProcs = palloc((so->numberOfKeys - nunmark) * sizeof(FmgrInfo));
1643 : : }
1644 : :
1645 : : /*
1646 : : * Next, copy the contents of so->keyData[] into the appropriate temp
1647 : : * array.
1648 : : *
1649 : : * Scans with = array keys need us to maintain invariants around the order
1650 : : * of so->orderProcs[] and so->arrayKeys[] relative to so->keyData[]. See
1651 : : * _bt_preprocess_array_keys_final for a full explanation.
1652 : : */
1653 [ + + ]: 15 : for (int i = 0; i < so->numberOfKeys; i++)
1654 : : {
1655 : 12 : ScanKey origkey = &so->keyData[i];
1656 : : ScanKey unmark;
1657 : :
1658 [ + + ]: 12 : if (!unmarkikey[i])
1659 : : {
1660 : : /*
1661 : : * Key gets to keep its original requiredness markings.
1662 : : *
1663 : : * Key will stay in its original position, unless we're going to
1664 : : * unmark an earlier key (in which case this key gets moved back).
1665 : : */
1666 : 9 : memcpy(keepKeys + nkept, origkey, sizeof(ScanKeyData));
1667 : :
1668 [ + - ]: 9 : if (so->numArrayKeys)
1669 : : {
1670 : 9 : keyDataMap[i] = nkept;
1671 : 9 : memcpy(keepOrderProcs + nkept, &so->orderProcs[i],
1672 : : sizeof(FmgrInfo));
1673 : : }
1674 : :
1675 : 9 : nkept++;
1676 : 9 : continue;
1677 : : }
1678 : :
1679 : : /*
1680 : : * Key will be unmarked as needed, and moved to the end of the array,
1681 : : * next to other keys that will become (or always were) nonrequired
1682 : : */
1683 : 3 : unmark = unmarkKeys + nunmarked;
1684 : 3 : memcpy(unmark, origkey, sizeof(ScanKeyData));
1685 : :
1686 [ + - ]: 3 : if (so->numArrayKeys)
1687 : : {
1688 : 3 : keyDataMap[i] = (so->numberOfKeys - nunmark) + nunmarked;
1689 : 3 : memcpy(&unmarkOrderProcs[nunmarked], &so->orderProcs[i],
1690 : : sizeof(FmgrInfo));
1691 : : }
1692 : :
1693 : : /*
1694 : : * Preprocessing only generates skip arrays when it knows that they'll
1695 : : * be the only required = key on the attr. We'll never unmark them.
1696 : : */
1697 [ - + ]: 3 : Assert(!(unmark->sk_flags & SK_BT_SKIP));
1698 : :
1699 : : /*
1700 : : * Also shouldn't have to unmark an IS NULL or an IS NOT NULL key.
1701 : : * They aren't cross-type, so an incomplete opfamily can't matter.
1702 : : */
1703 [ - + - - ]: 3 : Assert(!(unmark->sk_flags & SK_ISNULL) ||
1704 : : !(unmark->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)));
1705 : :
1706 : : /* Clear requiredness flags on redundant key (and on any subkeys) */
1707 : 3 : unmark->sk_flags &= ~(SK_BT_REQFWD | SK_BT_REQBKWD);
1708 [ + - ]: 3 : if (unmark->sk_flags & SK_ROW_HEADER)
1709 : : {
1710 : 3 : ScanKey subkey = (ScanKey) DatumGetPointer(unmark->sk_argument);
1711 : :
1712 [ + - ]: 3 : Assert(subkey->sk_strategy == unmark->sk_strategy);
1713 : : for (;;)
1714 : : {
1715 [ - + ]: 6 : Assert(subkey->sk_flags & SK_ROW_MEMBER);
1716 : 6 : subkey->sk_flags &= ~(SK_BT_REQFWD | SK_BT_REQBKWD);
1717 [ + + ]: 6 : if (subkey->sk_flags & SK_ROW_END)
1718 : 3 : break;
1719 : 3 : subkey++;
1720 : : }
1721 : : }
1722 : :
1723 : 3 : nunmarked++;
1724 : : }
1725 : :
1726 : : /* Copy both temp arrays back into so->keyData[] to reorder */
1727 [ - + ]: 3 : Assert(nkept == so->numberOfKeys - nunmark);
1728 [ - + ]: 3 : Assert(nunmarked == nunmark);
1729 : 3 : memcpy(so->keyData, keepKeys, sizeof(ScanKeyData) * nkept);
1730 : 3 : memcpy(so->keyData + nkept, unmarkKeys, sizeof(ScanKeyData) * nunmarked);
1731 : :
1732 : : /* Done with temp arrays */
1733 : 3 : pfree(unmarkikey);
1734 : 3 : pfree(keepKeys);
1735 : 3 : pfree(unmarkKeys);
1736 : :
1737 : : /*
1738 : : * Now copy so->orderProcs[] temp entries needed by scans with = array
1739 : : * keys back (just like with the so->keyData[] temp arrays)
1740 : : */
1741 [ + - ]: 3 : if (so->numArrayKeys)
1742 : : {
1743 : 3 : memcpy(so->orderProcs, keepOrderProcs, sizeof(FmgrInfo) * nkept);
1744 : 3 : memcpy(so->orderProcs + nkept, unmarkOrderProcs,
1745 : : sizeof(FmgrInfo) * nunmarked);
1746 : :
1747 : : /* Also fix-up array->scan_key references */
1748 [ + + ]: 9 : for (int arridx = 0; arridx < so->numArrayKeys; arridx++)
1749 : : {
1750 : 6 : BTArrayKeyInfo *array = &so->arrayKeys[arridx];
1751 : :
1752 : 6 : array->scan_key = keyDataMap[array->scan_key];
1753 : : }
1754 : :
1755 : : /*
1756 : : * Sort so->arrayKeys[] based on its new BTArrayKeyInfo.scan_key
1757 : : * offsets, so that its order matches so->keyData[] order as expected
1758 : : */
1759 : 3 : qsort(so->arrayKeys, so->numArrayKeys, sizeof(BTArrayKeyInfo),
1760 : : _bt_reorder_array_cmp);
1761 : :
1762 : : /* Done with temp arrays */
1763 : 3 : pfree(unmarkOrderProcs);
1764 : 3 : pfree(keepOrderProcs);
1765 : : }
1766 : 3 : }
1767 : :
1768 : : /*
1769 : : * qsort comparator for reordering so->arrayKeys[] BTArrayKeyInfo entries
1770 : : */
1771 : : static int
1772 : 3 : _bt_reorder_array_cmp(const void *a, const void *b)
1773 : : {
1774 : 3 : BTArrayKeyInfo *arraya = (BTArrayKeyInfo *) a;
1775 : 3 : BTArrayKeyInfo *arrayb = (BTArrayKeyInfo *) b;
1776 : :
1777 : 3 : return pg_cmp_s32(arraya->scan_key, arrayb->scan_key);
1778 : : }
1779 : :
1780 : : /*
1781 : : * _bt_preprocess_array_keys() -- Preprocess SK_SEARCHARRAY scan keys
1782 : : *
1783 : : * If there are any SK_SEARCHARRAY scan keys, deconstruct the array(s) and
1784 : : * set up BTArrayKeyInfo info for each one that is an equality-type key.
1785 : : * Returns modified scan keys as input for further, standard preprocessing.
1786 : : *
1787 : : * Currently we perform two kinds of preprocessing to deal with redundancies.
1788 : : * For inequality array keys, it's sufficient to find the extreme element
1789 : : * value and replace the whole array with that scalar value. This eliminates
1790 : : * all but one array element as redundant. Similarly, we are capable of
1791 : : * "merging together" multiple equality array keys (from two or more input
1792 : : * scan keys) into a single output scan key containing only the intersecting
1793 : : * array elements. This can eliminate many redundant array elements, as well
1794 : : * as eliminating whole array scan keys as redundant. It can also allow us to
1795 : : * detect contradictory quals.
1796 : : *
1797 : : * Caller must pass *new_numberOfKeys to give us a way to change the number of
1798 : : * scan keys that caller treats as input to standard preprocessing steps. The
1799 : : * returned array is smaller than scan->keyData[] when we could eliminate a
1800 : : * redundant array scan key (redundant with another array scan key). It is
1801 : : * convenient for _bt_preprocess_keys caller to have to deal with no more than
1802 : : * one equality strategy array scan key per index attribute. We'll always be
1803 : : * able to set things up that way when complete opfamilies are used.
1804 : : *
1805 : : * We're also responsible for generating skip arrays (and their associated
1806 : : * scan keys) here. This enables skip scan. We do this for index attributes
1807 : : * that initially lacked an equality condition within scan->keyData[], iff
1808 : : * doing so allows a later scan key (that was passed to us in scan->keyData[])
1809 : : * to be marked required by our _bt_preprocess_keys caller.
1810 : : *
1811 : : * We set the scan key references from the scan's BTArrayKeyInfo info array to
1812 : : * offsets into the temp modified input array returned to caller. Scans that
1813 : : * have array keys should call _bt_preprocess_array_keys_final when standard
1814 : : * preprocessing steps are complete. This will convert the scan key offset
1815 : : * references into references to the scan's so->keyData[] output scan keys.
1816 : : *
1817 : : * Note: the reason we need to return a temp scan key array, rather than just
1818 : : * modifying scan->keyData[], is that callers are permitted to call btrescan
1819 : : * without supplying a new set of scankey data. Certain other preprocessing
1820 : : * routines (e.g., _bt_fix_scankey_strategy) _can_ modify scan->keyData[], but
1821 : : * we can't make that work here because our modifications are non-idempotent.
1822 : : */
1823 : : static ScanKey
236 1824 : 6992386 : _bt_preprocess_array_keys(IndexScanDesc scan, int *new_numberOfKeys)
1825 : : {
1826 : 6992386 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1827 : 6992386 : Relation rel = scan->indexRelation;
1828 : 6992386 : int16 *indoption = rel->rd_indoption;
1829 : : Oid skip_eq_ops[INDEX_MAX_KEYS];
1830 : : int numArrayKeys,
1831 : : numSkipArrayKeys,
1832 : : numArrayKeyData;
155 1833 : 6992386 : AttrNumber attno_skip = 1;
236 1834 : 6992386 : int origarrayatt = InvalidAttrNumber,
1835 : 6992386 : origarraykey = -1;
1836 : 6992386 : Oid origelemtype = InvalidOid;
1837 : : MemoryContext oldContext;
1838 : : ScanKey arrayKeyData; /* modified copy of scan->keyData */
1839 : :
1840 : : /*
1841 : : * Check the number of input array keys within scan->keyData[] input keys
1842 : : * (also checks if we should add extra skip arrays based on input keys)
1843 : : */
155 1844 : 6992386 : numArrayKeys = _bt_num_array_keys(scan, skip_eq_ops, &numSkipArrayKeys);
1845 : :
1846 : : /* Quit if nothing to do. */
236 1847 [ + + ]: 6992386 : if (numArrayKeys == 0)
1848 : 6956855 : return NULL;
1849 : :
1850 : : /*
1851 : : * Estimated final size of arrayKeyData[] array we'll return to our caller
1852 : : * is the size of the original scan->keyData[] input array, plus space for
1853 : : * any additional skip array scan keys we'll need to generate below
1854 : : */
155 1855 : 35531 : numArrayKeyData = scan->numberOfKeys + numSkipArrayKeys;
1856 : :
1857 : : /*
1858 : : * Make a scan-lifespan context to hold array-associated data, or reset it
1859 : : * if we already have one from a previous rescan cycle.
1860 : : */
236 1861 [ + + ]: 35531 : if (so->arrayContext == NULL)
1862 : 2283 : so->arrayContext = AllocSetContextCreate(CurrentMemoryContext,
1863 : : "BTree array context",
1864 : : ALLOCSET_SMALL_SIZES);
1865 : : else
1866 : 33248 : MemoryContextReset(so->arrayContext);
1867 : :
1868 : 35531 : oldContext = MemoryContextSwitchTo(so->arrayContext);
1869 : :
1870 : : /* Create output scan keys in the workspace context */
155 1871 : 35531 : arrayKeyData = (ScanKey) palloc(numArrayKeyData * sizeof(ScanKeyData));
1872 : :
1873 : : /* Allocate space for per-array data in the workspace context */
1874 : 35531 : so->skipScan = (numSkipArrayKeys > 0);
236 1875 : 35531 : so->arrayKeys = (BTArrayKeyInfo *) palloc(numArrayKeys * sizeof(BTArrayKeyInfo));
1876 : :
1877 : : /* Allocate space for ORDER procs used to help _bt_checkkeys */
155 1878 : 35531 : so->orderProcs = (FmgrInfo *) palloc(numArrayKeyData * sizeof(FmgrInfo));
1879 : :
236 1880 : 35531 : numArrayKeys = 0;
155 1881 : 35531 : numArrayKeyData = 0;
1882 [ + + ]: 71901 : for (int input_ikey = 0; input_ikey < scan->numberOfKeys; input_ikey++)
1883 : : {
1884 : 36379 : ScanKey inkey = scan->keyData + input_ikey,
1885 : : cur;
1886 : : FmgrInfo sortproc;
236 1887 : 36379 : FmgrInfo *sortprocp = &sortproc;
1888 : : Oid elemtype;
1889 : : bool reverse;
1890 : : ArrayType *arrayval;
1891 : : int16 elmlen;
1892 : : bool elmbyval;
1893 : : char elmalign;
1894 : : int num_elems;
1895 : : Datum *elem_values;
1896 : : bool *elem_nulls;
1897 : : int num_nonnulls;
1898 : :
1899 : : /* set up next output scan key */
155 1900 : 36379 : cur = &arrayKeyData[numArrayKeyData];
1901 : :
1902 : : /* Backfill skip arrays for attrs < or <= input key's attr? */
1903 [ + + + + ]: 38257 : while (numSkipArrayKeys && attno_skip <= inkey->sk_attno)
1904 : : {
1905 : 2293 : Oid opfamily = rel->rd_opfamily[attno_skip - 1];
1906 : 2293 : Oid opcintype = rel->rd_opcintype[attno_skip - 1];
1907 : 2293 : Oid collation = rel->rd_indcollation[attno_skip - 1];
1908 : 2293 : Oid eq_op = skip_eq_ops[attno_skip - 1];
1909 : : CompactAttribute *attr;
1910 : : RegProcedure cmp_proc;
1911 : :
1912 [ + + ]: 2293 : if (!OidIsValid(eq_op))
1913 : : {
1914 : : /*
1915 : : * Attribute already has an = input key, so don't output a
1916 : : * skip array for attno_skip. Just copy attribute's = input
1917 : : * key into arrayKeyData[] once outside this inner loop.
1918 : : *
1919 : : * Note: When we get here there must be a later attribute that
1920 : : * lacks an equality input key, and still needs a skip array
1921 : : * (if there wasn't then numSkipArrayKeys would be 0 by now).
1922 : : */
1923 [ - + ]: 415 : Assert(attno_skip == inkey->sk_attno);
1924 : : /* inkey can't be last input key to be marked required: */
1925 [ - + ]: 415 : Assert(input_ikey < scan->numberOfKeys - 1);
1926 : : #if 0
1927 : : /* Could be a redundant input scan key, so can't do this: */
1928 : : Assert(inkey->sk_strategy == BTEqualStrategyNumber ||
1929 : : (inkey->sk_flags & SK_SEARCHNULL));
1930 : : #endif
1931 : :
1932 : 415 : attno_skip++;
1933 : 415 : break;
1934 : : }
1935 : :
1936 : 1878 : cmp_proc = get_opcode(eq_op);
1937 [ - + ]: 1878 : if (!RegProcedureIsValid(cmp_proc))
155 pg@bowt.ie 1938 [ # # ]:UBC 0 : elog(ERROR, "missing oprcode for skipping equals operator %u", eq_op);
1939 : :
155 pg@bowt.ie 1940 :CBC 1878 : ScanKeyEntryInitialize(cur,
1941 : : SK_SEARCHARRAY | SK_BT_SKIP, /* flags */
1942 : : attno_skip, /* skipped att number */
1943 : : BTEqualStrategyNumber, /* equality strategy */
1944 : : InvalidOid, /* opclass input subtype */
1945 : : collation, /* index column's collation */
1946 : : cmp_proc, /* equality operator's proc */
1947 : : (Datum) 0); /* constant */
1948 : :
1949 : : /* Initialize generic BTArrayKeyInfo fields */
1950 : 1878 : so->arrayKeys[numArrayKeys].scan_key = numArrayKeyData;
1951 : 1878 : so->arrayKeys[numArrayKeys].num_elems = -1;
1952 : :
1953 : : /* Initialize skip array specific BTArrayKeyInfo fields */
1954 : 1878 : attr = TupleDescCompactAttr(RelationGetDescr(rel), attno_skip - 1);
1955 : 1878 : reverse = (indoption[attno_skip - 1] & INDOPTION_DESC) != 0;
1956 : 1878 : so->arrayKeys[numArrayKeys].attlen = attr->attlen;
1957 : 1878 : so->arrayKeys[numArrayKeys].attbyval = attr->attbyval;
1958 : 1878 : so->arrayKeys[numArrayKeys].null_elem = true; /* for now */
1959 : 3756 : so->arrayKeys[numArrayKeys].sksup =
1960 : 1878 : PrepareSkipSupportFromOpclass(opfamily, opcintype, reverse);
1961 : 1878 : so->arrayKeys[numArrayKeys].low_compare = NULL; /* for now */
1962 : 1878 : so->arrayKeys[numArrayKeys].high_compare = NULL; /* for now */
1963 : :
1964 : : /*
1965 : : * We'll need a 3-way ORDER proc. Set that up now.
1966 : : */
1967 : 1878 : _bt_setup_array_cmp(scan, cur, opcintype,
1968 : 1878 : &so->orderProcs[numArrayKeyData], NULL);
1969 : :
1970 : 1878 : numArrayKeys++;
1971 : 1878 : numArrayKeyData++; /* keep this scan key/array */
1972 : :
1973 : : /* set up next output scan key */
1974 : 1878 : cur = &arrayKeyData[numArrayKeyData];
1975 : :
1976 : : /* remember having output this skip array and scan key */
1977 : 1878 : numSkipArrayKeys--;
1978 : 1878 : attno_skip++;
1979 : : }
1980 : :
1981 : : /*
1982 : : * Provisionally copy scan key into arrayKeyData[] array we'll return
1983 : : * to _bt_preprocess_keys caller
1984 : : */
1985 : 36379 : *cur = *inkey;
1986 : :
236 1987 [ + + ]: 36379 : if (!(cur->sk_flags & SK_SEARCHARRAY))
1988 : : {
155 1989 : 2563 : numArrayKeyData++; /* keep this non-array scan key */
236 1990 : 2572 : continue;
1991 : : }
1992 : :
1993 : : /*
1994 : : * Process SAOP array scan key
1995 : : */
155 1996 [ - + ]: 33816 : Assert(!(cur->sk_flags & (SK_ROW_HEADER | SK_SEARCHNULL | SK_SEARCHNOTNULL)));
1997 : :
1998 : : /* If array is null as a whole, the scan qual is unsatisfiable */
1999 [ + + ]: 33816 : if (cur->sk_flags & SK_ISNULL)
2000 : : {
2001 : 3 : so->qual_ok = false;
2002 : 9 : break;
2003 : : }
2004 : :
2005 : : /*
2006 : : * Deconstruct the array into elements
2007 : : */
236 2008 : 33813 : arrayval = DatumGetArrayTypeP(cur->sk_argument);
2009 : : /* We could cache this data, but not clear it's worth it */
2010 : 33813 : get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
2011 : : &elmlen, &elmbyval, &elmalign);
2012 : 33813 : deconstruct_array(arrayval,
2013 : : ARR_ELEMTYPE(arrayval),
2014 : : elmlen, elmbyval, elmalign,
2015 : : &elem_values, &elem_nulls, &num_elems);
2016 : :
2017 : : /*
2018 : : * Compress out any null elements. We can ignore them since we assume
2019 : : * all btree operators are strict.
2020 : : */
2021 : 33813 : num_nonnulls = 0;
155 2022 [ + + ]: 133910 : for (int j = 0; j < num_elems; j++)
2023 : : {
236 2024 [ + + ]: 100097 : if (!elem_nulls[j])
2025 : 100088 : elem_values[num_nonnulls++] = elem_values[j];
2026 : : }
2027 : :
2028 : : /* We could pfree(elem_nulls) now, but not worth the cycles */
2029 : :
2030 : : /* If there's no non-nulls, the scan qual is unsatisfiable */
2031 [ + + ]: 33813 : if (num_nonnulls == 0)
2032 : : {
2033 : 3 : so->qual_ok = false;
2034 : 3 : break;
2035 : : }
2036 : :
2037 : : /*
2038 : : * Determine the nominal datatype of the array elements. We have to
2039 : : * support the convention that sk_subtype == InvalidOid means the
2040 : : * opclass input type; this is a hack to simplify life for
2041 : : * ScanKeyInit().
2042 : : */
2043 : 33810 : elemtype = cur->sk_subtype;
2044 [ - + ]: 33810 : if (elemtype == InvalidOid)
236 pg@bowt.ie 2045 :UBC 0 : elemtype = rel->rd_opcintype[cur->sk_attno - 1];
2046 : :
2047 : : /*
2048 : : * If the comparison operator is not equality, then the array qual
2049 : : * degenerates to a simple comparison against the smallest or largest
2050 : : * non-null array element, as appropriate.
2051 : : */
236 pg@bowt.ie 2052 [ + + + - ]:CBC 33810 : switch (cur->sk_strategy)
2053 : : {
2054 : 3 : case BTLessStrategyNumber:
2055 : : case BTLessEqualStrategyNumber:
2056 : 3 : cur->sk_argument =
2057 : 3 : _bt_find_extreme_element(scan, cur, elemtype,
2058 : : BTGreaterStrategyNumber,
2059 : : elem_values, num_nonnulls);
155 2060 : 3 : numArrayKeyData++; /* keep this transformed scan key */
236 2061 : 3 : continue;
2062 : 33804 : case BTEqualStrategyNumber:
2063 : : /* proceed with rest of loop */
2064 : 33804 : break;
2065 : 3 : case BTGreaterEqualStrategyNumber:
2066 : : case BTGreaterStrategyNumber:
2067 : 3 : cur->sk_argument =
2068 : 3 : _bt_find_extreme_element(scan, cur, elemtype,
2069 : : BTLessStrategyNumber,
2070 : : elem_values, num_nonnulls);
155 2071 : 3 : numArrayKeyData++; /* keep this transformed scan key */
236 2072 : 3 : continue;
236 pg@bowt.ie 2073 :UBC 0 : default:
2074 [ # # ]: 0 : elog(ERROR, "unrecognized StrategyNumber: %d",
2075 : : (int) cur->sk_strategy);
2076 : : break;
2077 : : }
2078 : :
2079 : : /*
2080 : : * We'll need a 3-way ORDER proc to perform binary searches for the
2081 : : * next matching array element. Set that up now.
2082 : : *
2083 : : * Array scan keys with cross-type equality operators will require a
2084 : : * separate same-type ORDER proc for sorting their array. Otherwise,
2085 : : * sortproc just points to the same proc used during binary searches.
2086 : : */
236 pg@bowt.ie 2087 :CBC 33804 : _bt_setup_array_cmp(scan, cur, elemtype,
155 2088 : 33804 : &so->orderProcs[numArrayKeyData], &sortprocp);
2089 : :
2090 : : /*
2091 : : * Sort the non-null elements and eliminate any duplicates. We must
2092 : : * sort in the same ordering used by the index column, so that the
2093 : : * arrays can be advanced in lockstep with the scan's progress through
2094 : : * the index's key space.
2095 : : */
236 2096 : 33804 : reverse = (indoption[cur->sk_attno - 1] & INDOPTION_DESC) != 0;
2097 : 33804 : num_elems = _bt_sort_array_elements(cur, sortprocp, reverse,
2098 : : elem_values, num_nonnulls);
2099 : :
2100 [ + + ]: 33804 : if (origarrayatt == cur->sk_attno)
2101 : : {
2102 : 6 : BTArrayKeyInfo *orig = &so->arrayKeys[origarraykey];
2103 : :
2104 : : /*
2105 : : * This array scan key is redundant with a previous equality
2106 : : * operator array scan key. Merge the two arrays together to
2107 : : * eliminate contradictory non-intersecting elements (or try to).
2108 : : *
2109 : : * We merge this next array back into attribute's original array.
2110 : : */
2111 [ - + ]: 6 : Assert(arrayKeyData[orig->scan_key].sk_attno == cur->sk_attno);
2112 [ - + ]: 6 : Assert(arrayKeyData[orig->scan_key].sk_collation ==
2113 : : cur->sk_collation);
2114 [ + - ]: 6 : if (_bt_merge_arrays(scan, cur, sortprocp, reverse,
2115 : : origelemtype, elemtype,
2116 : : orig->elem_values, &orig->num_elems,
2117 : : elem_values, num_elems))
2118 : : {
2119 : : /* Successfully eliminated this array */
2120 : 6 : pfree(elem_values);
2121 : :
2122 : : /*
2123 : : * If no intersecting elements remain in the original array,
2124 : : * the scan qual is unsatisfiable
2125 : : */
2126 [ + + ]: 6 : if (orig->num_elems == 0)
2127 : : {
2128 : 3 : so->qual_ok = false;
2129 : 3 : break;
2130 : : }
2131 : :
2132 : : /* Throw away this scan key/array */
2133 : 3 : continue;
2134 : : }
2135 : :
2136 : : /*
2137 : : * Unable to merge this array with previous array due to a lack of
2138 : : * suitable cross-type opfamily support. Will need to keep both
2139 : : * scan keys/arrays.
2140 : : */
2141 : : }
2142 : : else
2143 : : {
2144 : : /*
2145 : : * This array is the first for current index attribute.
2146 : : *
2147 : : * If it turns out to not be the last array (that is, if the next
2148 : : * array is redundantly applied to this same index attribute),
2149 : : * we'll then treat this array as the attribute's "original" array
2150 : : * when merging.
2151 : : */
2152 : 33798 : origarrayatt = cur->sk_attno;
2153 : 33798 : origarraykey = numArrayKeys;
2154 : 33798 : origelemtype = elemtype;
2155 : : }
2156 : :
2157 : : /* Initialize generic BTArrayKeyInfo fields */
155 2158 : 33798 : so->arrayKeys[numArrayKeys].scan_key = numArrayKeyData;
236 2159 : 33798 : so->arrayKeys[numArrayKeys].num_elems = num_elems;
2160 : :
2161 : : /* Initialize SAOP array specific BTArrayKeyInfo fields */
2162 : 33798 : so->arrayKeys[numArrayKeys].elem_values = elem_values;
155 2163 : 33798 : so->arrayKeys[numArrayKeys].cur_elem = -1; /* i.e. invalid */
2164 : :
236 2165 : 33798 : numArrayKeys++;
155 2166 : 33798 : numArrayKeyData++; /* keep this scan key/array */
2167 : : }
2168 : :
129 2169 [ - + - - ]: 35531 : Assert(numSkipArrayKeys == 0 || !so->qual_ok);
2170 : :
2171 : : /* Set final number of equality-type array keys */
236 2172 : 35531 : so->numArrayKeys = numArrayKeys;
2173 : : /* Set number of scan keys in arrayKeyData[] */
155 2174 : 35531 : *new_numberOfKeys = numArrayKeyData;
2175 : :
236 2176 : 35531 : MemoryContextSwitchTo(oldContext);
2177 : :
2178 : 35531 : return arrayKeyData;
2179 : : }
2180 : :
2181 : : /*
2182 : : * _bt_preprocess_array_keys_final() -- fix up array scan key references
2183 : : *
2184 : : * When _bt_preprocess_array_keys performed initial array preprocessing, it
2185 : : * set each array's array->scan_key to its scankey's arrayKeyData[] offset.
2186 : : * This function handles translation of the scan key references from the
2187 : : * BTArrayKeyInfo info array, from input scan key references (to the keys in
2188 : : * arrayKeyData[]), into output references (to the keys in so->keyData[]).
2189 : : * Caller's keyDataMap[] array tells us how to perform this remapping.
2190 : : *
2191 : : * Also finalizes so->orderProcs[] for the scan. Arrays already have an ORDER
2192 : : * proc, which might need to be repositioned to its so->keyData[]-wise offset
2193 : : * (very much like the remapping that we apply to array->scan_key references).
2194 : : * Non-array equality strategy scan keys (that survived preprocessing) don't
2195 : : * yet have an so->orderProcs[] entry, so we set one for them here.
2196 : : *
2197 : : * Also converts single-element array scan keys into equivalent non-array
2198 : : * equality scan keys, which decrements so->numArrayKeys. It's possible that
2199 : : * this will leave this new btrescan without any arrays at all. This isn't
2200 : : * necessary for correctness; it's just an optimization. Non-array equality
2201 : : * scan keys are slightly faster than equivalent array scan keys at runtime.
2202 : : */
2203 : : static void
2204 : 2124 : _bt_preprocess_array_keys_final(IndexScanDesc scan, int *keyDataMap)
2205 : : {
2206 : 2124 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2207 : 2124 : Relation rel = scan->indexRelation;
2208 : 2124 : int arrayidx = 0;
2209 : 2124 : int last_equal_output_ikey PG_USED_FOR_ASSERTS_ONLY = -1;
2210 : :
2211 [ - + ]: 2124 : Assert(so->qual_ok);
2212 : :
2213 : : /*
2214 : : * Nothing for us to do when _bt_preprocess_array_keys only had to deal
2215 : : * with array inequalities
2216 : : */
2217 [ - + ]: 2124 : if (so->numArrayKeys == 0)
236 pg@bowt.ie 2218 :UBC 0 : return;
2219 : :
236 pg@bowt.ie 2220 [ + + ]:CBC 6817 : for (int output_ikey = 0; output_ikey < so->numberOfKeys; output_ikey++)
2221 : : {
2222 : 4699 : ScanKey outkey = so->keyData + output_ikey;
2223 : : int input_ikey;
2224 : 4699 : bool found PG_USED_FOR_ASSERTS_ONLY = false;
2225 : :
2226 [ - + ]: 4699 : Assert(outkey->sk_strategy != InvalidStrategy);
2227 : :
2228 [ + + ]: 4699 : if (outkey->sk_strategy != BTEqualStrategyNumber)
2229 : 52 : continue;
2230 : :
2231 : 4647 : input_ikey = keyDataMap[output_ikey];
2232 : :
2233 [ - + ]: 4647 : Assert(last_equal_output_ikey < output_ikey);
2234 [ - + ]: 4647 : Assert(last_equal_output_ikey < input_ikey);
2235 : 4647 : last_equal_output_ikey = output_ikey;
2236 : :
2237 : : /*
2238 : : * We're lazy about looking up ORDER procs for non-array keys, since
2239 : : * not all input keys become output keys. Take care of it now.
2240 : : */
2241 [ + + ]: 4647 : if (!(outkey->sk_flags & SK_SEARCHARRAY))
2242 : 2339 : {
2243 : : Oid elemtype;
2244 : :
2245 : : /* No need for an ORDER proc given an IS NULL scan key */
2246 [ + + ]: 2366 : if (outkey->sk_flags & SK_SEARCHNULL)
2247 : 27 : continue;
2248 : :
2249 : : /*
2250 : : * A non-required scan key doesn't need an ORDER proc, either
2251 : : * (unless it's associated with an array, which this one isn't)
2252 : : */
2253 [ - + ]: 2339 : if (!(outkey->sk_flags & SK_BT_REQFWD))
236 pg@bowt.ie 2254 :UBC 0 : continue;
2255 : :
236 pg@bowt.ie 2256 :CBC 2339 : elemtype = outkey->sk_subtype;
2257 [ + + ]: 2339 : if (elemtype == InvalidOid)
2258 : 1274 : elemtype = rel->rd_opcintype[outkey->sk_attno - 1];
2259 : :
2260 : 2339 : _bt_setup_array_cmp(scan, outkey, elemtype,
2261 : 2339 : &so->orderProcs[output_ikey], NULL);
2262 : 2339 : continue;
2263 : : }
2264 : :
2265 : : /*
2266 : : * Reorder existing array scan key so->orderProcs[] entries.
2267 : : *
2268 : : * Doing this in-place is safe because preprocessing is required to
2269 : : * output all equality strategy scan keys in original input order
2270 : : * (among each group of entries against the same index attribute).
2271 : : * This is also the order that the arrays themselves appear in.
2272 : : */
2273 : 2281 : so->orderProcs[output_ikey] = so->orderProcs[input_ikey];
2274 : :
2275 : : /* Fix-up array->scan_key references for arrays */
2276 [ + - ]: 2281 : for (; arrayidx < so->numArrayKeys; arrayidx++)
2277 : : {
2278 : 2281 : BTArrayKeyInfo *array = &so->arrayKeys[arrayidx];
2279 : :
2280 : : /*
2281 : : * All skip arrays must be marked required, and final column can
2282 : : * never have a skip array
2283 : : */
155 2284 [ + + - + ]: 2281 : Assert(array->num_elems > 0 || array->num_elems == -1);
2285 [ + + - + ]: 2281 : Assert(array->num_elems != -1 || outkey->sk_flags & SK_BT_REQFWD);
2286 [ + + - + ]: 2281 : Assert(array->num_elems != -1 ||
2287 : : outkey->sk_attno < IndexRelationGetNumberOfKeyAttributes(rel));
2288 : :
236 2289 [ + - ]: 2281 : if (array->scan_key == input_ikey)
2290 : : {
2291 : : /* found it */
2292 : 2281 : array->scan_key = output_ikey;
2293 : 2281 : found = true;
2294 : :
2295 : : /*
2296 : : * Transform array scan keys that have exactly 1 element
2297 : : * remaining (following all prior preprocessing) into
2298 : : * equivalent non-array scan keys.
2299 : : */
2300 [ + + ]: 2281 : if (array->num_elems == 1)
2301 : : {
2302 : 9 : outkey->sk_flags &= ~SK_SEARCHARRAY;
2303 : 9 : outkey->sk_argument = array->elem_values[0];
2304 : 9 : so->numArrayKeys--;
2305 : :
2306 : : /* If we're out of array keys, we can quit right away */
2307 [ + + ]: 9 : if (so->numArrayKeys == 0)
2308 : 6 : return;
2309 : :
2310 : : /* Shift other arrays forward */
2311 : 3 : memmove(array, array + 1,
2312 : : sizeof(BTArrayKeyInfo) *
2313 : 3 : (so->numArrayKeys - arrayidx));
2314 : :
2315 : : /*
2316 : : * Don't increment arrayidx (there was an entry that was
2317 : : * just shifted forward to the offset at arrayidx, which
2318 : : * will still need to be matched)
2319 : : */
2320 : : }
2321 : : else
2322 : : {
2323 : : /*
2324 : : * Any skip array low_compare and high_compare scan keys
2325 : : * are now final. Transform the array's > low_compare key
2326 : : * into a >= key (and < high_compare keys into a <= key).
2327 : : */
155 2328 [ + + + + ]: 2272 : if (array->num_elems == -1 && array->sksup &&
2329 [ + + ]: 1635 : !array->null_elem)
2330 : 39 : _bt_skiparray_strat_adjust(scan, outkey, array);
2331 : :
2332 : : /* Match found, so done with this array */
236 2333 : 2272 : arrayidx++;
2334 : : }
2335 : :
2336 : 2275 : break;
2337 : : }
2338 : : }
2339 : :
2340 [ - + ]: 2275 : Assert(found);
2341 : : }
2342 : :
2343 : : /*
2344 : : * Parallel index scans require space in shared memory to store the
2345 : : * current array elements (for arrays kept by preprocessing) to schedule
2346 : : * the next primitive index scan. The underlying structure is protected
2347 : : * using an LWLock, so defensively limit its size. In practice this can
2348 : : * only affect parallel scans that use an incomplete opfamily.
2349 : : */
2350 [ - + - - ]: 2118 : if (scan->parallel_scan && so->numArrayKeys > INDEX_MAX_KEYS)
236 pg@bowt.ie 2351 [ # # ]:UBC 0 : ereport(ERROR,
2352 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2353 : : errmsg_internal("number of array scan keys left by preprocessing (%d) exceeds the maximum allowed by parallel btree index scans (%d)",
2354 : : so->numArrayKeys, INDEX_MAX_KEYS)));
2355 : : }
2356 : :
2357 : : /*
2358 : : * _bt_num_array_keys() -- determine # of BTArrayKeyInfo entries
2359 : : *
2360 : : * _bt_preprocess_array_keys helper function. Returns the estimated size of
2361 : : * the scan's BTArrayKeyInfo array, which is guaranteed to be large enough to
2362 : : * fit every so->arrayKeys[] entry.
2363 : : *
2364 : : * Also sets *numSkipArrayKeys_out to the number of skip arrays caller must
2365 : : * add to the scan keys it'll output. Caller must add this many skip arrays:
2366 : : * one array for each of the most significant attributes that lack a = input
2367 : : * key (IS NULL keys count as = input keys here). The specific attributes
2368 : : * that need skip arrays are indicated by initializing skip_eq_ops_out[] arg
2369 : : * 0-based attribute offset to a valid = op strategy Oid. We'll only ever set
2370 : : * skip_eq_ops_out[] entries to InvalidOid for attributes that already have an
2371 : : * equality key in scan->keyData[] input keys -- and only when there's some
2372 : : * later "attribute gap" for us to "fill-in" with a skip array.
2373 : : *
2374 : : * We're optimistic about skipping working out: we always add exactly the skip
2375 : : * arrays needed to maximize the number of input scan keys that can ultimately
2376 : : * be marked as required to continue the scan (but no more). Given a
2377 : : * multi-column index on (a, b, c, d), we add skip arrays as follows:
2378 : : *
2379 : : * Input keys Output keys (after all preprocessing)
2380 : : * ---------- -------------------------------------
2381 : : * a = 1 a = 1 (no skip arrays)
2382 : : * b = 42 skip a AND b = 42
2383 : : * a = 1 AND b = 42 a = 1 AND b = 42 (no skip arrays)
2384 : : * a >= 1 AND b = 42 range skip a AND b = 42
2385 : : * a = 1 AND b > 42 a = 1 AND b > 42 (no skip arrays)
2386 : : * a >= 1 AND a <= 3 AND b = 42 range skip a AND b = 42
2387 : : * a = 1 AND c <= 27 a = 1 AND skip b AND c <= 27
2388 : : * a = 1 AND d >= 1 a = 1 AND skip b AND skip c AND d >= 1
2389 : : * a = 1 AND b >= 42 AND d > 1 a = 1 AND range skip b AND skip c AND d > 1
2390 : : */
2391 : : static int
155 pg@bowt.ie 2392 :CBC 6992386 : _bt_num_array_keys(IndexScanDesc scan, Oid *skip_eq_ops_out,
2393 : : int *numSkipArrayKeys_out)
2394 : : {
2395 : 6992386 : Relation rel = scan->indexRelation;
2396 : 6992386 : AttrNumber attno_skip = 1,
2397 : 6992386 : attno_inkey = 1;
2398 : 6992386 : bool attno_has_equal = false,
2399 : 6992386 : attno_has_rowcompare = false;
2400 : : int numSAOPArrayKeys,
2401 : : numSkipArrayKeys,
2402 : : prev_numSkipArrayKeys;
2403 : :
2404 [ - + ]: 6992386 : Assert(scan->numberOfKeys);
2405 : :
2406 : : /* Initial pass over input scan keys counts the number of SAOP arrays */
2407 : 6992386 : numSAOPArrayKeys = 0;
2408 : 6992386 : *numSkipArrayKeys_out = prev_numSkipArrayKeys = numSkipArrayKeys = 0;
2409 [ + + ]: 18246026 : for (int i = 0; i < scan->numberOfKeys; i++)
2410 : : {
2411 : 11253640 : ScanKey inkey = scan->keyData + i;
2412 : :
2413 [ + + ]: 11253640 : if (inkey->sk_flags & SK_SEARCHARRAY)
2414 : 33816 : numSAOPArrayKeys++;
2415 : : }
2416 : :
2417 : : #ifdef DEBUG_DISABLE_SKIP_SCAN
2418 : : /* don't attempt to add skip arrays */
2419 : : return numSAOPArrayKeys;
2420 : : #endif
2421 : :
2422 : 6992386 : for (int i = 0;; i++)
2423 : 11253625 : {
2424 : 18246011 : ScanKey inkey = scan->keyData + i;
2425 : :
2426 : : /*
2427 : : * Backfill skip arrays for any wholly omitted attributes prior to
2428 : : * attno_inkey
2429 : : */
2430 [ + + ]: 18246294 : while (attno_skip < attno_inkey)
2431 : : {
2432 : 283 : Oid opfamily = rel->rd_opfamily[attno_skip - 1];
2433 : 283 : Oid opcintype = rel->rd_opcintype[attno_skip - 1];
2434 : :
2435 : : /* Look up input opclass's equality operator (might fail) */
2436 : 566 : skip_eq_ops_out[attno_skip - 1] =
2437 : 283 : get_opfamily_member(opfamily, opcintype, opcintype,
2438 : : BTEqualStrategyNumber);
2439 [ - + ]: 283 : if (!OidIsValid(skip_eq_ops_out[attno_skip - 1]))
2440 : : {
2441 : : /*
2442 : : * Cannot generate a skip array for this or later attributes
2443 : : * (input opclass lacks an equality strategy operator)
2444 : : */
155 pg@bowt.ie 2445 :UBC 0 : *numSkipArrayKeys_out = prev_numSkipArrayKeys;
2446 : 0 : return numSAOPArrayKeys + prev_numSkipArrayKeys;
2447 : : }
2448 : :
2449 : : /* plan on adding a backfill skip array for this attribute */
155 pg@bowt.ie 2450 :CBC 283 : numSkipArrayKeys++;
2451 : 283 : attno_skip++;
2452 : : }
2453 : :
2454 : 18246011 : prev_numSkipArrayKeys = numSkipArrayKeys;
2455 : :
2456 : : /*
2457 : : * Stop once past the final input scan key. We deliberately never add
2458 : : * a skip array for the last input scan key's attribute -- even when
2459 : : * there are only inequality keys on that attribute.
2460 : : */
2461 [ + + ]: 18246011 : if (i == scan->numberOfKeys)
2462 : 6992377 : break;
2463 : :
2464 : : /*
2465 : : * Later preprocessing steps cannot merge a RowCompare into a skip
2466 : : * array, so stop adding skip arrays once we see one. (Note that we
2467 : : * can backfill skip arrays before a RowCompare, which will allow keys
2468 : : * up to and including the RowCompare to be marked required.)
2469 : : *
2470 : : * Skip arrays work by maintaining a current array element value,
2471 : : * which anchors lower-order keys via an implied equality constraint.
2472 : : * This is incompatible with the current nbtree row comparison design,
2473 : : * which compares all columns together, as an indivisible group.
2474 : : * Alternative designs that can be used alongside skip arrays are
2475 : : * possible, but it's not clear that they're really worth pursuing.
2476 : : *
2477 : : * A RowCompare qual "(a, b, c) > (10, 'foo', 42)" is equivalent to
2478 : : * "(a=10 AND b='foo' AND c>42) OR (a=10 AND b>'foo') OR (a>10)".
2479 : : * Decomposing this RowCompare into these 3 disjuncts allows each
2480 : : * disjunct to be executed as a separate "single value" index scan.
2481 : : * That'll give all 3 scans the ability to add skip arrays in the
2482 : : * usual way (when there are any scalar keys after the RowCompare).
2483 : : * Under this scheme, a qual "(a, b, c) > (10, 'foo', 42) AND d = 99"
2484 : : * performs 3 separate scans, each of which can mark keys up to and
2485 : : * including its "d = 99" key as required to continue the scan.
2486 : : */
2487 [ + + ]: 11253634 : if (attno_has_rowcompare)
2488 : 9 : break;
2489 : :
2490 : : /*
2491 : : * Now consider next attno_inkey (or keep going if this is an
2492 : : * additional scan key against the same attribute)
2493 : : */
2494 [ + + ]: 11253625 : if (attno_inkey < inkey->sk_attno)
2495 : : {
2496 : : /*
2497 : : * Now add skip array for previous scan key's attribute, though
2498 : : * only if the attribute has no equality strategy scan keys
2499 : : */
2500 [ + + ]: 4261660 : if (attno_has_equal)
2501 : : {
2502 : : /* Attributes with an = key must have InvalidOid eq_op set */
2503 : 4260065 : skip_eq_ops_out[attno_skip - 1] = InvalidOid;
2504 : : }
2505 : : else
2506 : : {
2507 : 1595 : Oid opfamily = rel->rd_opfamily[attno_skip - 1];
2508 : 1595 : Oid opcintype = rel->rd_opcintype[attno_skip - 1];
2509 : :
2510 : : /* Look up input opclass's equality operator (might fail) */
2511 : 3190 : skip_eq_ops_out[attno_skip - 1] =
2512 : 1595 : get_opfamily_member(opfamily, opcintype, opcintype,
2513 : : BTEqualStrategyNumber);
2514 : :
2515 [ - + ]: 1595 : if (!OidIsValid(skip_eq_ops_out[attno_skip - 1]))
2516 : : {
2517 : : /*
2518 : : * Input opclass lacks an equality strategy operator, so
2519 : : * don't generate a skip array that definitely won't work
2520 : : */
155 pg@bowt.ie 2521 :UBC 0 : break;
2522 : : }
2523 : :
2524 : : /* plan on adding a backfill skip array for this attribute */
155 pg@bowt.ie 2525 :CBC 1595 : numSkipArrayKeys++;
2526 : : }
2527 : :
2528 : : /* Set things up for this new attribute */
2529 : 4261660 : attno_skip++;
2530 : 4261660 : attno_inkey = inkey->sk_attno;
2531 : 4261660 : attno_has_equal = false;
2532 : : }
2533 : :
2534 : : /*
2535 : : * Track if this attribute's scan keys include any equality strategy
2536 : : * scan keys (IS NULL keys count as equality keys here). Also track
2537 : : * if it has any RowCompare keys.
2538 : : */
2539 [ + + ]: 11253625 : if (inkey->sk_strategy == BTEqualStrategyNumber ||
2540 [ + + ]: 713280 : (inkey->sk_flags & SK_SEARCHNULL))
2541 : 10540417 : attno_has_equal = true;
2542 [ + + ]: 11253625 : if (inkey->sk_flags & SK_ROW_HEADER)
2543 : 42 : attno_has_rowcompare = true;
2544 : : }
2545 : :
2546 : 6992386 : *numSkipArrayKeys_out = numSkipArrayKeys;
2547 : 6992386 : return numSAOPArrayKeys + numSkipArrayKeys;
2548 : : }
2549 : :
2550 : : /*
2551 : : * _bt_find_extreme_element() -- get least or greatest array element
2552 : : *
2553 : : * scan and skey identify the index column, whose opfamily determines the
2554 : : * comparison semantics. strat should be BTLessStrategyNumber to get the
2555 : : * least element, or BTGreaterStrategyNumber to get the greatest.
2556 : : */
2557 : : static Datum
236 2558 : 6 : _bt_find_extreme_element(IndexScanDesc scan, ScanKey skey, Oid elemtype,
2559 : : StrategyNumber strat,
2560 : : Datum *elems, int nelems)
2561 : : {
2562 : 6 : Relation rel = scan->indexRelation;
2563 : : Oid cmp_op;
2564 : : RegProcedure cmp_proc;
2565 : : FmgrInfo flinfo;
2566 : : Datum result;
2567 : : int i;
2568 : :
2569 : : /*
2570 : : * Look up the appropriate comparison operator in the opfamily.
2571 : : *
2572 : : * Note: it's possible that this would fail, if the opfamily is
2573 : : * incomplete, but it seems quite unlikely that an opfamily would omit
2574 : : * non-cross-type comparison operators for any datatype that it supports
2575 : : * at all.
2576 : : */
2577 [ - + ]: 6 : Assert(skey->sk_strategy != BTEqualStrategyNumber);
2578 [ - + ]: 6 : Assert(OidIsValid(elemtype));
2579 : 6 : cmp_op = get_opfamily_member(rel->rd_opfamily[skey->sk_attno - 1],
2580 : : elemtype,
2581 : : elemtype,
2582 : : strat);
2583 [ - + ]: 6 : if (!OidIsValid(cmp_op))
236 pg@bowt.ie 2584 [ # # ]:UBC 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2585 : : strat, elemtype, elemtype,
2586 : : rel->rd_opfamily[skey->sk_attno - 1]);
236 pg@bowt.ie 2587 :CBC 6 : cmp_proc = get_opcode(cmp_op);
2588 [ - + ]: 6 : if (!RegProcedureIsValid(cmp_proc))
236 pg@bowt.ie 2589 [ # # ]:UBC 0 : elog(ERROR, "missing oprcode for operator %u", cmp_op);
2590 : :
236 pg@bowt.ie 2591 :CBC 6 : fmgr_info(cmp_proc, &flinfo);
2592 : :
2593 [ - + ]: 6 : Assert(nelems > 0);
2594 : 6 : result = elems[0];
2595 [ + + ]: 18 : for (i = 1; i < nelems; i++)
2596 : : {
2597 [ + + ]: 12 : if (DatumGetBool(FunctionCall2Coll(&flinfo,
2598 : : skey->sk_collation,
2599 : 12 : elems[i],
2600 : : result)))
2601 : 3 : result = elems[i];
2602 : : }
2603 : :
2604 : 6 : return result;
2605 : : }
2606 : :
2607 : : /*
2608 : : * _bt_setup_array_cmp() -- Set up array comparison functions
2609 : : *
2610 : : * Sets ORDER proc in caller's orderproc argument, which is used during binary
2611 : : * searches of arrays during the index scan. Also sets a same-type ORDER proc
2612 : : * in caller's *sortprocp argument, which is used when sorting the array.
2613 : : *
2614 : : * Preprocessing calls here with all equality strategy scan keys (when scan
2615 : : * uses equality array keys), including those not associated with any array.
2616 : : * See _bt_advance_array_keys for an explanation of why it'll need to treat
2617 : : * simple scalar equality scan keys as degenerate single element arrays.
2618 : : *
2619 : : * Caller should pass an orderproc pointing to space that'll store the ORDER
2620 : : * proc for the scan, and a *sortprocp pointing to its own separate space.
2621 : : * When calling here for a non-array scan key, sortprocp arg should be NULL.
2622 : : *
2623 : : * In the common case where we don't need to deal with cross-type operators,
2624 : : * only one ORDER proc is actually required by caller. We'll set *sortprocp
2625 : : * to point to the same memory that caller's orderproc continues to point to.
2626 : : * Otherwise, *sortprocp will continue to point to caller's own space. Either
2627 : : * way, *sortprocp will point to a same-type ORDER proc (since that's the only
2628 : : * safe way to sort/deduplicate the array associated with caller's scan key).
2629 : : */
2630 : : static void
2631 : 38021 : _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
2632 : : FmgrInfo *orderproc, FmgrInfo **sortprocp)
2633 : : {
2634 : 38021 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2635 : 38021 : Relation rel = scan->indexRelation;
2636 : : RegProcedure cmp_proc;
2637 : 38021 : Oid opcintype = rel->rd_opcintype[skey->sk_attno - 1];
2638 : :
2639 [ - + ]: 38021 : Assert(skey->sk_strategy == BTEqualStrategyNumber);
2640 [ - + ]: 38021 : Assert(OidIsValid(elemtype));
2641 : :
2642 : : /*
2643 : : * If scankey operator is not a cross-type comparison, we can use the
2644 : : * cached comparison function; otherwise gotta look it up in the catalogs
2645 : : */
2646 [ + + ]: 38021 : if (elemtype == opcintype)
2647 : : {
2648 : : /* Set same-type ORDER procs for caller */
2649 : 37886 : *orderproc = *index_getprocinfo(rel, skey->sk_attno, BTORDER_PROC);
2650 [ + + ]: 37886 : if (sortprocp)
2651 : 33801 : *sortprocp = orderproc;
2652 : :
2653 : 37886 : return;
2654 : : }
2655 : :
2656 : : /*
2657 : : * Look up the appropriate cross-type comparison function in the opfamily.
2658 : : *
2659 : : * Use the opclass input type as the left hand arg type, and the array
2660 : : * element type as the right hand arg type (since binary searches use an
2661 : : * index tuple's attribute value to search for a matching array element).
2662 : : *
2663 : : * Note: it's possible that this would fail, if the opfamily is
2664 : : * incomplete, but only in cases where it's quite likely that _bt_first
2665 : : * would fail in just the same way (had we not failed before it could).
2666 : : */
2667 : 135 : cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
2668 : : opcintype, elemtype, BTORDER_PROC);
2669 [ - + ]: 135 : if (!RegProcedureIsValid(cmp_proc))
236 pg@bowt.ie 2670 [ # # ]:UBC 0 : elog(ERROR, "missing support function %d(%u,%u) for attribute %d of index \"%s\"",
2671 : : BTORDER_PROC, opcintype, elemtype, skey->sk_attno,
2672 : : RelationGetRelationName(rel));
2673 : :
2674 : : /* Set cross-type ORDER proc for caller */
236 pg@bowt.ie 2675 :CBC 135 : fmgr_info_cxt(cmp_proc, orderproc, so->arrayContext);
2676 : :
2677 : : /* Done if caller doesn't actually have an array they'll need to sort */
2678 [ + + ]: 135 : if (!sortprocp)
2679 : 132 : return;
2680 : :
2681 : : /*
2682 : : * Look up the appropriate same-type comparison function in the opfamily.
2683 : : *
2684 : : * Note: it's possible that this would fail, if the opfamily is
2685 : : * incomplete, but it seems quite unlikely that an opfamily would omit
2686 : : * non-cross-type comparison procs for any datatype that it supports at
2687 : : * all.
2688 : : */
2689 : 3 : cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
2690 : : elemtype, elemtype, BTORDER_PROC);
2691 [ - + ]: 3 : if (!RegProcedureIsValid(cmp_proc))
236 pg@bowt.ie 2692 [ # # ]:UBC 0 : elog(ERROR, "missing support function %d(%u,%u) for attribute %d of index \"%s\"",
2693 : : BTORDER_PROC, elemtype, elemtype,
2694 : : skey->sk_attno, RelationGetRelationName(rel));
2695 : :
2696 : : /* Set same-type ORDER proc for caller */
236 pg@bowt.ie 2697 :CBC 3 : fmgr_info_cxt(cmp_proc, *sortprocp, so->arrayContext);
2698 : : }
2699 : :
2700 : : /*
2701 : : * _bt_sort_array_elements() -- sort and de-dup array elements
2702 : : *
2703 : : * The array elements are sorted in-place, and the new number of elements
2704 : : * after duplicate removal is returned.
2705 : : *
2706 : : * skey identifies the index column whose opfamily determines the comparison
2707 : : * semantics, and sortproc is a corresponding ORDER proc. If reverse is true,
2708 : : * we sort in descending order.
2709 : : */
2710 : : static int
2711 : 33804 : _bt_sort_array_elements(ScanKey skey, FmgrInfo *sortproc, bool reverse,
2712 : : Datum *elems, int nelems)
2713 : : {
2714 : : BTSortArrayContext cxt;
2715 : :
2716 [ + + ]: 33804 : if (nelems <= 1)
2717 : 26 : return nelems; /* no work to do */
2718 : :
2719 : : /* Sort the array elements */
2720 : 33778 : cxt.sortproc = sortproc;
2721 : 33778 : cxt.collation = skey->sk_collation;
2722 : 33778 : cxt.reverse = reverse;
2723 : 33778 : qsort_arg(elems, nelems, sizeof(Datum),
2724 : : _bt_compare_array_elements, &cxt);
2725 : :
2726 : : /* Now scan the sorted elements and remove duplicates */
2727 : 33778 : return qunique_arg(elems, nelems, sizeof(Datum),
2728 : : _bt_compare_array_elements, &cxt);
2729 : : }
2730 : :
2731 : : /*
2732 : : * _bt_merge_arrays() -- merge next array's elements into an original array
2733 : : *
2734 : : * Called when preprocessing encounters a pair of array equality scan keys,
2735 : : * both against the same index attribute (during initial array preprocessing).
2736 : : * Merging reorganizes caller's original array (the left hand arg) in-place,
2737 : : * without ever copying elements from one array into the other. (Mixing the
2738 : : * elements together like this would be wrong, since they don't necessarily
2739 : : * use the same underlying element type, despite all the other similarities.)
2740 : : *
2741 : : * Both arrays must have already been sorted and deduplicated by calling
2742 : : * _bt_sort_array_elements. sortproc is the same-type ORDER proc that was
2743 : : * just used to sort and deduplicate caller's "next" array. We'll usually be
2744 : : * able to reuse that order PROC to merge the arrays together now. If not,
2745 : : * then we'll perform a separate ORDER proc lookup.
2746 : : *
2747 : : * If the opfamily doesn't supply a complete set of cross-type ORDER procs we
2748 : : * may not be able to determine which elements are contradictory. If we have
2749 : : * the required ORDER proc then we return true (and validly set *nelems_orig),
2750 : : * guaranteeing that at least the next array can be considered redundant. We
2751 : : * return false if the required comparisons cannot be made (caller must keep
2752 : : * both arrays when this happens).
2753 : : */
2754 : : static bool
2755 : 6 : _bt_merge_arrays(IndexScanDesc scan, ScanKey skey, FmgrInfo *sortproc,
2756 : : bool reverse, Oid origelemtype, Oid nextelemtype,
2757 : : Datum *elems_orig, int *nelems_orig,
2758 : : Datum *elems_next, int nelems_next)
2759 : : {
2760 : 6 : Relation rel = scan->indexRelation;
2761 : 6 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2762 : : BTSortArrayContext cxt;
2763 : 6 : int nelems_orig_start = *nelems_orig,
2764 : 6 : nelems_orig_merged = 0;
2765 : 6 : FmgrInfo *mergeproc = sortproc;
2766 : : FmgrInfo crosstypeproc;
2767 : :
2768 [ - + ]: 6 : Assert(skey->sk_strategy == BTEqualStrategyNumber);
2769 [ + - - + ]: 6 : Assert(OidIsValid(origelemtype) && OidIsValid(nextelemtype));
2770 : :
2771 [ + + ]: 6 : if (origelemtype != nextelemtype)
2772 : : {
2773 : : RegProcedure cmp_proc;
2774 : :
2775 : : /*
2776 : : * Cross-array-element-type merging is required, so can't just reuse
2777 : : * sortproc when merging
2778 : : */
2779 : 3 : cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
2780 : : origelemtype, nextelemtype, BTORDER_PROC);
2781 [ - + ]: 3 : if (!RegProcedureIsValid(cmp_proc))
2782 : : {
2783 : : /* Can't make the required comparisons */
236 pg@bowt.ie 2784 :UBC 0 : return false;
2785 : : }
2786 : :
2787 : : /* We have all we need to determine redundancy/contradictoriness */
236 pg@bowt.ie 2788 :CBC 3 : mergeproc = &crosstypeproc;
2789 : 3 : fmgr_info_cxt(cmp_proc, mergeproc, so->arrayContext);
2790 : : }
2791 : :
2792 : 6 : cxt.sortproc = mergeproc;
2793 : 6 : cxt.collation = skey->sk_collation;
2794 : 6 : cxt.reverse = reverse;
2795 : :
2796 [ + + + + ]: 27 : for (int i = 0, j = 0; i < nelems_orig_start && j < nelems_next;)
2797 : : {
2798 : 21 : Datum *oelem = elems_orig + i,
2799 : 21 : *nelem = elems_next + j;
2800 : 21 : int res = _bt_compare_array_elements(oelem, nelem, &cxt);
2801 : :
2802 [ + + ]: 21 : if (res == 0)
2803 : : {
2804 : 3 : elems_orig[nelems_orig_merged++] = *oelem;
2805 : 3 : i++;
2806 : 3 : j++;
2807 : : }
2808 [ + + ]: 18 : else if (res < 0)
2809 : 12 : i++;
2810 : : else /* res > 0 */
2811 : 6 : j++;
2812 : : }
2813 : :
2814 : 6 : *nelems_orig = nelems_orig_merged;
2815 : :
2816 : 6 : return true;
2817 : : }
2818 : :
2819 : : /*
2820 : : * qsort_arg comparator for sorting array elements
2821 : : */
2822 : : static int
2823 : 150106 : _bt_compare_array_elements(const void *a, const void *b, void *arg)
2824 : : {
2825 : 150106 : Datum da = *((const Datum *) a);
2826 : 150106 : Datum db = *((const Datum *) b);
2827 : 150106 : BTSortArrayContext *cxt = (BTSortArrayContext *) arg;
2828 : : int32 compare;
2829 : :
2830 : 150106 : compare = DatumGetInt32(FunctionCall2Coll(cxt->sortproc,
2831 : : cxt->collation,
2832 : : da, db));
2833 [ + + ]: 150106 : if (cxt->reverse)
2834 [ - + ]: 15 : INVERT_COMPARE_RESULT(compare);
2835 : 150106 : return compare;
2836 : : }
|