Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * nbtutils.c
4 : : * Utility code for Postgres btree implementation.
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/nbtutils.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include <time.h>
19 : :
20 : : #include "access/nbtree.h"
21 : : #include "access/reloptions.h"
22 : : #include "access/relscan.h"
23 : : #include "commands/progress.h"
24 : : #include "miscadmin.h"
25 : : #include "utils/datum.h"
26 : : #include "utils/lsyscache.h"
27 : : #include "utils/rel.h"
28 : :
29 : :
30 : : #define LOOK_AHEAD_REQUIRED_RECHECKS 3
31 : : #define LOOK_AHEAD_DEFAULT_DISTANCE 5
32 : : #define NSKIPADVANCES_THRESHOLD 3
33 : :
34 : : static inline int32 _bt_compare_array_skey(FmgrInfo *orderproc,
35 : : Datum tupdatum, bool tupnull,
36 : : Datum arrdatum, ScanKey cur);
37 : : static void _bt_binsrch_skiparray_skey(bool cur_elem_trig, ScanDirection dir,
38 : : Datum tupdatum, bool tupnull,
39 : : BTArrayKeyInfo *array, ScanKey cur,
40 : : int32 *set_elem_result);
41 : : static void _bt_skiparray_set_element(Relation rel, ScanKey skey, BTArrayKeyInfo *array,
42 : : int32 set_elem_result, Datum tupdatum, bool tupnull);
43 : : static void _bt_skiparray_set_isnull(Relation rel, ScanKey skey, BTArrayKeyInfo *array);
44 : : static void _bt_array_set_low_or_high(Relation rel, ScanKey skey,
45 : : BTArrayKeyInfo *array, bool low_not_high);
46 : : static bool _bt_array_decrement(Relation rel, ScanKey skey, BTArrayKeyInfo *array);
47 : : static bool _bt_array_increment(Relation rel, ScanKey skey, BTArrayKeyInfo *array);
48 : : static bool _bt_advance_array_keys_increment(IndexScanDesc scan, ScanDirection dir,
49 : : bool *skip_array_set);
50 : : static bool _bt_tuple_before_array_skeys(IndexScanDesc scan, ScanDirection dir,
51 : : IndexTuple tuple, TupleDesc tupdesc, int tupnatts,
52 : : bool readpagetup, int sktrig, bool *scanBehind);
53 : : static bool _bt_advance_array_keys(IndexScanDesc scan, BTReadPageState *pstate,
54 : : IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
55 : : int sktrig, bool sktrig_required);
56 : : #ifdef USE_ASSERT_CHECKING
57 : : static bool _bt_verify_keys_with_arraykeys(IndexScanDesc scan);
58 : : #endif
59 : : static bool _bt_oppodir_checkkeys(IndexScanDesc scan, ScanDirection dir,
60 : : IndexTuple finaltup);
61 : : static bool _bt_check_compare(IndexScanDesc scan, ScanDirection dir,
62 : : IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
63 : : bool advancenonrequired, bool forcenonrequired,
64 : : bool *continuescan, int *ikey);
65 : : static bool _bt_check_rowcompare(ScanKey skey,
66 : : IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
67 : : ScanDirection dir, bool forcenonrequired, bool *continuescan);
68 : : static void _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate,
69 : : int tupnatts, TupleDesc tupdesc);
70 : : static int _bt_keep_natts(Relation rel, IndexTuple lastleft,
71 : : IndexTuple firstright, BTScanInsert itup_key);
72 : :
73 : :
74 : : /*
75 : : * _bt_mkscankey
76 : : * Build an insertion scan key that contains comparison data from itup
77 : : * as well as comparator routines appropriate to the key datatypes.
78 : : *
79 : : * The result is intended for use with _bt_compare() and _bt_truncate().
80 : : * Callers that don't need to fill out the insertion scankey arguments
81 : : * (e.g. they use an ad-hoc comparison routine, or only need a scankey
82 : : * for _bt_truncate()) can pass a NULL index tuple. The scankey will
83 : : * be initialized as if an "all truncated" pivot tuple was passed
84 : : * instead.
85 : : *
86 : : * Note that we may occasionally have to share lock the metapage to
87 : : * determine whether or not the keys in the index are expected to be
88 : : * unique (i.e. if this is a "heapkeyspace" index). We assume a
89 : : * heapkeyspace index when caller passes a NULL tuple, allowing index
90 : : * build callers to avoid accessing the non-existent metapage. We
91 : : * also assume that the index is _not_ allequalimage when a NULL tuple
92 : : * is passed; CREATE INDEX callers call _bt_allequalimage() to set the
93 : : * field themselves.
94 : : */
95 : : BTScanInsert
819 pg@bowt.ie 96 :CBC 5982412 : _bt_mkscankey(Relation rel, IndexTuple itup)
97 : : {
98 : : BTScanInsert key;
99 : : ScanKey skey;
100 : : TupleDesc itupdesc;
101 : : int indnkeyatts;
102 : : int16 *indoption;
103 : : int tupnatts;
104 : : int i;
105 : :
9867 bruce@momjian.us 106 : 5982412 : itupdesc = RelationGetDescr(rel);
2709 teodor@sigaev.ru 107 : 5982412 : indnkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
6815 tgl@sss.pgh.pa.us 108 : 5982412 : indoption = rel->rd_indoption;
2362 pg@bowt.ie 109 [ + + + + ]: 5982412 : tupnatts = itup ? BTreeTupleGetNAtts(itup, rel) : 0;
110 : :
111 [ - + ]: 5982412 : Assert(tupnatts <= IndexRelationGetNumberOfAttributes(rel));
112 : :
113 : : /*
114 : : * We'll execute search using scan key constructed on key columns.
115 : : * Truncated attributes and non-key attributes are omitted from the final
116 : : * scan key.
117 : : */
118 : 5982412 : key = palloc(offsetof(BTScanInsertData, scankeys) +
119 : 5982412 : sizeof(ScanKeyData) * indnkeyatts);
2019 120 [ + + ]: 5982412 : if (itup)
819 121 : 5911525 : _bt_metaversion(rel, &key->heapkeyspace, &key->allequalimage);
122 : : else
123 : : {
124 : : /* Utility statement callers can set these fields themselves */
2019 125 : 70887 : key->heapkeyspace = true;
126 : 70887 : key->allequalimage = false;
127 : : }
2299 tgl@sss.pgh.pa.us 128 : 5982412 : key->anynullkeys = false; /* initial assumption */
638 pg@bowt.ie 129 : 5982412 : key->nextkey = false; /* usual case, required by btinsert */
130 : 5982412 : key->backward = false; /* usual case, required by btinsert */
2362 131 : 5982412 : key->keysz = Min(indnkeyatts, tupnatts);
132 [ + + ]: 5982412 : key->scantid = key->heapkeyspace && itup ?
133 [ + - ]: 11964824 : BTreeTupleGetHeapTID(itup) : NULL;
134 : 5982412 : skey = key->scankeys;
2709 teodor@sigaev.ru 135 [ + + ]: 16194641 : for (i = 0; i < indnkeyatts; i++)
136 : : {
137 : : FmgrInfo *procinfo;
138 : : Datum arg;
139 : : bool null;
140 : : int flags;
141 : :
142 : : /*
143 : : * We can use the cached (default) support procs since no cross-type
144 : : * comparison can be needed.
145 : : */
8736 tgl@sss.pgh.pa.us 146 : 10212229 : procinfo = index_getprocinfo(rel, i + 1, BTORDER_PROC);
147 : :
148 : : /*
149 : : * Key arguments built from truncated attributes (or when caller
150 : : * provides no tuple) are defensively represented as NULL values. They
151 : : * should never be used.
152 : : */
2362 pg@bowt.ie 153 [ + + ]: 10212229 : if (i < tupnatts)
154 : 10084723 : arg = index_getattr(itup, i + 1, itupdesc, &null);
155 : : else
156 : : {
157 : 127506 : arg = (Datum) 0;
158 : 127506 : null = true;
159 : : }
160 : 10212229 : flags = (null ? SK_ISNULL : 0) | (indoption[i] << SK_BT_INDOPTION_SHIFT);
8736 tgl@sss.pgh.pa.us 161 : 10212229 : ScanKeyEntryInitializeWithInfo(&skey[i],
162 : : flags,
163 : 10212229 : (AttrNumber) (i + 1),
164 : : InvalidStrategy,
165 : : InvalidOid,
5261 166 : 10212229 : rel->rd_indcollation[i],
167 : : procinfo,
168 : : arg);
169 : : /* Record if any key attribute is NULL (or truncated) */
2328 pg@bowt.ie 170 [ + + ]: 10212229 : if (null)
171 : 137830 : key->anynullkeys = true;
172 : : }
173 : :
174 : : /*
175 : : * In NULLS NOT DISTINCT mode, we pretend that there are no null keys, so
176 : : * that full uniqueness check is done.
177 : : */
1311 peter@eisentraut.org 178 [ + + ]: 5982412 : if (rel->rd_index->indnullsnotdistinct)
179 : 93 : key->anynullkeys = false;
180 : :
2362 pg@bowt.ie 181 : 5982412 : return key;
182 : : }
183 : :
184 : : /*
185 : : * free a retracement stack made by _bt_search.
186 : : */
187 : : void
10651 scrappy@hub.org 188 : 10333703 : _bt_freestack(BTStack stack)
189 : : {
190 : : BTStack ostack;
191 : :
7913 neilc@samurai.com 192 [ + + ]: 19055392 : while (stack != NULL)
193 : : {
10226 bruce@momjian.us 194 : 8721689 : ostack = stack;
195 : 8721689 : stack = stack->bts_parent;
196 : 8721689 : pfree(ostack);
197 : : }
10651 scrappy@hub.org 198 : 10333703 : }
199 : :
200 : : /*
201 : : * _bt_compare_array_skey() -- apply array comparison function
202 : : *
203 : : * Compares caller's tuple attribute value to a scan key/array element.
204 : : * Helper function used during binary searches of SK_SEARCHARRAY arrays.
205 : : *
206 : : * This routine returns:
207 : : * <0 if tupdatum < arrdatum;
208 : : * 0 if tupdatum == arrdatum;
209 : : * >0 if tupdatum > arrdatum.
210 : : *
211 : : * This is essentially the same interface as _bt_compare: both functions
212 : : * compare the value that they're searching for to a binary search pivot.
213 : : * However, unlike _bt_compare, this function's "tuple argument" comes first,
214 : : * while its "array/scankey argument" comes second.
215 : : */
216 : : static inline int32
236 pg@bowt.ie 217 : 445755 : _bt_compare_array_skey(FmgrInfo *orderproc,
218 : : Datum tupdatum, bool tupnull,
219 : : Datum arrdatum, ScanKey cur)
220 : : {
221 : 445755 : int32 result = 0;
222 : :
223 [ - + ]: 445755 : Assert(cur->sk_strategy == BTEqualStrategyNumber);
155 224 [ - + ]: 445755 : Assert(!(cur->sk_flags & (SK_BT_MINVAL | SK_BT_MAXVAL)));
225 : :
236 226 [ + + ]: 445755 : if (tupnull) /* NULL tupdatum */
227 : : {
228 [ + + ]: 231 : if (cur->sk_flags & SK_ISNULL)
229 : 126 : result = 0; /* NULL "=" NULL */
230 [ + + ]: 105 : else if (cur->sk_flags & SK_BT_NULLS_FIRST)
231 : 18 : result = -1; /* NULL "<" NOT_NULL */
232 : : else
233 : 87 : result = 1; /* NULL ">" NOT_NULL */
234 : : }
235 [ + + ]: 445524 : else if (cur->sk_flags & SK_ISNULL) /* NOT_NULL tupdatum, NULL arrdatum */
236 : : {
237 [ + + ]: 30510 : if (cur->sk_flags & SK_BT_NULLS_FIRST)
238 : 54 : result = 1; /* NOT_NULL ">" NULL */
239 : : else
240 : 30456 : result = -1; /* NOT_NULL "<" NULL */
241 : : }
242 : : else
243 : : {
244 : : /*
245 : : * Like _bt_compare, we need to be careful of cross-type comparisons,
246 : : * so the left value has to be the value that came from an index tuple
247 : : */
248 : 415014 : result = DatumGetInt32(FunctionCall2Coll(orderproc, cur->sk_collation,
249 : : tupdatum, arrdatum));
250 : :
251 : : /*
252 : : * We flip the sign by following the obvious rule: flip whenever the
253 : : * column is a DESC column.
254 : : *
255 : : * _bt_compare does it the wrong way around (flip when *ASC*) in order
256 : : * to compensate for passing its orderproc arguments backwards. We
257 : : * don't need to play these games because we find it natural to pass
258 : : * tupdatum as the left value (and arrdatum as the right value).
259 : : */
260 [ + + ]: 415014 : if (cur->sk_flags & SK_BT_DESC)
261 [ + + ]: 52029 : INVERT_COMPARE_RESULT(result);
262 : : }
263 : :
264 : 445755 : return result;
265 : : }
266 : :
267 : : /*
268 : : * _bt_binsrch_array_skey() -- Binary search for next matching array key
269 : : *
270 : : * Returns an index to the first array element >= caller's tupdatum argument.
271 : : * This convention is more natural for forwards scan callers, but that can't
272 : : * really matter to backwards scan callers. Both callers require handling for
273 : : * the case where the match we return is < tupdatum, and symmetric handling
274 : : * for the case where our best match is > tupdatum.
275 : : *
276 : : * Also sets *set_elem_result to the result _bt_compare_array_skey returned
277 : : * when we used it to compare the matching array element to tupdatum/tupnull.
278 : : *
279 : : * cur_elem_trig indicates if array advancement was triggered by this array's
280 : : * scan key, and that the array is for a required scan key. We can apply this
281 : : * information to find the next matching array element in the current scan
282 : : * direction using far fewer comparisons (fewer on average, compared to naive
283 : : * binary search). This scheme takes advantage of an important property of
284 : : * required arrays: required arrays always advance in lockstep with the index
285 : : * scan's progress through the index's key space.
286 : : */
287 : : int
288 : 15661 : _bt_binsrch_array_skey(FmgrInfo *orderproc,
289 : : bool cur_elem_trig, ScanDirection dir,
290 : : Datum tupdatum, bool tupnull,
291 : : BTArrayKeyInfo *array, ScanKey cur,
292 : : int32 *set_elem_result)
293 : : {
294 : 15661 : int low_elem = 0,
295 : 15661 : mid_elem = -1,
296 : 15661 : high_elem = array->num_elems - 1,
297 : 15661 : result = 0;
298 : : Datum arrdatum;
299 : :
300 [ - + ]: 15661 : Assert(cur->sk_flags & SK_SEARCHARRAY);
155 301 [ - + ]: 15661 : Assert(!(cur->sk_flags & SK_BT_SKIP));
302 [ - + ]: 15661 : Assert(!(cur->sk_flags & SK_ISNULL)); /* SAOP arrays never have NULLs */
236 303 [ - + ]: 15661 : Assert(cur->sk_strategy == BTEqualStrategyNumber);
304 : :
305 [ + + ]: 15661 : if (cur_elem_trig)
306 : : {
307 [ - + ]: 15502 : Assert(!ScanDirectionIsNoMovement(dir));
308 [ - + ]: 15502 : Assert(cur->sk_flags & SK_BT_REQFWD);
309 : :
310 : : /*
311 : : * When the scan key that triggered array advancement is a required
312 : : * array scan key, it is now certain that the current array element
313 : : * (plus all prior elements relative to the current scan direction)
314 : : * cannot possibly be at or ahead of the corresponding tuple value.
315 : : * (_bt_checkkeys must have called _bt_tuple_before_array_skeys, which
316 : : * makes sure this is true as a condition of advancing the arrays.)
317 : : *
318 : : * This makes it safe to exclude array elements up to and including
319 : : * the former-current array element from our search.
320 : : *
321 : : * Separately, when array advancement was triggered by a required scan
322 : : * key, the array element immediately after the former-current element
323 : : * is often either an exact tupdatum match, or a "close by" near-match
324 : : * (a near-match tupdatum is one whose key space falls _between_ the
325 : : * former-current and new-current array elements). We'll detect both
326 : : * cases via an optimistic comparison of the new search lower bound
327 : : * (or new search upper bound in the case of backwards scans).
328 : : */
329 [ + + ]: 15502 : if (ScanDirectionIsForward(dir))
330 : : {
331 : 15472 : low_elem = array->cur_elem + 1; /* old cur_elem exhausted */
332 : :
333 : : /* Compare prospective new cur_elem (also the new lower bound) */
334 [ + + ]: 15472 : if (high_elem >= low_elem)
335 : : {
336 : 11558 : arrdatum = array->elem_values[low_elem];
337 : 11558 : result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
338 : : arrdatum, cur);
339 : :
340 [ + + ]: 11558 : if (result <= 0)
341 : : {
342 : : /* Optimistic comparison optimization worked out */
343 : 11514 : *set_elem_result = result;
344 : 11514 : return low_elem;
345 : : }
346 : 44 : mid_elem = low_elem;
347 : 44 : low_elem++; /* this cur_elem exhausted, too */
348 : : }
349 : :
350 [ + + ]: 3958 : if (high_elem < low_elem)
351 : : {
352 : : /* Caller needs to perform "beyond end" array advancement */
353 : 3917 : *set_elem_result = 1;
354 : 3917 : return high_elem;
355 : : }
356 : : }
357 : : else
358 : : {
359 : 30 : high_elem = array->cur_elem - 1; /* old cur_elem exhausted */
360 : :
361 : : /* Compare prospective new cur_elem (also the new upper bound) */
362 [ + + ]: 30 : if (high_elem >= low_elem)
363 : : {
364 : 21 : arrdatum = array->elem_values[high_elem];
365 : 21 : result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
366 : : arrdatum, cur);
367 : :
368 [ + + ]: 21 : if (result >= 0)
369 : : {
370 : : /* Optimistic comparison optimization worked out */
371 : 15 : *set_elem_result = result;
372 : 15 : return high_elem;
373 : : }
374 : 6 : mid_elem = high_elem;
375 : 6 : high_elem--; /* this cur_elem exhausted, too */
376 : : }
377 : :
378 [ + - ]: 15 : if (high_elem < low_elem)
379 : : {
380 : : /* Caller needs to perform "beyond end" array advancement */
381 : 15 : *set_elem_result = -1;
382 : 15 : return low_elem;
383 : : }
384 : : }
385 : : }
386 : :
387 [ + + ]: 352 : while (high_elem > low_elem)
388 : : {
389 : 221 : mid_elem = low_elem + ((high_elem - low_elem) / 2);
390 : 221 : arrdatum = array->elem_values[mid_elem];
391 : :
392 : 221 : result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
393 : : arrdatum, cur);
394 : :
395 [ + + ]: 221 : if (result == 0)
396 : : {
397 : : /*
398 : : * It's safe to quit as soon as we see an equal array element.
399 : : * This often saves an extra comparison or two...
400 : : */
401 : 69 : low_elem = mid_elem;
402 : 69 : break;
403 : : }
404 : :
405 [ + + ]: 152 : if (result > 0)
406 : 137 : low_elem = mid_elem + 1;
407 : : else
408 : 15 : high_elem = mid_elem;
409 : : }
410 : :
411 : : /*
412 : : * ...but our caller also cares about how its searched-for tuple datum
413 : : * compares to the low_elem datum. Must always set *set_elem_result with
414 : : * the result of that comparison specifically.
415 : : */
416 [ + + ]: 200 : if (low_elem != mid_elem)
417 : 122 : result = _bt_compare_array_skey(orderproc, tupdatum, tupnull,
418 : 122 : array->elem_values[low_elem], cur);
419 : :
420 : 200 : *set_elem_result = result;
421 : :
422 : 200 : return low_elem;
423 : : }
424 : :
425 : : /*
426 : : * _bt_binsrch_skiparray_skey() -- "Binary search" within a skip array
427 : : *
428 : : * Does not return an index into the array, since skip arrays don't really
429 : : * contain elements (they generate their array elements procedurally instead).
430 : : * Our interface matches that of _bt_binsrch_array_skey in every other way.
431 : : *
432 : : * Sets *set_elem_result just like _bt_binsrch_array_skey would with a true
433 : : * array. The value 0 indicates that tupdatum/tupnull is within the range of
434 : : * the skip array. We return -1 when tupdatum/tupnull is lower that any value
435 : : * within the range of the array, and 1 when it is higher than every value.
436 : : * Caller should pass *set_elem_result to _bt_skiparray_set_element to advance
437 : : * the array.
438 : : *
439 : : * cur_elem_trig indicates if array advancement was triggered by this array's
440 : : * scan key. We use this to optimize-away comparisons that are known by our
441 : : * caller to be unnecessary from context, just like _bt_binsrch_array_skey.
442 : : */
443 : : static void
155 444 : 84832 : _bt_binsrch_skiparray_skey(bool cur_elem_trig, ScanDirection dir,
445 : : Datum tupdatum, bool tupnull,
446 : : BTArrayKeyInfo *array, ScanKey cur,
447 : : int32 *set_elem_result)
448 : : {
449 [ - + ]: 84832 : Assert(cur->sk_flags & SK_BT_SKIP);
450 [ - + ]: 84832 : Assert(cur->sk_flags & SK_SEARCHARRAY);
451 [ - + ]: 84832 : Assert(cur->sk_flags & SK_BT_REQFWD);
452 [ - + ]: 84832 : Assert(array->num_elems == -1);
453 [ - + ]: 84832 : Assert(!ScanDirectionIsNoMovement(dir));
454 : :
455 [ + + ]: 84832 : if (array->null_elem)
456 : : {
457 [ + - - + ]: 71873 : Assert(!array->low_compare && !array->high_compare);
458 : :
459 : 71873 : *set_elem_result = 0;
460 : 71873 : return;
461 : : }
462 : :
463 [ + + ]: 12959 : if (tupnull) /* NULL tupdatum */
464 : : {
465 [ - + ]: 12 : if (cur->sk_flags & SK_BT_NULLS_FIRST)
155 pg@bowt.ie 466 :UBC 0 : *set_elem_result = -1; /* NULL "<" NOT_NULL */
467 : : else
155 pg@bowt.ie 468 :CBC 12 : *set_elem_result = 1; /* NULL ">" NOT_NULL */
469 : 12 : return;
470 : : }
471 : :
472 : : /*
473 : : * Array inequalities determine whether tupdatum is within the range of
474 : : * caller's skip array
475 : : */
476 : 12947 : *set_elem_result = 0;
477 [ + + ]: 12947 : if (ScanDirectionIsForward(dir))
478 : : {
479 : : /*
480 : : * Evaluate low_compare first (unless cur_elem_trig tells us that it
481 : : * cannot possibly fail to be satisfied), then evaluate high_compare
482 : : */
483 [ + + + + ]: 12914 : if (!cur_elem_trig && array->low_compare &&
484 [ - + ]: 482 : !DatumGetBool(FunctionCall2Coll(&array->low_compare->sk_func,
485 : 482 : array->low_compare->sk_collation,
486 : : tupdatum,
487 : 482 : array->low_compare->sk_argument)))
155 pg@bowt.ie 488 :UBC 0 : *set_elem_result = -1;
155 pg@bowt.ie 489 [ + + ]:CBC 12914 : else if (array->high_compare &&
490 [ + + ]: 4757 : !DatumGetBool(FunctionCall2Coll(&array->high_compare->sk_func,
491 : 4757 : array->high_compare->sk_collation,
492 : : tupdatum,
493 : 4757 : array->high_compare->sk_argument)))
494 : 3207 : *set_elem_result = 1;
495 : : }
496 : : else
497 : : {
498 : : /*
499 : : * Evaluate high_compare first (unless cur_elem_trig tells us that it
500 : : * cannot possibly fail to be satisfied), then evaluate low_compare
501 : : */
502 [ + + + + ]: 33 : if (!cur_elem_trig && array->high_compare &&
503 [ - + ]: 6 : !DatumGetBool(FunctionCall2Coll(&array->high_compare->sk_func,
504 : 6 : array->high_compare->sk_collation,
505 : : tupdatum,
506 : 6 : array->high_compare->sk_argument)))
155 pg@bowt.ie 507 :UBC 0 : *set_elem_result = 1;
155 pg@bowt.ie 508 [ + + ]:CBC 33 : else if (array->low_compare &&
509 [ - + ]: 15 : !DatumGetBool(FunctionCall2Coll(&array->low_compare->sk_func,
510 : 15 : array->low_compare->sk_collation,
511 : : tupdatum,
512 : 15 : array->low_compare->sk_argument)))
155 pg@bowt.ie 513 :UBC 0 : *set_elem_result = -1;
514 : : }
515 : :
516 : : /*
517 : : * Assert that any keys that were assumed to be satisfied already (due to
518 : : * caller passing cur_elem_trig=true) really are satisfied as expected
519 : : */
520 : : #ifdef USE_ASSERT_CHECKING
155 pg@bowt.ie 521 [ + + ]:CBC 12947 : if (cur_elem_trig)
522 : : {
523 [ + + + + ]: 8847 : if (ScanDirectionIsForward(dir) && array->low_compare)
524 [ - + ]: 1176 : Assert(DatumGetBool(FunctionCall2Coll(&array->low_compare->sk_func,
525 : : array->low_compare->sk_collation,
526 : : tupdatum,
527 : : array->low_compare->sk_argument)));
528 : :
529 [ + + + + ]: 8847 : if (ScanDirectionIsBackward(dir) && array->high_compare)
530 [ - + ]: 3 : Assert(DatumGetBool(FunctionCall2Coll(&array->high_compare->sk_func,
531 : : array->high_compare->sk_collation,
532 : : tupdatum,
533 : : array->high_compare->sk_argument)));
534 : : }
535 : : #endif
536 : : }
537 : :
538 : : /*
539 : : * _bt_skiparray_set_element() -- Set skip array scan key's sk_argument
540 : : *
541 : : * Caller passes set_elem_result returned by _bt_binsrch_skiparray_skey for
542 : : * caller's tupdatum/tupnull.
543 : : *
544 : : * We copy tupdatum/tupnull into skey's sk_argument iff set_elem_result == 0.
545 : : * Otherwise, we set skey to either the lowest or highest value that's within
546 : : * the range of caller's skip array (whichever is the best available match to
547 : : * tupdatum/tupnull that is still within the range of the skip array according
548 : : * to _bt_binsrch_skiparray_skey/set_elem_result).
549 : : */
550 : : static void
551 : 76285 : _bt_skiparray_set_element(Relation rel, ScanKey skey, BTArrayKeyInfo *array,
552 : : int32 set_elem_result, Datum tupdatum, bool tupnull)
553 : : {
554 [ - + ]: 76285 : Assert(skey->sk_flags & SK_BT_SKIP);
555 [ - + ]: 76285 : Assert(skey->sk_flags & SK_SEARCHARRAY);
556 : :
557 [ + + ]: 76285 : if (set_elem_result)
558 : : {
559 : : /* tupdatum/tupnull is out of the range of the skip array */
560 [ - + ]: 321 : Assert(!array->null_elem);
561 : :
562 : 321 : _bt_array_set_low_or_high(rel, skey, array, set_elem_result < 0);
563 : 321 : return;
564 : : }
565 : :
566 : : /* Advance skip array to tupdatum (or tupnull) value */
567 [ + + ]: 75964 : if (unlikely(tupnull))
568 : : {
569 : 18 : _bt_skiparray_set_isnull(rel, skey, array);
570 : 18 : return;
571 : : }
572 : :
573 : : /* Free memory previously allocated for sk_argument if needed */
574 [ + + + + ]: 75946 : if (!array->attbyval && skey->sk_argument)
575 : 37959 : pfree(DatumGetPointer(skey->sk_argument));
576 : :
577 : : /* tupdatum becomes new sk_argument/new current element */
578 : 75946 : skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL |
579 : : SK_BT_MINVAL | SK_BT_MAXVAL |
580 : : SK_BT_NEXT | SK_BT_PRIOR);
581 : 75946 : skey->sk_argument = datumCopy(tupdatum, array->attbyval, array->attlen);
582 : : }
583 : :
584 : : /*
585 : : * _bt_skiparray_set_isnull() -- set skip array scan key to NULL
586 : : */
587 : : static void
588 : 24 : _bt_skiparray_set_isnull(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
589 : : {
590 [ - + ]: 24 : Assert(skey->sk_flags & SK_BT_SKIP);
591 [ - + ]: 24 : Assert(skey->sk_flags & SK_SEARCHARRAY);
592 [ + - + - : 24 : Assert(array->null_elem && !array->low_compare && !array->high_compare);
- + ]
593 : :
594 : : /* Free memory previously allocated for sk_argument if needed */
595 [ + + + - ]: 24 : if (!array->attbyval && skey->sk_argument)
596 : 3 : pfree(DatumGetPointer(skey->sk_argument));
597 : :
598 : : /* NULL becomes new sk_argument/new current element */
599 : 24 : skey->sk_argument = (Datum) 0;
600 : 24 : skey->sk_flags &= ~(SK_BT_MINVAL | SK_BT_MAXVAL |
601 : : SK_BT_NEXT | SK_BT_PRIOR);
602 : 24 : skey->sk_flags |= (SK_SEARCHNULL | SK_ISNULL);
603 : 24 : }
604 : :
605 : : /*
606 : : * _bt_start_array_keys() -- Initialize array keys at start of a scan
607 : : *
608 : : * Set up the cur_elem counters and fill in the first sk_argument value for
609 : : * each array scankey.
610 : : */
611 : : void
236 612 : 40587 : _bt_start_array_keys(IndexScanDesc scan, ScanDirection dir)
613 : : {
155 614 : 40587 : Relation rel = scan->indexRelation;
518 615 : 40587 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
616 : :
236 617 [ - + ]: 40587 : Assert(so->numArrayKeys);
518 618 [ - + ]: 40587 : Assert(so->qual_ok);
619 : :
155 620 [ + + ]: 81488 : for (int i = 0; i < so->numArrayKeys; i++)
621 : : {
622 : 40901 : BTArrayKeyInfo *array = &so->arrayKeys[i];
623 : 40901 : ScanKey skey = &so->keyData[array->scan_key];
624 : :
236 625 [ - + ]: 40901 : Assert(skey->sk_flags & SK_SEARCHARRAY);
626 : :
155 627 : 40901 : _bt_array_set_low_or_high(rel, skey, array,
628 : : ScanDirectionIsForward(dir));
629 : : }
325 630 : 40587 : so->scanBehind = so->oppositeDirCheck = false; /* reset */
4727 tgl@sss.pgh.pa.us 631 : 40587 : }
632 : :
633 : : /*
634 : : * _bt_array_set_low_or_high() -- Set array scan key to lowest/highest element
635 : : *
636 : : * Caller also passes associated scan key, which will have its argument set to
637 : : * the lowest/highest array value in passing.
638 : : */
639 : : static void
155 pg@bowt.ie 640 : 46519 : _bt_array_set_low_or_high(Relation rel, ScanKey skey, BTArrayKeyInfo *array,
641 : : bool low_not_high)
642 : : {
643 [ - + ]: 46519 : Assert(skey->sk_flags & SK_SEARCHARRAY);
644 : :
645 [ + + ]: 46519 : if (array->num_elems != -1)
646 : : {
647 : : /* set low or high element for SAOP array */
648 : 41992 : int set_elem = 0;
649 : :
650 [ - + ]: 41992 : Assert(!(skey->sk_flags & SK_BT_SKIP));
651 : :
652 [ + + ]: 41992 : if (!low_not_high)
653 : 4037 : set_elem = array->num_elems - 1;
654 : :
655 : : /*
656 : : * Just copy over array datum (only skip arrays require freeing and
657 : : * allocating memory for sk_argument)
658 : : */
659 : 41992 : array->cur_elem = set_elem;
660 : 41992 : skey->sk_argument = array->elem_values[set_elem];
661 : :
662 : 41992 : return;
663 : : }
664 : :
665 : : /* set low or high element for skip array */
666 [ - + ]: 4527 : Assert(skey->sk_flags & SK_BT_SKIP);
667 [ - + ]: 4527 : Assert(array->num_elems == -1);
668 : :
669 : : /* Free memory previously allocated for sk_argument if needed */
670 [ + + + + ]: 4527 : if (!array->attbyval && skey->sk_argument)
671 : 947 : pfree(DatumGetPointer(skey->sk_argument));
672 : :
673 : : /* Reset flags */
674 : 4527 : skey->sk_argument = (Datum) 0;
675 : 4527 : skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL |
676 : : SK_BT_MINVAL | SK_BT_MAXVAL |
677 : : SK_BT_NEXT | SK_BT_PRIOR);
678 : :
679 [ + + ]: 4527 : if (array->null_elem &&
680 [ + + ]: 3630 : (low_not_high == ((skey->sk_flags & SK_BT_NULLS_FIRST) != 0)))
681 : : {
682 : : /* Requested element (either lowest or highest) has the value NULL */
683 : 485 : skey->sk_flags |= (SK_SEARCHNULL | SK_ISNULL);
684 : : }
685 [ + + ]: 4042 : else if (low_not_high)
686 : : {
687 : : /* Setting array to lowest element (according to low_compare) */
688 : 3682 : skey->sk_flags |= SK_BT_MINVAL;
689 : : }
690 : : else
691 : : {
692 : : /* Setting array to highest element (according to high_compare) */
693 : 360 : skey->sk_flags |= SK_BT_MAXVAL;
694 : : }
695 : : }
696 : :
697 : : /*
698 : : * _bt_array_decrement() -- decrement array scan key's sk_argument
699 : : *
700 : : * Return value indicates whether caller's array was successfully decremented.
701 : : * Cannot decrement an array whose current element is already the first one.
702 : : */
703 : : static bool
704 : 456 : _bt_array_decrement(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
705 : : {
706 : 456 : bool uflow = false;
707 : : Datum dec_sk_argument;
708 : :
709 [ - + ]: 456 : Assert(skey->sk_flags & SK_SEARCHARRAY);
710 [ - + ]: 456 : Assert(!(skey->sk_flags & (SK_BT_MAXVAL | SK_BT_NEXT | SK_BT_PRIOR)));
711 : :
712 : : /* SAOP array? */
713 [ + + ]: 456 : if (array->num_elems != -1)
714 : : {
715 [ - + ]: 18 : Assert(!(skey->sk_flags & (SK_BT_SKIP | SK_BT_MINVAL | SK_BT_MAXVAL)));
716 [ + + ]: 18 : if (array->cur_elem > 0)
717 : : {
718 : : /*
719 : : * Just decrement current element, and assign its datum to skey
720 : : * (only skip arrays need us to free existing sk_argument memory)
721 : : */
722 : 3 : array->cur_elem--;
723 : 3 : skey->sk_argument = array->elem_values[array->cur_elem];
724 : :
725 : : /* Successfully decremented array */
726 : 3 : return true;
727 : : }
728 : :
729 : : /* Cannot decrement to before first array element */
730 : 15 : return false;
731 : : }
732 : :
733 : : /* Nope, this is a skip array */
734 [ - + ]: 438 : Assert(skey->sk_flags & SK_BT_SKIP);
735 : :
736 : : /*
737 : : * The sentinel value that represents the minimum value within the range
738 : : * of a skip array (often just -inf) is never decrementable
739 : : */
740 [ - + ]: 438 : if (skey->sk_flags & SK_BT_MINVAL)
155 pg@bowt.ie 741 :UBC 0 : return false;
742 : :
743 : : /*
744 : : * When the current array element is NULL, and the lowest sorting value in
745 : : * the index is also NULL, we cannot decrement before first array element
746 : : */
155 pg@bowt.ie 747 [ + + - + ]:CBC 438 : if ((skey->sk_flags & SK_ISNULL) && (skey->sk_flags & SK_BT_NULLS_FIRST))
155 pg@bowt.ie 748 :UBC 0 : return false;
749 : :
750 : : /*
751 : : * Opclasses without skip support "decrement" the scan key's current
752 : : * element by setting the PRIOR flag. The true prior value is determined
753 : : * by repositioning to the last index tuple < existing sk_argument/current
754 : : * array element. Note that this works in the usual way when the scan key
755 : : * is already marked ISNULL (i.e. when the current element is NULL).
756 : : */
155 pg@bowt.ie 757 [ + + ]:CBC 438 : if (!array->sksup)
758 : : {
759 : : /* Successfully "decremented" array */
760 : 6 : skey->sk_flags |= SK_BT_PRIOR;
761 : 6 : return true;
762 : : }
763 : :
764 : : /*
765 : : * Opclasses with skip support directly decrement sk_argument
766 : : */
767 [ + + ]: 432 : if (skey->sk_flags & SK_ISNULL)
768 : : {
769 [ - + ]: 3 : Assert(!(skey->sk_flags & SK_BT_NULLS_FIRST));
770 : :
771 : : /*
772 : : * Existing sk_argument/array element is NULL (for an IS NULL qual).
773 : : *
774 : : * "Decrement" from NULL to the high_elem value provided by opclass
775 : : * skip support routine.
776 : : */
777 : 3 : skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL);
778 : 6 : skey->sk_argument = datumCopy(array->sksup->high_elem,
779 : 3 : array->attbyval, array->attlen);
780 : 3 : return true;
781 : : }
782 : :
783 : : /*
784 : : * Ask opclass support routine to provide decremented copy of existing
785 : : * non-NULL sk_argument
786 : : */
787 : 429 : dec_sk_argument = array->sksup->decrement(rel, skey->sk_argument, &uflow);
788 [ - + ]: 429 : if (unlikely(uflow))
789 : : {
790 : : /* dec_sk_argument has undefined value (so no pfree) */
155 pg@bowt.ie 791 [ # # # # ]:UBC 0 : if (array->null_elem && (skey->sk_flags & SK_BT_NULLS_FIRST))
792 : : {
793 : 0 : _bt_skiparray_set_isnull(rel, skey, array);
794 : :
795 : : /* Successfully "decremented" array to NULL */
796 : 0 : return true;
797 : : }
798 : :
799 : : /* Cannot decrement to before first array element */
800 : 0 : return false;
801 : : }
802 : :
803 : : /*
804 : : * Successfully decremented sk_argument to a non-NULL value. Make sure
805 : : * that the decremented value is still within the range of the array.
806 : : */
155 pg@bowt.ie 807 [ + + ]:CBC 429 : if (array->low_compare &&
808 [ + + ]: 6 : !DatumGetBool(FunctionCall2Coll(&array->low_compare->sk_func,
809 : 6 : array->low_compare->sk_collation,
810 : : dec_sk_argument,
811 : 6 : array->low_compare->sk_argument)))
812 : : {
813 : : /* Keep existing sk_argument after all */
814 [ - + ]: 3 : if (!array->attbyval)
155 pg@bowt.ie 815 :UBC 0 : pfree(DatumGetPointer(dec_sk_argument));
816 : :
817 : : /* Cannot decrement to before first array element */
155 pg@bowt.ie 818 :CBC 3 : return false;
819 : : }
820 : :
821 : : /* Accept value returned by opclass decrement callback */
822 [ - + - - ]: 426 : if (!array->attbyval && skey->sk_argument)
155 pg@bowt.ie 823 :UBC 0 : pfree(DatumGetPointer(skey->sk_argument));
155 pg@bowt.ie 824 :CBC 426 : skey->sk_argument = dec_sk_argument;
825 : :
826 : : /* Successfully decremented array */
827 : 426 : return true;
828 : : }
829 : :
830 : : /*
831 : : * _bt_array_increment() -- increment array scan key's sk_argument
832 : : *
833 : : * Return value indicates whether caller's array was successfully incremented.
834 : : * Cannot increment an array whose current element is already the final one.
835 : : */
836 : : static bool
837 : 15540 : _bt_array_increment(Relation rel, ScanKey skey, BTArrayKeyInfo *array)
838 : : {
839 : 15540 : bool oflow = false;
840 : : Datum inc_sk_argument;
841 : :
842 [ - + ]: 15540 : Assert(skey->sk_flags & SK_SEARCHARRAY);
843 [ - + ]: 15540 : Assert(!(skey->sk_flags & (SK_BT_MINVAL | SK_BT_NEXT | SK_BT_PRIOR)));
844 : :
845 : : /* SAOP array? */
846 [ + + ]: 15540 : if (array->num_elems != -1)
847 : : {
848 [ - + ]: 4058 : Assert(!(skey->sk_flags & (SK_BT_SKIP | SK_BT_MINVAL | SK_BT_MAXVAL)));
849 [ + + ]: 4058 : if (array->cur_elem < array->num_elems - 1)
850 : : {
851 : : /*
852 : : * Just increment current element, and assign its datum to skey
853 : : * (only skip arrays need us to free existing sk_argument memory)
854 : : */
855 : 28 : array->cur_elem++;
856 : 28 : skey->sk_argument = array->elem_values[array->cur_elem];
857 : :
858 : : /* Successfully incremented array */
859 : 28 : return true;
860 : : }
861 : :
862 : : /* Cannot increment past final array element */
863 : 4030 : return false;
864 : : }
865 : :
866 : : /* Nope, this is a skip array */
867 [ - + ]: 11482 : Assert(skey->sk_flags & SK_BT_SKIP);
868 : :
869 : : /*
870 : : * The sentinel value that represents the maximum value within the range
871 : : * of a skip array (often just +inf) is never incrementable
872 : : */
873 [ + + ]: 11482 : if (skey->sk_flags & SK_BT_MAXVAL)
874 : 321 : return false;
875 : :
876 : : /*
877 : : * When the current array element is NULL, and the highest sorting value
878 : : * in the index is also NULL, we cannot increment past the final element
879 : : */
880 [ + + + + ]: 11161 : if ((skey->sk_flags & SK_ISNULL) && !(skey->sk_flags & SK_BT_NULLS_FIRST))
881 : 220 : return false;
882 : :
883 : : /*
884 : : * Opclasses without skip support "increment" the scan key's current
885 : : * element by setting the NEXT flag. The true next value is determined by
886 : : * repositioning to the first index tuple > existing sk_argument/current
887 : : * array element. Note that this works in the usual way when the scan key
888 : : * is already marked ISNULL (i.e. when the current element is NULL).
889 : : */
890 [ + + ]: 10941 : if (!array->sksup)
891 : : {
892 : : /* Successfully "incremented" array */
893 : 7291 : skey->sk_flags |= SK_BT_NEXT;
894 : 7291 : return true;
895 : : }
896 : :
897 : : /*
898 : : * Opclasses with skip support directly increment sk_argument
899 : : */
900 [ + + ]: 3650 : if (skey->sk_flags & SK_ISNULL)
901 : : {
902 [ - + ]: 18 : Assert(skey->sk_flags & SK_BT_NULLS_FIRST);
903 : :
904 : : /*
905 : : * Existing sk_argument/array element is NULL (for an IS NULL qual).
906 : : *
907 : : * "Increment" from NULL to the low_elem value provided by opclass
908 : : * skip support routine.
909 : : */
910 : 18 : skey->sk_flags &= ~(SK_SEARCHNULL | SK_ISNULL);
911 : 36 : skey->sk_argument = datumCopy(array->sksup->low_elem,
912 : 18 : array->attbyval, array->attlen);
913 : 18 : return true;
914 : : }
915 : :
916 : : /*
917 : : * Ask opclass support routine to provide incremented copy of existing
918 : : * non-NULL sk_argument
919 : : */
920 : 3632 : inc_sk_argument = array->sksup->increment(rel, skey->sk_argument, &oflow);
921 [ + + ]: 3632 : if (unlikely(oflow))
922 : : {
923 : : /* inc_sk_argument has undefined value (so no pfree) */
924 [ + - + + ]: 15 : if (array->null_elem && !(skey->sk_flags & SK_BT_NULLS_FIRST))
925 : : {
926 : 6 : _bt_skiparray_set_isnull(rel, skey, array);
927 : :
928 : : /* Successfully "incremented" array to NULL */
929 : 6 : return true;
930 : : }
931 : :
932 : : /* Cannot increment past final array element */
933 : 9 : return false;
934 : : }
935 : :
936 : : /*
937 : : * Successfully incremented sk_argument to a non-NULL value. Make sure
938 : : * that the incremented value is still within the range of the array.
939 : : */
940 [ + + ]: 3617 : if (array->high_compare &&
941 [ + + ]: 21 : !DatumGetBool(FunctionCall2Coll(&array->high_compare->sk_func,
942 : 21 : array->high_compare->sk_collation,
943 : : inc_sk_argument,
944 : 21 : array->high_compare->sk_argument)))
945 : : {
946 : : /* Keep existing sk_argument after all */
947 [ - + ]: 6 : if (!array->attbyval)
155 pg@bowt.ie 948 :UBC 0 : pfree(DatumGetPointer(inc_sk_argument));
949 : :
950 : : /* Cannot increment past final array element */
155 pg@bowt.ie 951 :CBC 6 : return false;
952 : : }
953 : :
954 : : /* Accept value returned by opclass increment callback */
955 [ - + - - ]: 3611 : if (!array->attbyval && skey->sk_argument)
155 pg@bowt.ie 956 :UBC 0 : pfree(DatumGetPointer(skey->sk_argument));
155 pg@bowt.ie 957 :CBC 3611 : skey->sk_argument = inc_sk_argument;
958 : :
959 : : /* Successfully incremented array */
960 : 3611 : return true;
961 : : }
962 : :
963 : : /*
964 : : * _bt_advance_array_keys_increment() -- Advance to next set of array elements
965 : : *
966 : : * Advances the array keys by a single increment in the current scan
967 : : * direction. When there are multiple array keys this can roll over from the
968 : : * lowest order array to higher order arrays.
969 : : *
970 : : * Returns true if there is another set of values to consider, false if not.
971 : : * On true result, the scankeys are initialized with the next set of values.
972 : : * On false result, the scankeys stay the same, and the array keys are not
973 : : * advanced (every array remains at its final element for scan direction).
974 : : */
975 : : static bool
976 : 15425 : _bt_advance_array_keys_increment(IndexScanDesc scan, ScanDirection dir,
977 : : bool *skip_array_set)
978 : : {
979 : 15425 : Relation rel = scan->indexRelation;
4727 tgl@sss.pgh.pa.us 980 : 15425 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
981 : :
982 : : /*
983 : : * We must advance the last array key most quickly, since it will
984 : : * correspond to the lowest-order index column among the available
985 : : * qualifications
986 : : */
518 pg@bowt.ie 987 [ + + ]: 20029 : for (int i = so->numArrayKeys - 1; i >= 0; i--)
988 : : {
155 989 : 15996 : BTArrayKeyInfo *array = &so->arrayKeys[i];
990 : 15996 : ScanKey skey = &so->keyData[array->scan_key];
991 : :
992 [ + + ]: 15996 : if (array->num_elems == -1)
993 : 11920 : *skip_array_set = true;
994 : :
995 [ + + ]: 15996 : if (ScanDirectionIsForward(dir))
996 : : {
997 [ + + ]: 15540 : if (_bt_array_increment(rel, skey, array))
998 : 10954 : return true;
999 : : }
1000 : : else
1001 : : {
1002 [ + + ]: 456 : if (_bt_array_decrement(rel, skey, array))
1003 : 438 : return true;
1004 : : }
1005 : :
1006 : : /*
1007 : : * Couldn't increment (or decrement) array. Handle array roll over.
1008 : : *
1009 : : * Start over at the array's lowest sorting value (or its highest
1010 : : * value, for backward scans)...
1011 : : */
1012 : 4604 : _bt_array_set_low_or_high(rel, skey, array,
1013 : : ScanDirectionIsForward(dir));
1014 : :
1015 : : /* ...then increment (or decrement) next most significant array */
1016 : : }
1017 : :
1018 : : /*
1019 : : * The array keys are now exhausted.
1020 : : *
1021 : : * Restore the array keys to the state they were in immediately before we
1022 : : * were called. This ensures that the arrays only ever ratchet in the
1023 : : * current scan direction.
1024 : : *
1025 : : * Without this, scans could overlook matching tuples when the scan
1026 : : * direction gets reversed just before btgettuple runs out of items to
1027 : : * return, but just after _bt_readpage prepares all the items from the
1028 : : * scan's final page in so->currPos. When we're on the final page it is
1029 : : * typical for so->currPos to get invalidated once btgettuple finally
1030 : : * returns false, which'll effectively invalidate the scan's array keys.
1031 : : * That hasn't happened yet, though -- and in general it may never happen.
1032 : : */
518 1033 : 4033 : _bt_start_array_keys(scan, -dir);
1034 : :
1035 : 4033 : return false;
1036 : : }
1037 : :
1038 : : /*
1039 : : * _bt_tuple_before_array_skeys() -- too early to advance required arrays?
1040 : : *
1041 : : * We always compare the tuple using the current array keys (which we assume
1042 : : * are already set in so->keyData[]). readpagetup indicates if tuple is the
1043 : : * scan's current _bt_readpage-wise tuple.
1044 : : *
1045 : : * readpagetup callers must only call here when _bt_check_compare already set
1046 : : * continuescan=false. We help these callers deal with _bt_check_compare's
1047 : : * inability to distinguish between the < and > cases (it uses equality
1048 : : * operator scan keys, whereas we use 3-way ORDER procs). These callers pass
1049 : : * a _bt_check_compare-set sktrig value that indicates which scan key
1050 : : * triggered the call (!readpagetup callers just pass us sktrig=0 instead).
1051 : : * This information allows us to avoid wastefully checking earlier scan keys
1052 : : * that were already deemed to have been satisfied inside _bt_check_compare.
1053 : : *
1054 : : * Returns false when caller's tuple is >= the current required equality scan
1055 : : * keys (or <=, in the case of backwards scans). This happens to readpagetup
1056 : : * callers when the scan has reached the point of needing its array keys
1057 : : * advanced; caller will need to advance required and non-required arrays at
1058 : : * scan key offsets >= sktrig, plus scan keys < sktrig iff sktrig rolls over.
1059 : : * (When we return false to readpagetup callers, tuple can only be == current
1060 : : * required equality scan keys when caller's sktrig indicates that the arrays
1061 : : * need to be advanced due to an unsatisfied required inequality key trigger.)
1062 : : *
1063 : : * Returns true when caller passes a tuple that is < the current set of
1064 : : * equality keys for the most significant non-equal required scan key/column
1065 : : * (or > the keys, during backwards scans). This happens to readpagetup
1066 : : * callers when tuple is still before the start of matches for the scan's
1067 : : * required equality strategy scan keys. (sktrig can't have indicated that an
1068 : : * inequality strategy scan key wasn't satisfied in _bt_check_compare when we
1069 : : * return true. In fact, we automatically return false when passed such an
1070 : : * inequality sktrig by readpagetup callers -- _bt_check_compare's initial
1071 : : * continuescan=false doesn't really need to be confirmed here by us.)
1072 : : *
1073 : : * !readpagetup callers optionally pass us *scanBehind, which tracks whether
1074 : : * any missing truncated attributes might have affected array advancement
1075 : : * (compared to what would happen if it was shown the first non-pivot tuple on
1076 : : * the page to the right of caller's finaltup/high key tuple instead). It's
1077 : : * only possible that we'll set *scanBehind to true when caller passes us a
1078 : : * pivot tuple (with truncated -inf attributes) that we return false for.
1079 : : */
1080 : : static bool
1081 : 327827 : _bt_tuple_before_array_skeys(IndexScanDesc scan, ScanDirection dir,
1082 : : IndexTuple tuple, TupleDesc tupdesc, int tupnatts,
1083 : : bool readpagetup, int sktrig, bool *scanBehind)
1084 : : {
1085 : 327827 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1086 : :
1087 [ - + ]: 327827 : Assert(so->numArrayKeys);
1088 [ - + ]: 327827 : Assert(so->numberOfKeys);
1089 [ + + - + ]: 327827 : Assert(sktrig == 0 || readpagetup);
1090 [ + + - + ]: 327827 : Assert(!readpagetup || scanBehind == NULL);
1091 : :
1092 [ + + ]: 327827 : if (scanBehind)
1093 : 41624 : *scanBehind = false;
1094 : :
1095 [ + + ]: 393462 : for (int ikey = sktrig; ikey < so->numberOfKeys; ikey++)
1096 : : {
1097 : 389217 : ScanKey cur = so->keyData + ikey;
1098 : : Datum tupdatum;
1099 : : bool tupnull;
1100 : : int32 result;
1101 : :
1102 : : /* readpagetup calls require one ORDER proc comparison (at most) */
1103 [ + + - + ]: 389217 : Assert(!readpagetup || ikey == sktrig);
1104 : :
1105 : : /*
1106 : : * Once we reach a non-required scan key, we're completely done.
1107 : : *
1108 : : * Note: we deliberately don't consider the scan direction here.
1109 : : * _bt_advance_array_keys caller requires that we track *scanBehind
1110 : : * without concern for scan direction.
1111 : : */
1112 [ - + ]: 389217 : if ((cur->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)) == 0)
1113 : : {
518 pg@bowt.ie 1114 [ # # ]:UBC 0 : Assert(!readpagetup);
1115 [ # # # # ]: 0 : Assert(ikey > sktrig || ikey == 0);
518 pg@bowt.ie 1116 :CBC 323582 : return false;
1117 : : }
1118 : :
1119 [ + + ]: 389217 : if (cur->sk_attno > tupnatts)
1120 : : {
1121 [ - + ]: 1113 : Assert(!readpagetup);
1122 : :
1123 : : /*
1124 : : * When we reach a high key's truncated attribute, assume that the
1125 : : * tuple attribute's value is >= the scan's equality constraint
1126 : : * scan keys (but set *scanBehind to let interested callers know
1127 : : * that a truncated attribute might have affected our answer).
1128 : : */
1129 [ + + ]: 1113 : if (scanBehind)
1130 : 16 : *scanBehind = true;
1131 : :
1132 : 1113 : return false;
1133 : : }
1134 : :
1135 : : /*
1136 : : * Deal with inequality strategy scan keys that _bt_check_compare set
1137 : : * continuescan=false for
1138 : : */
1139 [ + + ]: 388104 : if (cur->sk_strategy != BTEqualStrategyNumber)
1140 : : {
1141 : : /*
1142 : : * When _bt_check_compare indicated that a required inequality
1143 : : * scan key wasn't satisfied, there's no need to verify anything;
1144 : : * caller always calls _bt_advance_array_keys with this sktrig.
1145 : : */
1146 [ + + ]: 8040 : if (readpagetup)
1147 : 174 : return false;
1148 : :
1149 : : /*
1150 : : * Otherwise we can't give up, since we must check all required
1151 : : * scan keys (required in either direction) in order to correctly
1152 : : * track *scanBehind for caller
1153 : : */
1154 : 7866 : continue;
1155 : : }
1156 : :
1157 : 380064 : tupdatum = index_getattr(tuple, cur->sk_attno, tupdesc, &tupnull);
1158 : :
155 1159 [ + + ]: 380064 : if (likely(!(cur->sk_flags & (SK_BT_MINVAL | SK_BT_MAXVAL))))
1160 : : {
1161 : : /* Scankey has a valid/comparable sk_argument value */
1162 : 374660 : result = _bt_compare_array_skey(&so->orderProcs[ikey],
1163 : : tupdatum, tupnull,
1164 : : cur->sk_argument, cur);
1165 : :
1166 [ + + ]: 374660 : if (result == 0)
1167 : : {
1168 : : /*
1169 : : * Interpret result in a way that takes NEXT/PRIOR into
1170 : : * account
1171 : : */
1172 [ + + ]: 72179 : if (cur->sk_flags & SK_BT_NEXT)
1173 : 14389 : result = -1;
1174 [ + + ]: 57790 : else if (cur->sk_flags & SK_BT_PRIOR)
1175 : 21 : result = 1;
1176 : :
1177 [ + + - + ]: 72179 : Assert(result == 0 || (cur->sk_flags & SK_BT_SKIP));
1178 : : }
1179 : : }
1180 : : else
1181 : : {
1182 : 5404 : BTArrayKeyInfo *array = NULL;
1183 : :
1184 : : /*
1185 : : * Current array element/array = scan key value is a sentinel
1186 : : * value that represents the lowest (or highest) possible value
1187 : : * that's still within the range of the array.
1188 : : *
1189 : : * Like _bt_first, we only see MINVAL keys during forwards scans
1190 : : * (and similarly only see MAXVAL keys during backwards scans).
1191 : : * Even if the scan's direction changes, we'll stop at some higher
1192 : : * order key before we can ever reach any MAXVAL (or MINVAL) keys.
1193 : : * (However, unlike _bt_first we _can_ get to keys marked either
1194 : : * NEXT or PRIOR, regardless of the scan's current direction.)
1195 : : */
1196 [ + + - + ]: 5404 : Assert(ScanDirectionIsForward(dir) ?
1197 : : !(cur->sk_flags & SK_BT_MAXVAL) :
1198 : : !(cur->sk_flags & SK_BT_MINVAL));
1199 : :
1200 : : /*
1201 : : * There are no valid sk_argument values in MINVAL/MAXVAL keys.
1202 : : * Check if tupdatum is within the range of skip array instead.
1203 : : */
1204 [ + - ]: 5930 : for (int arrayidx = 0; arrayidx < so->numArrayKeys; arrayidx++)
1205 : : {
1206 : 5930 : array = &so->arrayKeys[arrayidx];
1207 [ + + ]: 5930 : if (array->scan_key == ikey)
1208 : 5404 : break;
1209 : : }
1210 : :
1211 : 5404 : _bt_binsrch_skiparray_skey(false, dir, tupdatum, tupnull,
1212 : : array, cur, &result);
1213 : :
1214 [ + + ]: 5404 : if (result == 0)
1215 : : {
1216 : : /*
1217 : : * tupdatum satisfies both low_compare and high_compare, so
1218 : : * it's time to advance the array keys.
1219 : : *
1220 : : * Note: It's possible that the skip array will "advance" from
1221 : : * its MINVAL (or MAXVAL) representation to an alternative,
1222 : : * logically equivalent representation of the same value: a
1223 : : * representation where the = key gets a valid datum in its
1224 : : * sk_argument. This is only possible when low_compare uses
1225 : : * the >= strategy (or high_compare uses the <= strategy).
1226 : : */
1227 : 5396 : return false;
1228 : : }
1229 : : }
1230 : :
1231 : : /*
1232 : : * Does this comparison indicate that caller must _not_ advance the
1233 : : * scan's arrays just yet?
1234 : : */
518 1235 [ + + + + : 374668 : if ((ScanDirectionIsForward(dir) && result < 0) ||
+ + ]
1236 [ + + ]: 3312 : (ScanDirectionIsBackward(dir) && result > 0))
1237 : 97830 : return true;
1238 : :
1239 : : /*
1240 : : * Does this comparison indicate that caller should now advance the
1241 : : * scan's arrays? (Must be if we get here during a readpagetup call.)
1242 : : */
1243 [ + + + + ]: 276838 : if (readpagetup || result != 0)
1244 : : {
1245 [ - + ]: 219069 : Assert(result != 0);
1246 : 219069 : return false;
1247 : : }
1248 : :
1249 : : /*
1250 : : * Inconclusive -- need to check later scan keys, too.
1251 : : *
1252 : : * This must be a finaltup precheck, or a call made from an assertion.
1253 : : */
1254 [ - + ]: 57769 : Assert(result == 0);
1255 : : }
1256 : :
1257 [ - + ]: 4245 : Assert(!readpagetup);
1258 : :
1259 : 4245 : return false;
1260 : : }
1261 : :
1262 : : /*
1263 : : * _bt_start_prim_scan() -- start scheduled primitive index scan?
1264 : : *
1265 : : * Returns true if _bt_checkkeys scheduled another primitive index scan, just
1266 : : * as the last one ended. Otherwise returns false, indicating that the array
1267 : : * keys are now fully exhausted.
1268 : : *
1269 : : * Only call here during scans with one or more equality type array scan keys,
1270 : : * after _bt_first or _bt_next return false.
1271 : : */
1272 : : bool
1273 : 44217 : _bt_start_prim_scan(IndexScanDesc scan, ScanDirection dir)
1274 : : {
1275 : 44217 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1276 : :
1277 [ - + ]: 44217 : Assert(so->numArrayKeys);
1278 : :
325 1279 : 44217 : so->scanBehind = so->oppositeDirCheck = false; /* reset */
1280 : :
1281 : : /*
1282 : : * Array keys are advanced within _bt_checkkeys when the scan reaches the
1283 : : * leaf level (more precisely, they're advanced when the scan reaches the
1284 : : * end of each distinct set of array elements). This process avoids
1285 : : * repeat access to leaf pages (across multiple primitive index scans) by
1286 : : * advancing the scan's array keys when it allows the primitive index scan
1287 : : * to find nearby matching tuples (or when it eliminates ranges of array
1288 : : * key space that can't possibly be satisfied by any index tuple).
1289 : : *
1290 : : * _bt_checkkeys sets a simple flag variable to schedule another primitive
1291 : : * index scan. The flag tells us what to do.
1292 : : *
1293 : : * We cannot rely on _bt_first always reaching _bt_checkkeys. There are
1294 : : * various cases where that won't happen. For example, if the index is
1295 : : * completely empty, then _bt_first won't call _bt_readpage/_bt_checkkeys.
1296 : : * We also don't expect a call to _bt_checkkeys during searches for a
1297 : : * non-existent value that happens to be lower/higher than any existing
1298 : : * value in the index.
1299 : : *
1300 : : * We don't require special handling for these cases -- we don't need to
1301 : : * be explicitly instructed to _not_ perform another primitive index scan.
1302 : : * It's up to code under the control of _bt_first to always set the flag
1303 : : * when another primitive index scan will be required.
1304 : : *
1305 : : * This works correctly, even with the tricky cases listed above, which
1306 : : * all involve access to leaf pages "near the boundaries of the key space"
1307 : : * (whether it's from a leftmost/rightmost page, or an imaginary empty
1308 : : * leaf root page). If _bt_checkkeys cannot be reached by a primitive
1309 : : * index scan for one set of array keys, then it also won't be reached for
1310 : : * any later set ("later" in terms of the direction that we scan the index
1311 : : * and advance the arrays). The array keys won't have advanced in these
1312 : : * cases, but that's the correct behavior (even _bt_advance_array_keys
1313 : : * won't always advance the arrays at the point they become "exhausted").
1314 : : */
518 1315 [ + + ]: 44217 : if (so->needPrimScan)
1316 : : {
1317 : : /*
1318 : : * Flag was set -- must call _bt_first again, which will reset the
1319 : : * scan's needPrimScan flag
1320 : : */
1321 : 8751 : return true;
1322 : : }
1323 : :
1324 : : /* The top-level index scan ran out of tuples in this scan direction */
1325 [ + + ]: 35466 : if (scan->parallel_scan != NULL)
1326 : 15 : _bt_parallel_done(scan);
1327 : :
1328 : 35466 : return false;
1329 : : }
1330 : :
1331 : : /*
1332 : : * _bt_advance_array_keys() -- Advance array elements using a tuple
1333 : : *
1334 : : * The scan always gets a new qual as a consequence of calling here (except
1335 : : * when we determine that the top-level scan has run out of matching tuples).
1336 : : * All later _bt_check_compare calls also use the same new qual that was first
1337 : : * used here (at least until the next call here advances the keys once again).
1338 : : * It's convenient to structure _bt_check_compare rechecks of caller's tuple
1339 : : * (using the new qual) as one the steps of advancing the scan's array keys,
1340 : : * so this function works as a wrapper around _bt_check_compare.
1341 : : *
1342 : : * Like _bt_check_compare, we'll set pstate.continuescan on behalf of the
1343 : : * caller, and return a boolean indicating if caller's tuple satisfies the
1344 : : * scan's new qual. But unlike _bt_check_compare, we set so->needPrimScan
1345 : : * when we set continuescan=false, indicating if a new primitive index scan
1346 : : * has been scheduled (otherwise, the top-level scan has run out of tuples in
1347 : : * the current scan direction).
1348 : : *
1349 : : * Caller must use _bt_tuple_before_array_skeys to determine if the current
1350 : : * place in the scan is >= the current array keys _before_ calling here.
1351 : : * We're responsible for ensuring that caller's tuple is <= the newly advanced
1352 : : * required array keys once we return. We try to find an exact match, but
1353 : : * failing that we'll advance the array keys to whatever set of array elements
1354 : : * comes next in the key space for the current scan direction. Required array
1355 : : * keys "ratchet forwards" (or backwards). They can only advance as the scan
1356 : : * itself advances through the index/key space.
1357 : : *
1358 : : * (The rules are the same for backwards scans, except that the operators are
1359 : : * flipped: just replace the precondition's >= operator with a <=, and the
1360 : : * postcondition's <= operator with a >=. In other words, just swap the
1361 : : * precondition with the postcondition.)
1362 : : *
1363 : : * We also deal with "advancing" non-required arrays here (or arrays that are
1364 : : * treated as non-required for the duration of a _bt_readpage call). Callers
1365 : : * whose sktrig scan key is non-required specify sktrig_required=false. These
1366 : : * calls are the only exception to the general rule about always advancing the
1367 : : * required array keys (the scan may not even have a required array). These
1368 : : * callers should just pass a NULL pstate (since there is never any question
1369 : : * of stopping the scan). No call to _bt_tuple_before_array_skeys is required
1370 : : * ahead of these calls (it's already clear that any required scan keys must
1371 : : * be satisfied by caller's tuple).
1372 : : *
1373 : : * Note that we deal with non-array required equality strategy scan keys as
1374 : : * degenerate single element arrays here. Obviously, they can never really
1375 : : * advance in the way that real arrays can, but they must still affect how we
1376 : : * advance real array scan keys (exactly like true array equality scan keys).
1377 : : * We have to keep around a 3-way ORDER proc for these (using the "=" operator
1378 : : * won't do), since in general whether the tuple is < or > _any_ unsatisfied
1379 : : * required equality key influences how the scan's real arrays must advance.
1380 : : *
1381 : : * Note also that we may sometimes need to advance the array keys when the
1382 : : * existing required array keys (and other required equality keys) are already
1383 : : * an exact match for every corresponding value from caller's tuple. We must
1384 : : * do this for inequalities that _bt_check_compare set continuescan=false for.
1385 : : * They'll advance the array keys here, just like any other scan key that
1386 : : * _bt_check_compare stops on. (This can even happen _after_ we advance the
1387 : : * array keys, in which case we'll advance the array keys a second time. That
1388 : : * way _bt_checkkeys caller always has its required arrays advance to the
1389 : : * maximum possible extent that its tuple will allow.)
1390 : : */
1391 : : static bool
1392 : 98868 : _bt_advance_array_keys(IndexScanDesc scan, BTReadPageState *pstate,
1393 : : IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
1394 : : int sktrig, bool sktrig_required)
1395 : : {
1396 : 98868 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
1397 : 98868 : Relation rel = scan->indexRelation;
311 1398 : 98868 : ScanDirection dir = so->currPos.dir;
518 1399 : 98868 : int arrayidx = 0;
1400 : 98868 : bool beyond_end_advance = false,
155 1401 : 98868 : skip_array_advanced = false,
518 1402 : 98868 : has_required_opposite_direction_only = false,
1403 : 98868 : all_required_satisfied = true,
1404 : 98868 : all_satisfied = true;
1405 : :
168 1406 [ + - + - : 98868 : Assert(!so->needPrimScan && !so->scanBehind && !so->oppositeDirCheck);
- + ]
155 1407 [ - + ]: 98868 : Assert(_bt_verify_keys_with_arraykeys(scan));
1408 : :
518 1409 [ + + ]: 98868 : if (sktrig_required)
1410 : : {
1411 : : /*
1412 : : * Precondition array state assertion
1413 : : */
1414 [ - + ]: 94504 : Assert(!_bt_tuple_before_array_skeys(scan, dir, tuple, tupdesc,
1415 : : tupnatts, false, 0, NULL));
1416 : :
1417 : : /*
1418 : : * Once we return we'll have a new set of required array keys, so
1419 : : * reset state used by "look ahead" optimization
1420 : : */
1421 : 94504 : pstate->rechecks = 0;
1422 : 94504 : pstate->targetdistance = 0;
1423 : : }
155 1424 [ + - ]: 4364 : else if (sktrig < so->numberOfKeys - 1 &&
1425 [ + - ]: 4364 : !(so->keyData[so->numberOfKeys - 1].sk_flags & SK_SEARCHARRAY))
1426 : : {
1427 : 4364 : int least_sign_ikey = so->numberOfKeys - 1;
1428 : : bool continuescan;
1429 : :
1430 : : /*
1431 : : * Optimization: perform a precheck of the least significant key
1432 : : * during !sktrig_required calls when it isn't already our sktrig
1433 : : * (provided the precheck key is not itself an array).
1434 : : *
1435 : : * When the precheck works out we'll avoid an expensive binary search
1436 : : * of sktrig's array (plus any other arrays before least_sign_ikey).
1437 : : */
1438 [ - + ]: 4364 : Assert(so->keyData[sktrig].sk_flags & SK_SEARCHARRAY);
1439 [ + + ]: 4364 : if (!_bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, false,
1440 : : false, &continuescan,
1441 : : &least_sign_ikey))
1442 : 1220 : return false;
1443 : : }
1444 : :
518 1445 [ + + ]: 286852 : for (int ikey = 0; ikey < so->numberOfKeys; ikey++)
1446 : : {
1447 : 192087 : ScanKey cur = so->keyData + ikey;
1448 : 192087 : BTArrayKeyInfo *array = NULL;
1449 : : Datum tupdatum;
1450 : 192087 : bool required = false,
1451 : 192087 : required_opposite_direction_only = false,
1452 : : tupnull;
1453 : : int32 result;
1454 : 192087 : int set_elem = 0;
1455 : :
1456 [ + + ]: 192087 : if (cur->sk_strategy == BTEqualStrategyNumber)
1457 : : {
1458 : : /* Manage array state */
1459 [ + + ]: 168025 : if (cur->sk_flags & SK_SEARCHARRAY)
1460 : : {
1461 : 102817 : array = &so->arrayKeys[arrayidx++];
1462 [ - + ]: 102817 : Assert(array->scan_key == ikey);
1463 : : }
1464 : : }
1465 : : else
1466 : : {
1467 : : /*
1468 : : * Are any inequalities required in the opposite direction only
1469 : : * present here?
1470 : : */
1471 [ + - ]: 24062 : if (((ScanDirectionIsForward(dir) &&
1472 [ + + - + ]: 24062 : (cur->sk_flags & (SK_BT_REQBKWD))) ||
518 pg@bowt.ie 1473 :UBC 0 : (ScanDirectionIsBackward(dir) &&
1474 [ # # ]: 0 : (cur->sk_flags & (SK_BT_REQFWD)))))
518 pg@bowt.ie 1475 :CBC 7790 : has_required_opposite_direction_only =
1476 : 7790 : required_opposite_direction_only = true;
1477 : : }
1478 : :
1479 : : /* Optimization: skip over known-satisfied scan keys */
1480 [ + + ]: 192087 : if (ikey < sktrig)
1481 : 38100 : continue;
1482 : :
1483 [ + - ]: 183888 : if (cur->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD))
1484 : : {
1485 : 183888 : required = true;
1486 : :
1487 [ + + ]: 183888 : if (cur->sk_attno > tupnatts)
1488 : : {
1489 : : /* Set this just like _bt_tuple_before_array_skeys */
1490 [ - + ]: 1146 : Assert(sktrig < ikey);
1491 : 1146 : so->scanBehind = true;
1492 : : }
1493 : : }
1494 : :
1495 : : /*
1496 : : * Handle a required non-array scan key that the initial call to
1497 : : * _bt_check_compare indicated triggered array advancement, if any.
1498 : : *
1499 : : * The non-array scan key's strategy will be <, <=, or = during a
1500 : : * forwards scan (or any one of =, >=, or > during a backwards scan).
1501 : : * It follows that the corresponding tuple attribute's value must now
1502 : : * be either > or >= the scan key value (for backwards scans it must
1503 : : * be either < or <= that value).
1504 : : *
1505 : : * If this is a required equality strategy scan key, this is just an
1506 : : * optimization; _bt_tuple_before_array_skeys already confirmed that
1507 : : * this scan key places us ahead of caller's tuple. There's no need
1508 : : * to repeat that work now. (The same underlying principle also gets
1509 : : * applied by the cur_elem_trig optimization used to speed up searches
1510 : : * for the next array element.)
1511 : : *
1512 : : * If this is a required inequality strategy scan key, we _must_ rely
1513 : : * on _bt_check_compare like this; we aren't capable of directly
1514 : : * evaluating required inequality strategy scan keys here, on our own.
1515 : : */
1516 [ + + + + ]: 183888 : if (ikey == sktrig && !array)
1517 : : {
1518 [ + - + - : 3736 : Assert(sktrig_required && required && all_required_satisfied);
- + ]
1519 : :
1520 : : /* Use "beyond end" advancement. See below for an explanation. */
1521 : 3736 : beyond_end_advance = true;
1522 : 3736 : all_satisfied = all_required_satisfied = false;
1523 : :
1524 : 3736 : continue;
1525 : : }
1526 : :
1527 : : /*
1528 : : * Nothing more for us to do with an inequality strategy scan key that
1529 : : * wasn't the one that _bt_check_compare stopped on, though.
1530 : : *
1531 : : * Note: if our later call to _bt_check_compare (to recheck caller's
1532 : : * tuple) sets continuescan=false due to finding this same inequality
1533 : : * unsatisfied (possible when it's required in the scan direction),
1534 : : * we'll deal with it via a recursive "second pass" call.
1535 : : */
1536 [ + + ]: 180152 : else if (cur->sk_strategy != BTEqualStrategyNumber)
1537 : 23777 : continue;
1538 : :
1539 : : /*
1540 : : * Nothing for us to do with an equality strategy scan key that isn't
1541 : : * marked required, either -- unless it's a non-required array
1542 : : */
1543 [ - + - - ]: 156375 : else if (!required && !array)
518 pg@bowt.ie 1544 :UBC 0 : continue;
1545 : :
1546 : : /*
1547 : : * Here we perform steps for all array scan keys after a required
1548 : : * array scan key whose binary search triggered "beyond end of array
1549 : : * element" array advancement due to encountering a tuple attribute
1550 : : * value > the closest matching array key (or < for backwards scans).
1551 : : */
518 pg@bowt.ie 1552 [ + + ]:CBC 156375 : if (beyond_end_advance)
1553 : : {
155 1554 [ + + ]: 714 : if (array)
1555 : 299 : _bt_array_set_low_or_high(rel, cur, array,
1556 : : ScanDirectionIsBackward(dir));
1557 : :
518 1558 : 714 : continue;
1559 : : }
1560 : :
1561 : : /*
1562 : : * Here we perform steps for all array scan keys after a required
1563 : : * array scan key whose tuple attribute was < the closest matching
1564 : : * array key when we dealt with it (or > for backwards scans).
1565 : : *
1566 : : * This earlier required array key already puts us ahead of caller's
1567 : : * tuple in the key space (for the current scan direction). We must
1568 : : * make sure that subsequent lower-order array keys do not put us too
1569 : : * far ahead (ahead of tuples that have yet to be seen by our caller).
1570 : : * For example, when a tuple "(a, b) = (42, 5)" advances the array
1571 : : * keys on "a" from 40 to 45, we must also set "b" to whatever the
1572 : : * first array element for "b" is. It would be wrong to allow "b" to
1573 : : * be set based on the tuple value.
1574 : : *
1575 : : * Perform the same steps with truncated high key attributes. You can
1576 : : * think of this as a "binary search" for the element closest to the
1577 : : * value -inf. Again, the arrays must never get ahead of the scan.
1578 : : */
1579 [ + + + + ]: 155661 : if (!all_required_satisfied || cur->sk_attno > tupnatts)
1580 : : {
155 1581 [ + + ]: 1674 : if (array)
1582 : 394 : _bt_array_set_low_or_high(rel, cur, array,
1583 : : ScanDirectionIsForward(dir));
1584 : :
518 1585 : 1674 : continue;
1586 : : }
1587 : :
1588 : : /*
1589 : : * Search in scankey's array for the corresponding tuple attribute
1590 : : * value from caller's tuple
1591 : : */
1592 : 153987 : tupdatum = index_getattr(tuple, cur->sk_attno, tupdesc, &tupnull);
1593 : :
1594 [ + + ]: 153987 : if (array)
1595 : : {
1596 [ + + + + ]: 94814 : bool cur_elem_trig = (sktrig_required && ikey == sktrig);
1597 : :
1598 : : /*
1599 : : * "Binary search" by checking if tupdatum/tupnull are within the
1600 : : * range of the skip array
1601 : : */
155 1602 [ + + ]: 94814 : if (array->num_elems == -1)
1603 : 79168 : _bt_binsrch_skiparray_skey(cur_elem_trig, dir,
1604 : : tupdatum, tupnull, array, cur,
1605 : : &result);
1606 : :
1607 : : /*
1608 : : * Binary search for the closest match from the SAOP array
1609 : : */
1610 : : else
1611 : 15646 : set_elem = _bt_binsrch_array_skey(&so->orderProcs[ikey],
1612 : : cur_elem_trig, dir,
1613 : : tupdatum, tupnull, array, cur,
1614 : : &result);
1615 : : }
1616 : : else
1617 : : {
1618 [ - + ]: 59173 : Assert(required);
1619 : :
1620 : : /*
1621 : : * This is a required non-array equality strategy scan key, which
1622 : : * we'll treat as a degenerate single element array.
1623 : : *
1624 : : * This scan key's imaginary "array" can't really advance, but it
1625 : : * can still roll over like any other array. (Actually, this is
1626 : : * no different to real single value arrays, which never advance
1627 : : * without rolling over -- they can never truly advance, either.)
1628 : : */
518 1629 : 59173 : result = _bt_compare_array_skey(&so->orderProcs[ikey],
1630 : : tupdatum, tupnull,
1631 : : cur->sk_argument, cur);
1632 : : }
1633 : :
1634 : : /*
1635 : : * Consider "beyond end of array element" array advancement.
1636 : : *
1637 : : * When the tuple attribute value is > the closest matching array key
1638 : : * (or < in the backwards scan case), we need to ratchet this array
1639 : : * forward (backward) by one increment, so that caller's tuple ends up
1640 : : * being < final array value instead (or > final array value instead).
1641 : : * This process has to work for all of the arrays, not just this one:
1642 : : * it must "carry" to higher-order arrays when the set_elem that we
1643 : : * just found happens to be the final one for the scan's direction.
1644 : : * Incrementing (decrementing) set_elem itself isn't good enough.
1645 : : *
1646 : : * Our approach is to provisionally use set_elem as if it was an exact
1647 : : * match now, then set each later/less significant array to whatever
1648 : : * its final element is. Once outside the loop we'll then "increment
1649 : : * this array's set_elem" by calling _bt_advance_array_keys_increment.
1650 : : * That way the process rolls over to higher order arrays as needed.
1651 : : *
1652 : : * Under this scheme any required arrays only ever ratchet forwards
1653 : : * (or backwards), and always do so to the maximum possible extent
1654 : : * that we can know will be safe without seeing the scan's next tuple.
1655 : : * We don't need any special handling for required scan keys that lack
1656 : : * a real array to advance, nor for redundant scan keys that couldn't
1657 : : * be eliminated by _bt_preprocess_keys. It won't matter if some of
1658 : : * our "true" array scan keys (or even all of them) are non-required.
1659 : : */
155 1660 [ + + + - : 153987 : if (sktrig_required && required &&
+ + ]
518 1661 [ + + + + ]: 150843 : ((ScanDirectionIsForward(dir) && result > 0) ||
1662 [ + + ]: 858 : (ScanDirectionIsBackward(dir) && result < 0)))
1663 : 11689 : beyond_end_advance = true;
1664 : :
1665 [ + - - + ]: 153987 : Assert(all_required_satisfied && all_satisfied);
1666 [ + + ]: 153987 : if (result != 0)
1667 : : {
1668 : : /*
1669 : : * Track whether caller's tuple satisfies our new post-advancement
1670 : : * qual, for required scan keys, as well as for the entire set of
1671 : : * interesting scan keys (all required scan keys plus non-required
1672 : : * array scan keys are considered interesting.)
1673 : : */
1674 : 70370 : all_satisfied = false;
155 1675 [ + + + - ]: 70370 : if (sktrig_required && required)
518 1676 : 67487 : all_required_satisfied = false;
1677 : : else
1678 : : {
1679 : : /*
1680 : : * There's no need to advance the arrays using the best
1681 : : * available match for a non-required array. Give up now.
1682 : : * (Though note that sktrig_required calls still have to do
1683 : : * all the usual post-advancement steps, including the recheck
1684 : : * call to _bt_check_compare.)
1685 : : */
1686 : : break;
1687 : : }
1688 : : }
1689 : :
1690 : : /* Advance array keys, even when we don't have an exact match */
155 1691 [ + + ]: 151104 : if (array)
1692 : : {
1693 [ + + ]: 91931 : if (array->num_elems == -1)
1694 : : {
1695 : : /* Skip array's new element is tupdatum (or MINVAL/MAXVAL) */
1696 : 76285 : _bt_skiparray_set_element(rel, cur, array, result,
1697 : : tupdatum, tupnull);
1698 : 76285 : skip_array_advanced = true;
1699 : : }
1700 [ + + ]: 15646 : else if (array->cur_elem != set_elem)
1701 : : {
1702 : : /* SAOP array's new element is set_elem datum */
1703 : 11693 : array->cur_elem = set_elem;
1704 : 11693 : cur->sk_argument = array->elem_values[set_elem];
1705 : : }
1706 : : }
1707 : : }
1708 : :
1709 : : /*
1710 : : * Advance the array keys incrementally whenever "beyond end of array
1711 : : * element" array advancement happens, so that advancement will carry to
1712 : : * higher-order arrays (might exhaust all the scan's arrays instead, which
1713 : : * ends the top-level scan).
1714 : : */
1715 [ + + ]: 97648 : if (beyond_end_advance &&
1716 [ + + ]: 15425 : !_bt_advance_array_keys_increment(scan, dir, &skip_array_advanced))
518 1717 : 4033 : goto end_toplevel_scan;
1718 : :
1719 [ - + ]: 93615 : Assert(_bt_verify_keys_with_arraykeys(scan));
1720 : :
1721 : : /*
1722 : : * Maintain a page-level count of the number of times the scan's array
1723 : : * keys advanced in a way that affected at least one skip array
1724 : : */
155 1725 [ + + + + ]: 93615 : if (sktrig_required && skip_array_advanced)
1726 : 79302 : pstate->nskipadvances++;
1727 : :
1728 : : /*
1729 : : * Does tuple now satisfy our new qual? Recheck with _bt_check_compare.
1730 : : *
1731 : : * Calls triggered by an unsatisfied required scan key, whose tuple now
1732 : : * satisfies all required scan keys, but not all nonrequired array keys,
1733 : : * will still require a recheck call to _bt_check_compare. They'll still
1734 : : * need its "second pass" handling of required inequality scan keys.
1735 : : * (Might have missed a still-unsatisfied required inequality scan key
1736 : : * that caller didn't detect as the sktrig scan key during its initial
1737 : : * _bt_check_compare call that used the old/original qual.)
1738 : : *
1739 : : * Calls triggered by an unsatisfied nonrequired array scan key never need
1740 : : * "second pass" handling of required inequalities (nor any other handling
1741 : : * of any required scan key). All that matters is whether caller's tuple
1742 : : * satisfies the new qual, so it's safe to just skip the _bt_check_compare
1743 : : * recheck when we've already determined that it can only return 'false'.
1744 : : *
1745 : : * Note: In practice most scan keys are marked required by preprocessing,
1746 : : * if necessary by generating a preceding skip array. We nevertheless
1747 : : * often handle array keys marked required as if they were nonrequired.
1748 : : * This behavior is requested by our _bt_check_compare caller, though only
1749 : : * when it is passed "forcenonrequired=true" by _bt_checkkeys.
1750 : : */
518 1751 [ + + + + ]: 93615 : if ((sktrig_required && all_required_satisfied) ||
1752 [ + + + + ]: 70334 : (!sktrig_required && all_satisfied))
1753 : : {
1754 : 23542 : int nsktrig = sktrig + 1;
1755 : : bool continuescan;
1756 : :
1757 [ - + ]: 23542 : Assert(all_required_satisfied);
1758 : :
1759 : : /* Recheck _bt_check_compare on behalf of caller */
155 1760 [ + + ]: 23542 : if (_bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, false,
127 1761 : 23542 : !sktrig_required, &continuescan,
155 1762 : 23542 : &nsktrig) &&
518 1763 [ + + ]: 19711 : !so->scanBehind)
1764 : : {
1765 : : /* This tuple satisfies the new qual */
1766 [ + - - + ]: 18614 : Assert(all_satisfied && continuescan);
1767 : :
1768 [ + + ]: 18614 : if (pstate)
1769 : 18353 : pstate->continuescan = true;
1770 : :
1771 : 18725 : return true;
1772 : : }
1773 : :
1774 : : /*
1775 : : * Consider "second pass" handling of required inequalities.
1776 : : *
1777 : : * It's possible that our _bt_check_compare call indicated that the
1778 : : * scan should end due to some unsatisfied inequality that wasn't
1779 : : * initially recognized as such by us. Handle this by calling
1780 : : * ourselves recursively, this time indicating that the trigger is the
1781 : : * inequality that we missed first time around (and using a set of
1782 : : * required array/equality keys that are now exact matches for tuple).
1783 : : *
1784 : : * We make a strong, general guarantee that every _bt_checkkeys call
1785 : : * here will advance the array keys to the maximum possible extent
1786 : : * that we can know to be safe based on caller's tuple alone. If we
1787 : : * didn't perform this step, then that guarantee wouldn't quite hold.
1788 : : */
1789 [ + + ]: 4928 : if (unlikely(!continuescan))
1790 : : {
1791 : : bool satisfied PG_USED_FOR_ASSERTS_ONLY;
1792 : :
1793 [ - + ]: 111 : Assert(sktrig_required);
1794 [ - + ]: 111 : Assert(so->keyData[nsktrig].sk_strategy != BTEqualStrategyNumber);
1795 : :
1796 : : /*
1797 : : * The tuple must use "beyond end" advancement during the
1798 : : * recursive call, so we cannot possibly end up back here when
1799 : : * recursing. We'll consume a small, fixed amount of stack space.
1800 : : */
1801 [ - + ]: 111 : Assert(!beyond_end_advance);
1802 : :
1803 : : /* Advance the array keys a second time using same tuple */
1804 : 111 : satisfied = _bt_advance_array_keys(scan, pstate, tuple, tupnatts,
1805 : : tupdesc, nsktrig, true);
1806 : :
1807 : : /* This tuple doesn't satisfy the inequality */
1808 [ - + ]: 111 : Assert(!satisfied);
1809 : 111 : return false;
1810 : : }
1811 : :
1812 : : /*
1813 : : * Some non-required scan key (from new qual) still not satisfied.
1814 : : *
1815 : : * All scan keys required in the current scan direction must still be
1816 : : * satisfied, though, so we can trust all_required_satisfied below.
1817 : : */
1818 : : }
1819 : :
1820 : : /*
1821 : : * When we were called just to deal with "advancing" non-required arrays,
1822 : : * this is as far as we can go (cannot stop the scan for these callers)
1823 : : */
1824 [ + + ]: 74890 : if (!sktrig_required)
1825 : : {
1826 : : /* Caller's tuple doesn't match any qual */
1827 : 2883 : return false;
1828 : : }
1829 : :
1830 : : /*
1831 : : * Postcondition array state assertion (for still-unsatisfied tuples).
1832 : : *
1833 : : * By here we have established that the scan's required arrays (scan must
1834 : : * have at least one required array) advanced, without becoming exhausted.
1835 : : *
1836 : : * Caller's tuple is now < the newly advanced array keys (or > when this
1837 : : * is a backwards scan), except in the case where we only got this far due
1838 : : * to an unsatisfied non-required scan key. Verify that with an assert.
1839 : : *
1840 : : * Note: we don't just quit at this point when all required scan keys were
1841 : : * found to be satisfied because we need to consider edge-cases involving
1842 : : * scan keys required in the opposite direction only; those aren't tracked
1843 : : * by all_required_satisfied.
1844 : : */
1845 [ - + ]: 72007 : Assert(_bt_tuple_before_array_skeys(scan, dir, tuple, tupdesc, tupnatts,
1846 : : false, 0, NULL) ==
1847 : : !all_required_satisfied);
1848 : :
1849 : : /*
1850 : : * We generally permit primitive index scans to continue onto the next
1851 : : * sibling page when the page's finaltup satisfies all required scan keys
1852 : : * at the point where we're between pages.
1853 : : *
1854 : : * If caller's tuple is also the page's finaltup, and we see that required
1855 : : * scan keys still aren't satisfied, start a new primitive index scan.
1856 : : */
1857 [ + + + + ]: 72007 : if (!all_required_satisfied && pstate->finaltup == tuple)
1858 : 262 : goto new_prim_scan;
1859 : :
1860 : : /*
1861 : : * Proactively check finaltup (don't wait until finaltup is reached by the
1862 : : * scan) when it might well turn out to not be satisfied later on.
1863 : : *
1864 : : * Note: if so->scanBehind hasn't already been set for finaltup by us,
1865 : : * it'll be set during this call to _bt_tuple_before_array_skeys. Either
1866 : : * way, it'll be set correctly (for the whole page) after this point.
1867 : : */
1868 [ + + + + : 112078 : if (!all_required_satisfied && pstate->finaltup &&
+ + ]
1869 [ + + ]: 80666 : _bt_tuple_before_array_skeys(scan, dir, pstate->finaltup, tupdesc,
1870 : 80666 : BTreeTupleGetNAtts(pstate->finaltup, rel),
1871 : : false, 0, &so->scanBehind))
1872 : 8718 : goto new_prim_scan;
1873 : :
1874 : : /*
1875 : : * When we encounter a truncated finaltup high key attribute, we're
1876 : : * optimistic about the chances of its corresponding required scan key
1877 : : * being satisfied when we go on to recheck it against tuples from this
1878 : : * page's right sibling leaf page. We consider truncated attributes to be
1879 : : * satisfied by required scan keys, which allows the primitive index scan
1880 : : * to continue to the next leaf page. We must set so->scanBehind to true
1881 : : * to remember that the last page's finaltup had "satisfied" required scan
1882 : : * keys for one or more truncated attribute values (scan keys required in
1883 : : * _either_ scan direction).
1884 : : *
1885 : : * There is a chance that _bt_readpage (which checks so->scanBehind) will
1886 : : * find that even the sibling leaf page's finaltup is < the new array
1887 : : * keys. When that happens, our optimistic policy will have incurred a
1888 : : * single extra leaf page access that could have been avoided.
1889 : : *
1890 : : * A pessimistic policy would give backward scans a gratuitous advantage
1891 : : * over forward scans. We'd punish forward scans for applying more
1892 : : * accurate information from the high key, rather than just using the
1893 : : * final non-pivot tuple as finaltup, in the style of backward scans.
1894 : : * Being pessimistic would also give some scans with non-required arrays a
1895 : : * perverse advantage over similar scans that use required arrays instead.
1896 : : *
1897 : : * This is similar to our scan-level heuristics, below. They also set
1898 : : * scanBehind to speculatively continue the primscan onto the next page.
1899 : : */
168 1900 [ + + ]: 63027 : if (so->scanBehind)
1901 : : {
1902 : : /* Truncated high key -- _bt_scanbehind_checkkeys recheck scheduled */
1903 : : }
1904 : :
1905 : : /*
1906 : : * Handle inequalities marked required in the opposite scan direction.
1907 : : * They can also signal that we should start a new primitive index scan.
1908 : : *
1909 : : * It's possible that the scan is now positioned where "matching" tuples
1910 : : * begin, and that caller's tuple satisfies all scan keys required in the
1911 : : * current scan direction. But if caller's tuple still doesn't satisfy
1912 : : * other scan keys that are required in the opposite scan direction only
1913 : : * (e.g., a required >= strategy scan key when scan direction is forward),
1914 : : * it's still possible that there are many leaf pages before the page that
1915 : : * _bt_first could skip straight to. Groveling through all those pages
1916 : : * will always give correct answers, but it can be very inefficient. We
1917 : : * must avoid needlessly scanning extra pages.
1918 : : *
1919 : : * Separately, it's possible that _bt_check_compare set continuescan=false
1920 : : * for a scan key that's required in the opposite direction only. This is
1921 : : * a special case, that happens only when _bt_check_compare sees that the
1922 : : * inequality encountered a NULL value. This signals the end of non-NULL
1923 : : * values in the current scan direction, which is reason enough to end the
1924 : : * (primitive) scan. If this happens at the start of a large group of
1925 : : * NULL values, then we shouldn't expect to be called again until after
1926 : : * the scan has already read indefinitely-many leaf pages full of tuples
1927 : : * with NULL suffix values. (_bt_first is expected to skip over the group
1928 : : * of NULLs by applying a similar "deduce NOT NULL" rule of its own, which
1929 : : * involves consing up an explicit SK_SEARCHNOTNULL key.)
1930 : : *
1931 : : * Apply a test against finaltup to detect and recover from the problem:
1932 : : * if even finaltup doesn't satisfy such an inequality, we just skip by
1933 : : * starting a new primitive index scan. When we skip, we know for sure
1934 : : * that all of the tuples on the current page following caller's tuple are
1935 : : * also before the _bt_first-wise start of tuples for our new qual. That
1936 : : * at least suggests many more skippable pages beyond the current page.
1937 : : * (when so->scanBehind and so->oppositeDirCheck are set, this'll happen
1938 : : * when we test the next page's finaltup/high key instead.)
1939 : : */
236 1940 [ + + + + ]: 61914 : else if (has_required_opposite_direction_only && pstate->finaltup &&
1941 [ + + ]: 2146 : unlikely(!_bt_oppodir_checkkeys(scan, dir, pstate->finaltup)))
236 pg@bowt.ie 1942 :GBC 1 : goto new_prim_scan;
1943 : :
168 pg@bowt.ie 1944 :CBC 61913 : continue_scan:
1945 : :
1946 : : /*
1947 : : * Stick with the ongoing primitive index scan for now.
1948 : : *
1949 : : * It's possible that later tuples will also turn out to have values that
1950 : : * are still < the now-current array keys (or > the current array keys).
1951 : : * Our caller will handle this by performing what amounts to a linear
1952 : : * search of the page, implemented by calling _bt_check_compare and then
1953 : : * _bt_tuple_before_array_skeys for each tuple.
1954 : : *
1955 : : * This approach has various advantages over a binary search of the page.
1956 : : * Repeated binary searches of the page (one binary search for every array
1957 : : * advancement) won't outperform a continuous linear search. While there
1958 : : * are workloads that a naive linear search won't handle well, our caller
1959 : : * has a "look ahead" fallback mechanism to deal with that problem.
1960 : : */
236 1961 : 63462 : pstate->continuescan = true; /* Override _bt_check_compare */
1962 : 63462 : so->needPrimScan = false; /* _bt_readpage has more tuples to check */
1963 : :
1964 [ + + ]: 63462 : if (so->scanBehind)
1965 : : {
1966 : : /*
1967 : : * Remember if recheck needs to call _bt_oppodir_checkkeys for next
1968 : : * page's finaltup (see above comments about "Handle inequalities
1969 : : * marked required in the opposite scan direction" for why).
1970 : : */
155 1971 : 1549 : so->oppositeDirCheck = has_required_opposite_direction_only;
1972 : :
1973 : : /*
1974 : : * skip by setting "look ahead" mechanism's offnum for forwards scans
1975 : : * (backwards scans check scanBehind flag directly instead)
1976 : : */
168 1977 [ + + ]: 1549 : if (ScanDirectionIsForward(dir))
1978 : 1540 : pstate->skip = pstate->maxoff + 1;
1979 : : }
1980 : :
1981 : : /* Caller's tuple doesn't match the new qual */
236 1982 : 63462 : return false;
1983 : :
1984 : 8981 : new_prim_scan:
1985 : :
1986 [ - + ]: 8981 : Assert(pstate->finaltup); /* not on rightmost/leftmost page */
1987 : :
1988 : : /*
1989 : : * Looks like another primitive index scan is required. But consider
1990 : : * continuing the current primscan based on scan-level heuristics.
1991 : : *
1992 : : * Continue the ongoing primitive scan (and schedule a recheck for when
1993 : : * the scan arrives on the next sibling leaf page) when it has already
1994 : : * read at least one leaf page before the one we're reading now. This
1995 : : * makes primscan scheduling more efficient when scanning subsets of an
1996 : : * index with many distinct attribute values matching many array elements.
1997 : : * It encourages fewer, larger primitive scans where that makes sense.
1998 : : * This will in turn encourage _bt_readpage to apply the pstate.startikey
1999 : : * optimization more often.
2000 : : *
2001 : : * Also continue the ongoing primitive index scan when it is still on the
2002 : : * first page if there have been more than NSKIPADVANCES_THRESHOLD calls
2003 : : * here that each advanced at least one of the scan's skip arrays
2004 : : * (deliberately ignore advancements that only affected SAOP arrays here).
2005 : : * A page that cycles through this many skip array elements is quite
2006 : : * likely to neighbor similar pages, that we'll also need to read.
2007 : : *
2008 : : * Note: These heuristics aren't as aggressive as you might think. We're
2009 : : * conservative about allowing a primitive scan to step from the first
2010 : : * leaf page it reads to the page's sibling page (we only allow it on
2011 : : * first pages whose finaltup strongly suggests that it'll work out, as
2012 : : * well as first pages that have a large number of skip array advances).
2013 : : * Clearing this first page finaltup hurdle is a strong signal in itself.
2014 : : *
2015 : : * Note: The NSKIPADVANCES_THRESHOLD heuristic exists only to avoid
2016 : : * pathological cases. Specifically, cases where a skip scan should just
2017 : : * behave like a traditional full index scan, but ends up "skipping" again
2018 : : * and again, descending to the prior leaf page's direct sibling leaf page
2019 : : * each time. This misbehavior would otherwise be possible during scans
2020 : : * that never quite manage to "clear the first page finaltup hurdle".
2021 : : */
155 2022 [ + + + + ]: 8981 : if (!pstate->firstpage || pstate->nskipadvances > NSKIPADVANCES_THRESHOLD)
2023 : : {
2024 : : /* Schedule a recheck once on the next (or previous) page */
168 2025 : 436 : so->scanBehind = true;
2026 : :
2027 : : /* Continue the current primitive scan after all */
2028 : 436 : goto continue_scan;
2029 : : }
2030 : :
2031 : : /*
2032 : : * End this primitive index scan, but schedule another.
2033 : : *
2034 : : * Note: We make a soft assumption that the current scan direction will
2035 : : * also be used within _bt_next, when it is asked to step off this page.
2036 : : * It is up to _bt_next to cancel this scheduled primitive index scan
2037 : : * whenever it steps to a page in the direction opposite currPos.dir.
2038 : : */
236 2039 : 8545 : pstate->continuescan = false; /* Tell _bt_readpage we're done... */
2040 : 8545 : so->needPrimScan = true; /* ...but call _bt_first again */
2041 : :
2042 [ + + ]: 8545 : if (scan->parallel_scan)
2043 : 18 : _bt_parallel_primscan_schedule(scan, so->currPos.currPage);
2044 : :
2045 : : /* Caller's tuple doesn't match the new qual */
2046 : 8545 : return false;
2047 : :
2048 : 4033 : end_toplevel_scan:
2049 : :
2050 : : /*
2051 : : * End the current primitive index scan, but don't schedule another.
2052 : : *
2053 : : * This ends the entire top-level scan in the current scan direction.
2054 : : *
2055 : : * Note: The scan's arrays (including any non-required arrays) are now in
2056 : : * their final positions for the current scan direction. If the scan
2057 : : * direction happens to change, then the arrays will already be in their
2058 : : * first positions for what will then be the current scan direction.
2059 : : */
2060 : 4033 : pstate->continuescan = false; /* Tell _bt_readpage we're done... */
168 2061 : 4033 : so->needPrimScan = false; /* ...and don't call _bt_first again */
2062 : :
2063 : : /* Caller's tuple doesn't match any qual */
236 2064 : 4033 : return false;
2065 : : }
2066 : :
2067 : : #ifdef USE_ASSERT_CHECKING
2068 : : /*
2069 : : * Verify that the scan's "so->keyData[]" scan keys are in agreement with
2070 : : * its array key state
2071 : : */
2072 : : static bool
518 2073 : 192483 : _bt_verify_keys_with_arraykeys(IndexScanDesc scan)
2074 : : {
2075 : 192483 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2076 : 192483 : int last_sk_attno = InvalidAttrNumber,
2077 : 192483 : arrayidx = 0;
66 2078 : 192483 : bool nonrequiredseen = false;
2079 : :
518 2080 [ - + ]: 192483 : if (!so->qual_ok)
518 pg@bowt.ie 2081 :UBC 0 : return false;
2082 : :
518 pg@bowt.ie 2083 [ + + ]:CBC 581089 : for (int ikey = 0; ikey < so->numberOfKeys; ikey++)
2084 : : {
2085 : 388606 : ScanKey cur = so->keyData + ikey;
2086 : : BTArrayKeyInfo *array;
2087 : :
2088 [ + + ]: 388606 : if (cur->sk_strategy != BTEqualStrategyNumber ||
2089 [ + + ]: 333630 : !(cur->sk_flags & SK_SEARCHARRAY))
2090 : 184805 : continue;
2091 : :
2092 : 203801 : array = &so->arrayKeys[arrayidx++];
2093 [ - + ]: 203801 : if (array->scan_key != ikey)
518 pg@bowt.ie 2094 :UBC 0 : return false;
2095 : :
155 pg@bowt.ie 2096 [ + - - + ]:CBC 203801 : if (array->num_elems == 0 || array->num_elems < -1)
518 pg@bowt.ie 2097 :UBC 0 : return false;
2098 : :
155 pg@bowt.ie 2099 [ + + ]:CBC 203801 : if (array->num_elems != -1 &&
2100 [ - + ]: 28614 : cur->sk_argument != array->elem_values[array->cur_elem])
518 pg@bowt.ie 2101 :UBC 0 : return false;
66 pg@bowt.ie 2102 [ + - ]:CBC 203801 : if (cur->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD))
2103 : : {
2104 [ - + ]: 203801 : if (last_sk_attno > cur->sk_attno)
66 pg@bowt.ie 2105 :UBC 0 : return false;
66 pg@bowt.ie 2106 [ - + ]:CBC 203801 : if (nonrequiredseen)
66 pg@bowt.ie 2107 :UBC 0 : return false;
2108 : : }
2109 : : else
2110 : 0 : nonrequiredseen = true;
2111 : :
518 pg@bowt.ie 2112 :CBC 203801 : last_sk_attno = cur->sk_attno;
2113 : : }
2114 : :
2115 [ - + ]: 192483 : if (arrayidx != so->numArrayKeys)
518 pg@bowt.ie 2116 :UBC 0 : return false;
2117 : :
518 pg@bowt.ie 2118 :CBC 192483 : return true;
2119 : : }
2120 : : #endif
2121 : :
2122 : : /*
2123 : : * Test whether an indextuple satisfies all the scankey conditions.
2124 : : *
2125 : : * Return true if so, false if not. If the tuple fails to pass the qual,
2126 : : * we also determine whether there's any need to continue the scan beyond
2127 : : * this tuple, and set pstate.continuescan accordingly. See comments for
2128 : : * _bt_preprocess_keys() about how this is done.
2129 : : *
2130 : : * Forward scan callers can pass a high key tuple in the hopes of having
2131 : : * us set *continuescan to false, and avoiding an unnecessary visit to
2132 : : * the page to the right.
2133 : : *
2134 : : * Advances the scan's array keys when necessary for arrayKeys=true callers.
2135 : : * Scans without any array keys must always pass arrayKeys=false.
2136 : : *
2137 : : * Also stops and starts primitive index scans for arrayKeys=true callers.
2138 : : * Scans with array keys are required to set up page state that helps us with
2139 : : * this. The page's finaltup tuple (the page high key for a forward scan, or
2140 : : * the page's first non-pivot tuple for a backward scan) must be set in
2141 : : * pstate.finaltup ahead of the first call here for the page. Set this to
2142 : : * NULL for rightmost page (or the leftmost page for backwards scans).
2143 : : *
2144 : : * scan: index scan descriptor (containing a search-type scankey)
2145 : : * pstate: page level input and output parameters
2146 : : * arrayKeys: should we advance the scan's array keys if necessary?
2147 : : * tuple: index tuple to test
2148 : : * tupnatts: number of attributes in tupnatts (high key may be truncated)
2149 : : */
2150 : : bool
2151 : 28036965 : _bt_checkkeys(IndexScanDesc scan, BTReadPageState *pstate, bool arrayKeys,
2152 : : IndexTuple tuple, int tupnatts)
2153 : : {
2154 : 28036965 : TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
2155 : 28036965 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
311 2156 : 28036965 : ScanDirection dir = so->currPos.dir;
155 2157 : 28036965 : int ikey = pstate->startikey;
2158 : : bool res;
2159 : :
2359 2160 [ + + - + ]: 28036965 : Assert(BTreeTupleGetNAtts(tuple, scan->indexRelation) == tupnatts);
168 2161 [ + - + - : 28036965 : Assert(!so->needPrimScan && !so->scanBehind && !so->oppositeDirCheck);
- + ]
155 2162 [ + + - + ]: 28036965 : Assert(arrayKeys || so->numArrayKeys == 0);
2163 : :
2164 : 28036965 : res = _bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, arrayKeys,
2165 : 28036965 : pstate->forcenonrequired, &pstate->continuescan,
2166 : : &ikey);
2167 : :
2168 : : /*
2169 : : * If _bt_check_compare relied on the pstate.startikey optimization, call
2170 : : * again (in assert-enabled builds) to verify it didn't affect our answer.
2171 : : *
2172 : : * Note: we can't do this when !pstate.forcenonrequired, since any arrays
2173 : : * before pstate.startikey won't have advanced on this page at all.
2174 : : */
2175 [ + + - + ]: 28036965 : Assert(!pstate->forcenonrequired || arrayKeys);
2176 : : #ifdef USE_ASSERT_CHECKING
2177 [ + + + + ]: 28036965 : if (pstate->startikey > 0 && !pstate->forcenonrequired)
2178 : : {
2179 : : bool dres,
2180 : : dcontinuescan;
518 2181 : 690465 : int dikey = 0;
2182 : :
2183 : : /* Pass arrayKeys=false to avoid array side-effects */
155 2184 : 690465 : dres = _bt_check_compare(scan, dir, tuple, tupnatts, tupdesc, false,
2185 : 690465 : pstate->forcenonrequired, &dcontinuescan,
2186 : : &dikey);
2187 [ - + ]: 690465 : Assert(res == dres);
2188 [ - + ]: 690465 : Assert(pstate->continuescan == dcontinuescan);
2189 : :
2190 : : /*
2191 : : * Should also get the same ikey result. We need a slightly weaker
2192 : : * assertion during arrayKeys calls, since they might be using an
2193 : : * array that couldn't be marked required during preprocessing.
2194 : : */
2195 [ + - - + ]: 690465 : Assert(arrayKeys || ikey == dikey);
2196 [ - + ]: 690465 : Assert(ikey <= dikey);
2197 : : }
2198 : : #endif
2199 : :
2200 : : /*
2201 : : * Only one _bt_check_compare call is required in the common case where
2202 : : * there are no equality strategy array scan keys. Otherwise we can only
2203 : : * accept _bt_check_compare's answer unreservedly when it didn't set
2204 : : * pstate.continuescan=false.
2205 : : */
518 2206 [ + + + + ]: 28036965 : if (!arrayKeys || pstate->continuescan)
2207 : 27922636 : return res;
2208 : :
2209 : : /*
2210 : : * _bt_check_compare call set continuescan=false in the presence of
2211 : : * equality type array keys. This could mean that the tuple is just past
2212 : : * the end of matches for the current array keys.
2213 : : *
2214 : : * It's also possible that the scan is still _before_ the _start_ of
2215 : : * tuples matching the current set of array keys. Check for that first.
2216 : : */
155 2217 [ - + ]: 114329 : Assert(!pstate->forcenonrequired);
518 2218 [ + + ]: 114329 : if (_bt_tuple_before_array_skeys(scan, dir, tuple, tupdesc, tupnatts, true,
2219 : : ikey, NULL))
2220 : : {
2221 : : /* Override _bt_check_compare, continue primitive scan */
168 2222 : 19936 : pstate->continuescan = true;
2223 : :
2224 : : /*
2225 : : * We will end up here repeatedly given a group of tuples > the
2226 : : * previous array keys and < the now-current keys (for a backwards
2227 : : * scan it's just the same, though the operators swap positions).
2228 : : *
2229 : : * We must avoid allowing this linear search process to scan very many
2230 : : * tuples from well before the start of tuples matching the current
2231 : : * array keys (or from well before the point where we'll once again
2232 : : * have to advance the scan's array keys).
2233 : : *
2234 : : * We keep the overhead under control by speculatively "looking ahead"
2235 : : * to later still-unscanned items from this same leaf page. We'll
2236 : : * only attempt this once the number of tuples that the linear search
2237 : : * process has examined starts to get out of hand.
2238 : : */
2239 : 19936 : pstate->rechecks++;
2240 [ + + ]: 19936 : if (pstate->rechecks >= LOOK_AHEAD_REQUIRED_RECHECKS)
2241 : : {
2242 : : /* See if we should skip ahead within the current leaf page */
2243 : 5625 : _bt_checkkeys_look_ahead(scan, pstate, tupnatts, tupdesc);
2244 : :
2245 : : /*
2246 : : * Might have set pstate.skip to a later page offset. When that
2247 : : * happens then _bt_readpage caller will inexpensively skip ahead
2248 : : * to a later tuple from the same page (the one just after the
2249 : : * tuple we successfully "looked ahead" to).
2250 : : */
2251 : : }
2252 : :
2253 : : /* This indextuple doesn't match the current qual, in any case */
518 2254 : 19936 : return false;
2255 : : }
2256 : :
2257 : : /*
2258 : : * Caller's tuple is >= the current set of array keys and other equality
2259 : : * constraint scan keys (or <= if this is a backwards scan). It's now
2260 : : * clear that we _must_ advance any required array keys in lockstep with
2261 : : * the scan.
2262 : : */
2263 : 94393 : return _bt_advance_array_keys(scan, pstate, tuple, tupnatts, tupdesc,
2264 : : ikey, true);
2265 : : }
2266 : :
2267 : : /*
2268 : : * Test whether caller's finaltup tuple is still before the start of matches
2269 : : * for the current array keys.
2270 : : *
2271 : : * Called at the start of reading a page during a scan with array keys, though
2272 : : * only when the so->scanBehind flag was set on the scan's prior page.
2273 : : *
2274 : : * Returns false if the tuple is still before the start of matches. When that
2275 : : * happens, caller should cut its losses and start a new primitive index scan.
2276 : : * Otherwise returns true.
2277 : : */
2278 : : bool
168 2279 : 1291 : _bt_scanbehind_checkkeys(IndexScanDesc scan, ScanDirection dir,
2280 : : IndexTuple finaltup)
2281 : : {
2282 : 1291 : Relation rel = scan->indexRelation;
2283 : 1291 : TupleDesc tupdesc = RelationGetDescr(rel);
2284 : 1291 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2285 [ + + ]: 1291 : int nfinaltupatts = BTreeTupleGetNAtts(finaltup, rel);
2286 : : bool scanBehind;
2287 : :
2288 [ - + ]: 1291 : Assert(so->numArrayKeys);
2289 : :
2290 [ + + ]: 1291 : if (_bt_tuple_before_array_skeys(scan, dir, finaltup, tupdesc,
2291 : : nfinaltupatts, false, 0, &scanBehind))
122 2292 : 206 : return false;
2293 : :
2294 : : /*
2295 : : * If scanBehind was set, all of the untruncated attribute values from
2296 : : * finaltup that correspond to an array match the array's current element,
2297 : : * but there are other keys associated with truncated suffix attributes.
2298 : : * Array advancement must have incremented the scan's arrays on the
2299 : : * previous page, resulting in a set of array keys that happen to be an
2300 : : * exact match for the current page high key's untruncated prefix values.
2301 : : *
2302 : : * This page definitely doesn't contain tuples that the scan will need to
2303 : : * return. The next page may or may not contain relevant tuples. Handle
2304 : : * this by cutting our losses and starting a new primscan.
2305 : : */
2306 [ - + ]: 1085 : if (scanBehind)
168 pg@bowt.ie 2307 :UBC 0 : return false;
2308 : :
168 pg@bowt.ie 2309 [ + + ]:CBC 1085 : if (!so->oppositeDirCheck)
2310 : 1022 : return true;
2311 : :
2312 : 63 : return _bt_oppodir_checkkeys(scan, dir, finaltup);
2313 : : }
2314 : :
2315 : : /*
2316 : : * Test whether an indextuple fails to satisfy an inequality required in the
2317 : : * opposite direction only.
2318 : : *
2319 : : * Caller's finaltup tuple is the page high key (for forwards scans), or the
2320 : : * first non-pivot tuple (for backwards scans). Called during scans with
2321 : : * required array keys and required opposite-direction inequalities.
2322 : : *
2323 : : * Returns false if an inequality scan key required in the opposite direction
2324 : : * only isn't satisfied (and any earlier required scan keys are satisfied).
2325 : : * Otherwise returns true.
2326 : : *
2327 : : * An unsatisfied inequality required in the opposite direction only might
2328 : : * well enable skipping over many leaf pages, provided another _bt_first call
2329 : : * takes place. This type of unsatisfied inequality won't usually cause
2330 : : * _bt_checkkeys to stop the scan to consider array advancement/starting a new
2331 : : * primitive index scan.
2332 : : */
2333 : : static bool
325 2334 : 2209 : _bt_oppodir_checkkeys(IndexScanDesc scan, ScanDirection dir,
2335 : : IndexTuple finaltup)
2336 : : {
2337 : 2209 : Relation rel = scan->indexRelation;
2338 : 2209 : TupleDesc tupdesc = RelationGetDescr(rel);
2339 : 2209 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2340 [ + - ]: 2209 : int nfinaltupatts = BTreeTupleGetNAtts(finaltup, rel);
2341 : : bool continuescan;
2342 : 2209 : ScanDirection flipped = -dir;
2343 : 2209 : int ikey = 0;
2344 : :
2345 [ - + ]: 2209 : Assert(so->numArrayKeys);
2346 : :
155 2347 : 2209 : _bt_check_compare(scan, flipped, finaltup, nfinaltupatts, tupdesc, false,
2348 : : false, &continuescan,
2349 : : &ikey);
2350 : :
325 2351 [ + - + + ]: 2209 : if (!continuescan && so->keyData[ikey].sk_strategy != BTEqualStrategyNumber)
325 pg@bowt.ie 2352 :GBC 1 : return false;
2353 : :
325 pg@bowt.ie 2354 :CBC 2208 : return true;
2355 : : }
2356 : :
2357 : : /*
2358 : : * Determines an offset to the first scan key (an so->keyData[]-wise offset)
2359 : : * that is _not_ guaranteed to be satisfied by every tuple from pstate.page,
2360 : : * which is set in pstate.startikey for _bt_checkkeys calls for the page.
2361 : : * This allows caller to save cycles on comparisons of a prefix of keys while
2362 : : * reading pstate.page.
2363 : : *
2364 : : * Also determines if later calls to _bt_checkkeys (for pstate.page) should be
2365 : : * forced to treat all required scan keys >= pstate.startikey as nonrequired
2366 : : * (that is, if they're to be treated as if any SK_BT_REQFWD/SK_BT_REQBKWD
2367 : : * markings that were set by preprocessing were not set at all, for the
2368 : : * duration of _bt_checkkeys calls prior to the call for pstate.finaltup).
2369 : : * This is indicated to caller by setting pstate.forcenonrequired.
2370 : : *
2371 : : * Call here at the start of reading a leaf page beyond the first one for the
2372 : : * primitive index scan. We consider all non-pivot tuples, so it doesn't make
2373 : : * sense to call here when only a subset of those tuples can ever be read.
2374 : : * This is also a good idea on performance grounds; not calling here when on
2375 : : * the first page (first for the current primitive scan) avoids wasting cycles
2376 : : * during selective point queries. They typically don't stand to gain as much
2377 : : * when we can set pstate.startikey, and are likely to notice the overhead of
2378 : : * calling here. (Also, allowing pstate.forcenonrequired to be set on a
2379 : : * primscan's first page would mislead _bt_advance_array_keys, which expects
2380 : : * pstate.nskipadvances to be representative of every first page's key space.)
2381 : : *
2382 : : * Caller must call _bt_start_array_keys and reset startikey/forcenonrequired
2383 : : * ahead of the finaltup _bt_checkkeys call when we set forcenonrequired=true.
2384 : : * This will give _bt_checkkeys the opportunity to call _bt_advance_array_keys
2385 : : * with sktrig_required=true, restoring the invariant that the scan's required
2386 : : * arrays always track the scan's progress through the index's key space.
2387 : : * Caller won't need to do this on the rightmost/leftmost page in the index
2388 : : * (where pstate.finaltup isn't ever set), since forcenonrequired will never
2389 : : * be set here in the first place.
2390 : : */
2391 : : void
155 2392 : 15057 : _bt_set_startikey(IndexScanDesc scan, BTReadPageState *pstate)
2393 : : {
2394 : 15057 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2395 : 15057 : Relation rel = scan->indexRelation;
2396 : 15057 : TupleDesc tupdesc = RelationGetDescr(rel);
2397 : : ItemId iid;
2398 : : IndexTuple firsttup,
2399 : : lasttup;
2400 : 15057 : int startikey = 0,
2401 : 15057 : arrayidx = 0,
2402 : : firstchangingattnum;
2403 : 15057 : bool start_past_saop_eq = false;
2404 : :
2405 [ - + ]: 15057 : Assert(!so->scanBehind);
2406 [ - + ]: 15057 : Assert(pstate->minoff < pstate->maxoff);
2407 [ - + ]: 15057 : Assert(!pstate->firstpage);
2408 [ - + ]: 15057 : Assert(pstate->startikey == 0);
2409 [ + + + + : 15057 : Assert(!so->numArrayKeys || pstate->finaltup ||
- + - - ]
2410 : : P_RIGHTMOST(BTPageGetOpaque(pstate->page)) ||
2411 : : P_LEFTMOST(BTPageGetOpaque(pstate->page)));
2412 : :
2413 [ + + ]: 15057 : if (so->numberOfKeys == 0)
2414 : 6521 : return;
2415 : :
2416 : : /* minoff is an offset to the lowest non-pivot tuple on the page */
2417 : 8536 : iid = PageGetItemId(pstate->page, pstate->minoff);
2418 : 8536 : firsttup = (IndexTuple) PageGetItem(pstate->page, iid);
2419 : :
2420 : : /* maxoff is an offset to the highest non-pivot tuple on the page */
2421 : 8536 : iid = PageGetItemId(pstate->page, pstate->maxoff);
2422 : 8536 : lasttup = (IndexTuple) PageGetItem(pstate->page, iid);
2423 : :
2424 : : /* Determine the first attribute whose values change on caller's page */
2425 : 8536 : firstchangingattnum = _bt_keep_natts_fast(rel, firsttup, lasttup);
2426 : :
2427 [ + + ]: 13005 : for (; startikey < so->numberOfKeys; startikey++)
2428 : : {
2429 : 9954 : ScanKey key = so->keyData + startikey;
2430 : : BTArrayKeyInfo *array;
2431 : : Datum firstdatum,
2432 : : lastdatum;
2433 : : bool firstnull,
2434 : : lastnull;
2435 : : int32 result;
2436 : :
2437 : : /*
2438 : : * Determine if it's safe to set pstate.startikey to an offset to a
2439 : : * key that comes after this key, by examining this key
2440 : : */
2441 [ - + ]: 9954 : if (!(key->sk_flags & (SK_BT_REQFWD | SK_BT_REQBKWD)))
2442 : : {
2443 : : /* Scan key isn't marked required (corner case) */
2444 : 5485 : break; /* unsafe */
2445 : : }
2446 [ - + ]: 9954 : if (key->sk_flags & SK_ROW_HEADER)
2447 : : {
2448 : : /* RowCompare inequalities currently aren't supported */
66 pg@bowt.ie 2449 :UBC 0 : break; /* "unsafe" */
2450 : : }
155 pg@bowt.ie 2451 [ + + ]:CBC 9954 : if (key->sk_strategy != BTEqualStrategyNumber)
2452 : : {
2453 : : /*
2454 : : * Scalar inequality key.
2455 : : *
2456 : : * It's definitely safe for _bt_checkkeys to avoid assessing this
2457 : : * inequality when the page's first and last non-pivot tuples both
2458 : : * satisfy the inequality (since the same must also be true of all
2459 : : * the tuples in between these two).
2460 : : *
2461 : : * Unlike the "=" case, it doesn't matter if this attribute has
2462 : : * more than one distinct value (though it _is_ necessary for any
2463 : : * and all _prior_ attributes to contain no more than one distinct
2464 : : * value amongst all of the tuples from pstate.page).
2465 : : */
2466 [ + + ]: 2229 : if (key->sk_attno > firstchangingattnum) /* >, not >= */
2467 : 180 : break; /* unsafe, preceding attr has multiple
2468 : : * distinct values */
2469 : :
2470 : 2049 : firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc, &firstnull);
2471 : 2049 : lastdatum = index_getattr(lasttup, key->sk_attno, tupdesc, &lastnull);
2472 : :
2473 [ + + ]: 2049 : if (key->sk_flags & SK_ISNULL)
2474 : : {
2475 : : /* IS NOT NULL key */
2476 [ - + ]: 65 : Assert(key->sk_flags & SK_SEARCHNOTNULL);
2477 : :
2478 [ + - + - ]: 65 : if (firstnull || lastnull)
2479 : : break; /* unsafe */
2480 : :
2481 : : /* Safe, IS NOT NULL key satisfied by every tuple */
2482 : 4346 : continue;
2483 : : }
2484 : :
2485 : : /* Test firsttup */
2486 [ + - ]: 1984 : if (firstnull ||
2487 [ + + ]: 1984 : !DatumGetBool(FunctionCall2Coll(&key->sk_func,
2488 : : key->sk_collation, firstdatum,
2489 : : key->sk_argument)))
2490 : : break; /* unsafe */
2491 : :
2492 : : /* Test lasttup */
2493 [ + - ]: 1982 : if (lastnull ||
2494 [ + + ]: 1982 : !DatumGetBool(FunctionCall2Coll(&key->sk_func,
2495 : : key->sk_collation, lastdatum,
2496 : : key->sk_argument)))
2497 : : break; /* unsafe */
2498 : :
2499 : : /* Safe, scalar inequality satisfied by every tuple */
2500 : 1934 : continue;
2501 : : }
2502 : :
2503 : : /* Some = key (could be a scalar = key, could be an array = key) */
2504 [ - + ]: 7725 : Assert(key->sk_strategy == BTEqualStrategyNumber);
2505 : :
2506 [ + + ]: 7725 : if (!(key->sk_flags & SK_SEARCHARRAY))
2507 : : {
2508 : : /*
2509 : : * Scalar = key (possibly an IS NULL key).
2510 : : *
2511 : : * It is unsafe to set pstate.startikey to an ikey beyond this
2512 : : * key, unless the = key is satisfied by every possible tuple on
2513 : : * the page (possible only when attribute has just one distinct
2514 : : * value among all tuples on the page).
2515 : : */
2516 [ + + ]: 6094 : if (key->sk_attno >= firstchangingattnum)
2517 : 4928 : break; /* unsafe, multiple distinct attr values */
2518 : :
2519 : 1166 : firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc,
2520 : : &firstnull);
2521 [ - + ]: 1166 : if (key->sk_flags & SK_ISNULL)
2522 : : {
2523 : : /* IS NULL key */
155 pg@bowt.ie 2524 [ # # ]:UBC 0 : Assert(key->sk_flags & SK_SEARCHNULL);
2525 : :
2526 [ # # ]: 0 : if (!firstnull)
2527 : 0 : break; /* unsafe */
2528 : :
2529 : : /* Safe, IS NULL key satisfied by every tuple */
2530 : 0 : continue;
2531 : : }
155 pg@bowt.ie 2532 [ + - ]:CBC 1166 : if (firstnull ||
2533 [ + - ]: 1166 : !DatumGetBool(FunctionCall2Coll(&key->sk_func,
2534 : : key->sk_collation, firstdatum,
2535 : : key->sk_argument)))
2536 : : break; /* unsafe */
2537 : :
2538 : : /* Safe, scalar = key satisfied by every tuple */
2539 : 1166 : continue;
2540 : : }
2541 : :
2542 : : /* = array key (could be a SAOP array, could be a skip array) */
2543 : 1631 : array = &so->arrayKeys[arrayidx++];
2544 [ - + ]: 1631 : Assert(array->scan_key == startikey);
2545 [ + + ]: 1631 : if (array->num_elems != -1)
2546 : : {
2547 : : /*
2548 : : * SAOP array = key.
2549 : : *
2550 : : * Handle this like we handle scalar = keys (though binary search
2551 : : * for a matching element, to avoid relying on key's sk_argument).
2552 : : */
2553 [ + - ]: 296 : if (key->sk_attno >= firstchangingattnum)
2554 : 296 : break; /* unsafe, multiple distinct attr values */
2555 : :
155 pg@bowt.ie 2556 :UBC 0 : firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc,
2557 : : &firstnull);
2558 : 0 : _bt_binsrch_array_skey(&so->orderProcs[startikey],
2559 : : false, NoMovementScanDirection,
2560 : : firstdatum, firstnull, array, key,
2561 : : &result);
2562 [ # # ]: 0 : if (result != 0)
2563 : 0 : break; /* unsafe */
2564 : :
2565 : : /* Safe, SAOP = key satisfied by every tuple */
2566 : 0 : start_past_saop_eq = true;
2567 : 0 : continue;
2568 : : }
2569 : :
2570 : : /*
2571 : : * Skip array = key
2572 : : */
155 pg@bowt.ie 2573 [ - + ]:CBC 1335 : Assert(key->sk_flags & SK_BT_SKIP);
2574 [ + + ]: 1335 : if (array->null_elem)
2575 : : {
2576 : : /*
2577 : : * Non-range skip array = key.
2578 : : *
2579 : : * Safe, non-range skip array "satisfied" by every tuple on page
2580 : : * (safe even when "key->sk_attno > firstchangingattnum").
2581 : : */
2582 : 1181 : continue;
2583 : : }
2584 : :
2585 : : /*
2586 : : * Range skip array = key.
2587 : : *
2588 : : * Handle this like we handle scalar inequality keys (but avoid using
2589 : : * key's sk_argument directly, as in the SAOP array case).
2590 : : */
2591 [ + + ]: 154 : if (key->sk_attno > firstchangingattnum) /* >, not >= */
2592 : 24 : break; /* unsafe, preceding attr has multiple
2593 : : * distinct values */
2594 : :
2595 : 130 : firstdatum = index_getattr(firsttup, key->sk_attno, tupdesc, &firstnull);
2596 : 130 : lastdatum = index_getattr(lasttup, key->sk_attno, tupdesc, &lastnull);
2597 : :
2598 : : /* Test firsttup */
2599 : 130 : _bt_binsrch_skiparray_skey(false, ForwardScanDirection,
2600 : : firstdatum, firstnull, array, key,
2601 : : &result);
2602 [ - + ]: 130 : if (result != 0)
155 pg@bowt.ie 2603 :UBC 0 : break; /* unsafe */
2604 : :
2605 : : /* Test lasttup */
155 pg@bowt.ie 2606 :CBC 130 : _bt_binsrch_skiparray_skey(false, ForwardScanDirection,
2607 : : lastdatum, lastnull, array, key,
2608 : : &result);
2609 [ + + ]: 130 : if (result != 0)
2610 : 7 : break; /* unsafe */
2611 : :
2612 : : /* Safe, range skip array satisfied by every tuple on page */
2613 : : }
2614 : :
2615 : : /*
2616 : : * Use of forcenonrequired is typically undesirable, since it'll force
2617 : : * _bt_readpage caller to read every tuple on the page -- even though, in
2618 : : * general, it might well be possible to end the scan on an earlier tuple.
2619 : : * However, caller must use forcenonrequired when start_past_saop_eq=true,
2620 : : * since the usual required array behavior might fail to roll over to the
2621 : : * SAOP array.
2622 : : *
2623 : : * We always prefer forcenonrequired=true during scans with skip arrays
2624 : : * (except on the first page of each primitive index scan), though -- even
2625 : : * when "startikey == 0". That way, _bt_advance_array_keys's low-order
2626 : : * key precheck optimization can always be used (unless on the first page
2627 : : * of the scan). It seems slightly preferable to check more tuples when
2628 : : * that allows us to do significantly less skip array maintenance.
2629 : : */
2630 [ + - + + ]: 8536 : pstate->forcenonrequired = (start_past_saop_eq || so->skipScan);
2631 : 8536 : pstate->startikey = startikey;
2632 : :
2633 : : /*
2634 : : * _bt_readpage caller is required to call _bt_checkkeys against page's
2635 : : * finaltup with forcenonrequired=false whenever we initially set
2636 : : * forcenonrequired=true. That way the scan's arrays will reliably track
2637 : : * its progress through the index's key space.
2638 : : *
2639 : : * We don't expect this when _bt_readpage caller has no finaltup due to
2640 : : * its page being the rightmost (or the leftmost, during backwards scans).
2641 : : * When we see that _bt_readpage has no finaltup, back out of everything.
2642 : : */
2643 [ + + - + ]: 8536 : Assert(!pstate->forcenonrequired || so->numArrayKeys);
2644 [ + + + + ]: 8536 : if (pstate->forcenonrequired && !pstate->finaltup)
2645 : : {
2646 : 235 : pstate->forcenonrequired = false;
2647 : 235 : pstate->startikey = 0;
2648 : : }
2649 : : }
2650 : :
2651 : : /*
2652 : : * Test whether an indextuple satisfies current scan condition.
2653 : : *
2654 : : * Return true if so, false if not. If not, also sets *continuescan to false
2655 : : * when it's also not possible for any later tuples to pass the current qual
2656 : : * (with the scan's current set of array keys, in the current scan direction),
2657 : : * in addition to setting *ikey to the so->keyData[] subscript/offset for the
2658 : : * unsatisfied scan key (needed when caller must consider advancing the scan's
2659 : : * array keys).
2660 : : *
2661 : : * This is a subroutine for _bt_checkkeys. We provisionally assume that
2662 : : * reaching the end of the current set of required keys (in particular the
2663 : : * current required array keys) ends the ongoing (primitive) index scan.
2664 : : * Callers without array keys should just end the scan right away when they
2665 : : * find that continuescan has been set to false here by us. Things are more
2666 : : * complicated for callers with array keys.
2667 : : *
2668 : : * Callers with array keys must first consider advancing the arrays when
2669 : : * continuescan has been set to false here by us. They must then consider if
2670 : : * it really does make sense to end the current (primitive) index scan, in
2671 : : * light of everything that is known at that point. (In general when we set
2672 : : * continuescan=false for these callers it must be treated as provisional.)
2673 : : *
2674 : : * We deal with advancing unsatisfied non-required arrays directly, though.
2675 : : * This is safe, since by definition non-required keys can't end the scan.
2676 : : * This is just how we determine if non-required arrays are just unsatisfied
2677 : : * by the current array key, or if they're truly unsatisfied (that is, if
2678 : : * they're unsatisfied by every possible array key).
2679 : : *
2680 : : * Pass advancenonrequired=false to avoid all array related side effects.
2681 : : * This allows _bt_advance_array_keys caller to avoid infinite recursion.
2682 : : *
2683 : : * Pass forcenonrequired=true to instruct us to treat all keys as nonrequired.
2684 : : * This is used to make it safe to temporarily stop properly maintaining the
2685 : : * scan's required arrays. _bt_checkkeys caller (_bt_readpage, actually)
2686 : : * determines a prefix of keys that must satisfy every possible corresponding
2687 : : * index attribute value from its page, which is passed to us via *ikey arg
2688 : : * (this is the first key that might be unsatisfied by tuples on the page).
2689 : : * Obviously, we won't maintain any array keys from before *ikey, so it's
2690 : : * quite possible for such arrays to "fall behind" the index's keyspace.
2691 : : * Caller will need to "catch up" by passing forcenonrequired=true (alongside
2692 : : * an *ikey=0) once the page's finaltup is reached.
2693 : : *
2694 : : * Note: it's safe to pass an *ikey > 0 with forcenonrequired=false, but only
2695 : : * when caller determines that it won't affect array maintenance.
2696 : : */
2697 : : static bool
518 2698 : 28757545 : _bt_check_compare(IndexScanDesc scan, ScanDirection dir,
2699 : : IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
2700 : : bool advancenonrequired, bool forcenonrequired,
2701 : : bool *continuescan, int *ikey)
2702 : : {
2703 : 28757545 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
2704 : :
2705 : 28757545 : *continuescan = true; /* default assumption */
2706 : :
2707 [ + + ]: 55169112 : for (; *ikey < so->numberOfKeys; (*ikey)++)
2708 : : {
2709 : 31837716 : ScanKey key = so->keyData + *ikey;
2710 : : Datum datum;
2711 : : bool isNull;
701 akorotkov@postgresql 2712 : 31837716 : bool requiredSameDir = false,
518 pg@bowt.ie 2713 : 31837716 : requiredOppositeDirOnly = false;
2714 : :
2715 : : /*
2716 : : * Check if the key is required in the current scan direction, in the
2717 : : * opposite scan direction _only_, or in neither direction (except
2718 : : * when we're forced to treat all scan keys as nonrequired)
2719 : : */
155 2720 [ + + ]: 31837716 : if (forcenonrequired)
2721 : : {
2722 : : /* treating scan's keys as non-required */
2723 : : }
2724 [ + + + + ]: 31635868 : else if (((key->sk_flags & SK_BT_REQFWD) && ScanDirectionIsForward(dir)) ||
2725 [ + + + + ]: 7472561 : ((key->sk_flags & SK_BT_REQBKWD) && ScanDirectionIsBackward(dir)))
701 akorotkov@postgresql 2726 : 24175651 : requiredSameDir = true;
2727 [ + + - + ]: 7460217 : else if (((key->sk_flags & SK_BT_REQFWD) && ScanDirectionIsBackward(dir)) ||
2728 [ + - + - ]: 2899528 : ((key->sk_flags & SK_BT_REQBKWD) && ScanDirectionIsForward(dir)))
518 pg@bowt.ie 2729 : 7460217 : requiredOppositeDirOnly = true;
2730 : :
2359 2731 [ + + ]: 31837716 : if (key->sk_attno > tupnatts)
2732 : : {
2733 : : /*
2734 : : * This attribute is truncated (must be high key). The value for
2735 : : * this attribute in the first non-pivot tuple on the page to the
2736 : : * right could be any possible value. Assume that truncated
2737 : : * attribute passes the qual.
2738 : : */
2019 2739 [ - + ]: 1145 : Assert(BTreeTupleIsPivot(tuple));
2359 2740 : 9592887 : continue;
2741 : : }
2742 : :
2743 : : /*
2744 : : * A skip array scan key uses one of several sentinel values. We just
2745 : : * fall back on _bt_tuple_before_array_skeys when we see such a value.
2746 : : */
155 2747 [ + + ]: 31836571 : if (key->sk_flags & (SK_BT_MINVAL | SK_BT_MAXVAL |
2748 : : SK_BT_NEXT | SK_BT_PRIOR))
2749 : : {
2750 [ - + ]: 17934 : Assert(key->sk_flags & SK_SEARCHARRAY);
2751 [ - + ]: 17934 : Assert(key->sk_flags & SK_BT_SKIP);
2752 [ + + - + ]: 17934 : Assert(requiredSameDir || forcenonrequired);
2753 : :
2754 : : /*
2755 : : * Cannot fall back on _bt_tuple_before_array_skeys when we're
2756 : : * treating the scan's keys as nonrequired, though. Just handle
2757 : : * this like any other non-required equality-type array key.
2758 : : */
2759 [ + + ]: 17934 : if (forcenonrequired)
2760 : 5426149 : return _bt_advance_array_keys(scan, NULL, tuple, tupnatts,
2761 : : tupdesc, *ikey, false);
2762 : :
2763 : 16920 : *continuescan = false;
2764 : 16920 : return false;
2765 : : }
2766 : :
2767 : : /* row-comparison keys need special processing */
7164 tgl@sss.pgh.pa.us 2768 [ + + ]: 31818637 : if (key->sk_flags & SK_ROW_HEADER)
2769 : : {
2359 pg@bowt.ie 2770 [ + + ]: 1227 : if (_bt_check_rowcompare(key, tuple, tupnatts, tupdesc, dir,
2771 : : forcenonrequired, continuescan))
7164 tgl@sss.pgh.pa.us 2772 : 1194 : continue;
2359 pg@bowt.ie 2773 : 33 : return false;
2774 : : }
2775 : :
10226 bruce@momjian.us 2776 : 31817410 : datum = index_getattr(tuple,
9174 tgl@sss.pgh.pa.us 2777 : 31817410 : key->sk_attno,
2778 : : tupdesc,
2779 : : &isNull);
2780 : :
2781 [ + + ]: 31817410 : if (key->sk_flags & SK_ISNULL)
2782 : : {
2783 : : /* Handle IS NULL/NOT NULL tests */
5727 2784 [ + + ]: 9599434 : if (key->sk_flags & SK_SEARCHNULL)
2785 : : {
2786 [ + + ]: 9064 : if (isNull)
5671 bruce@momjian.us 2787 : 214 : continue; /* tuple satisfies this qual */
2788 : : }
2789 : : else
2790 : : {
5727 tgl@sss.pgh.pa.us 2791 [ - + ]: 9590370 : Assert(key->sk_flags & SK_SEARCHNOTNULL);
155 pg@bowt.ie 2792 [ - + ]: 9590370 : Assert(!(key->sk_flags & SK_BT_SKIP));
5727 tgl@sss.pgh.pa.us 2793 [ + + ]: 9590370 : if (!isNull)
5671 bruce@momjian.us 2794 : 9590334 : continue; /* tuple satisfies this qual */
2795 : : }
2796 : :
2797 : : /*
2798 : : * Tuple fails this qual. If it's a required qual for the current
2799 : : * scan direction, then we can conclude no further tuples will
2800 : : * pass, either.
2801 : : */
701 akorotkov@postgresql 2802 [ + + ]: 8886 : if (requiredSameDir)
6728 tgl@sss.pgh.pa.us 2803 : 102 : *continuescan = false;
155 pg@bowt.ie 2804 [ - + ]: 8784 : else if (unlikely(key->sk_flags & SK_BT_SKIP))
2805 : : {
2806 : : /*
2807 : : * If we're treating scan keys as nonrequired, and encounter a
2808 : : * skip array scan key whose current element is NULL, then it
2809 : : * must be a non-range skip array. It must be satisfied, so
2810 : : * there's no need to call _bt_advance_array_keys to check.
2811 : : */
155 pg@bowt.ie 2812 [ # # # # ]:UBC 0 : Assert(forcenonrequired && *ikey > 0);
2813 : 0 : continue;
2814 : : }
2815 : :
2816 : : /*
2817 : : * This indextuple doesn't match the qual.
2818 : : */
2359 pg@bowt.ie 2819 :CBC 8886 : return false;
2820 : : }
2821 : :
9174 tgl@sss.pgh.pa.us 2822 [ + + ]: 22217976 : if (isNull)
2823 : : {
2824 : : /*
2825 : : * Scalar scan key isn't satisfied by NULL tuple value.
2826 : : *
2827 : : * If we're treating scan keys as nonrequired, and key is for a
2828 : : * skip array, then we must attempt to advance the array to NULL
2829 : : * (if we're successful then the tuple might match the qual).
2830 : : */
131 pg@bowt.ie 2831 [ - + - - : 114 : if (unlikely(forcenonrequired && key->sk_flags & SK_BT_SKIP))
- + ]
131 pg@bowt.ie 2832 :UBC 0 : return _bt_advance_array_keys(scan, NULL, tuple, tupnatts,
2833 : : tupdesc, *ikey, false);
2834 : :
5057 tgl@sss.pgh.pa.us 2835 [ - + ]:CBC 114 : if (key->sk_flags & SK_BT_NULLS_FIRST)
2836 : : {
2837 : : /*
2838 : : * Since NULLs are sorted before non-NULLs, we know we have
2839 : : * reached the lower limit of the range of values for this
2840 : : * index attr. On a backward scan, we can stop if this qual
2841 : : * is one of the "must match" subset. We can stop regardless
2842 : : * of whether the qual is > or <, so long as it's required,
2843 : : * because it's not possible for any future tuples to pass. On
2844 : : * a forward scan, however, we must keep going, because we may
2845 : : * have initially positioned to the start of the index.
2846 : : * (_bt_advance_array_keys also relies on this behavior during
2847 : : * forward scans.)
2848 : : */
155 pg@bowt.ie 2849 [ # # # # :UBC 0 : if ((requiredSameDir || requiredOppositeDirOnly) &&
# # ]
2850 : : ScanDirectionIsBackward(dir))
5057 tgl@sss.pgh.pa.us 2851 : 0 : *continuescan = false;
2852 : : }
2853 : : else
2854 : : {
2855 : : /*
2856 : : * Since NULLs are sorted after non-NULLs, we know we have
2857 : : * reached the upper limit of the range of values for this
2858 : : * index attr. On a forward scan, we can stop if this qual is
2859 : : * one of the "must match" subset. We can stop regardless of
2860 : : * whether the qual is > or <, so long as it's required,
2861 : : * because it's not possible for any future tuples to pass. On
2862 : : * a backward scan, however, we must keep going, because we
2863 : : * may have initially positioned to the end of the index.
2864 : : * (_bt_advance_array_keys also relies on this behavior during
2865 : : * backward scans.)
2866 : : */
155 pg@bowt.ie 2867 [ + + + - :CBC 114 : if ((requiredSameDir || requiredOppositeDirOnly) &&
+ + ]
2868 : : ScanDirectionIsForward(dir))
5057 tgl@sss.pgh.pa.us 2869 : 111 : *continuescan = false;
2870 : : }
2871 : :
2872 : : /*
2873 : : * This indextuple doesn't match the qual.
2874 : : */
2359 pg@bowt.ie 2875 : 114 : return false;
2876 : : }
2877 : :
155 2878 [ + + ]: 22217862 : if (!DatumGetBool(FunctionCall2Coll(&key->sk_func, key->sk_collation,
2879 : : datum, key->sk_argument)))
2880 : : {
2881 : : /*
2882 : : * Tuple fails this qual. If it's a required qual for the current
2883 : : * scan direction, then we can conclude no further tuples will
2884 : : * pass, either.
2885 : : *
2886 : : * Note: because we stop the scan as soon as any required equality
2887 : : * qual fails, it is critical that equality quals be used for the
2888 : : * initial positioning in _bt_first() when they are available. See
2889 : : * comments in _bt_first().
2890 : : */
701 akorotkov@postgresql 2891 [ + + ]: 5399182 : if (requiredSameDir)
7166 tgl@sss.pgh.pa.us 2892 : 5222463 : *continuescan = false;
2893 : :
2894 : : /*
2895 : : * If this is a non-required equality-type array key, the tuple
2896 : : * needs to be checked against every possible array key. Handle
2897 : : * this by "advancing" the scan key's array to a matching value
2898 : : * (if we're successful then the tuple might match the qual).
2899 : : */
518 pg@bowt.ie 2900 [ + + ]: 176719 : else if (advancenonrequired &&
2901 [ + + ]: 172999 : key->sk_strategy == BTEqualStrategyNumber &&
2902 [ + + ]: 135102 : (key->sk_flags & SK_SEARCHARRAY))
2903 : 3350 : return _bt_advance_array_keys(scan, NULL, tuple, tupnatts,
2904 : : tupdesc, *ikey, false);
2905 : :
2906 : : /*
2907 : : * This indextuple doesn't match the qual.
2908 : : */
2359 2909 : 5395832 : return false;
2910 : : }
2911 : : }
2912 : :
2913 : : /* If we get here, the tuple passes all index quals. */
2914 : 23331396 : return true;
2915 : : }
2916 : :
2917 : : /*
2918 : : * Test whether an indextuple satisfies a row-comparison scan condition.
2919 : : *
2920 : : * Return true if so, false if not. If not, also clear *continuescan if
2921 : : * it's not possible for any future tuples in the current scan direction
2922 : : * to pass the qual.
2923 : : *
2924 : : * This is a subroutine for _bt_checkkeys/_bt_check_compare.
2925 : : */
2926 : : static bool
2927 : 1227 : _bt_check_rowcompare(ScanKey skey, IndexTuple tuple, int tupnatts,
2928 : : TupleDesc tupdesc, ScanDirection dir,
2929 : : bool forcenonrequired, bool *continuescan)
2930 : : {
7164 tgl@sss.pgh.pa.us 2931 : 1227 : ScanKey subkey = (ScanKey) DatumGetPointer(skey->sk_argument);
2932 : 1227 : int32 cmpresult = 0;
2933 : : bool result;
2934 : :
2935 : : /* First subkey should be same as the header says */
2936 [ + - ]: 1227 : Assert(subkey->sk_attno == skey->sk_attno);
2937 : :
2938 : : /* Loop over columns of the row condition */
2939 : : for (;;)
2940 : 120 : {
2941 : : Datum datum;
2942 : : bool isNull;
2943 : :
2944 [ - + ]: 1347 : Assert(subkey->sk_flags & SK_ROW_MEMBER);
2945 : :
2946 : : /* When a NULL row member is compared, the row never matches */
66 pg@bowt.ie 2947 [ + + ]: 1347 : if (subkey->sk_flags & SK_ISNULL)
2948 : : {
2949 : : /*
2950 : : * Unlike the simple-scankey case, this isn't a disallowed case
2951 : : * (except when it's the first row element that has the NULL arg).
2952 : : * But it can never match. If all the earlier row comparison
2953 : : * columns are required for the scan direction, we can stop the
2954 : : * scan, because there can't be another tuple that will succeed.
2955 : : */
2956 [ - + ]: 6 : Assert(subkey != (ScanKey) DatumGetPointer(skey->sk_argument));
2957 : 6 : subkey--;
2958 [ + - ]: 6 : if (forcenonrequired)
2959 : : {
2960 : : /* treating scan's keys as non-required */
2961 : : }
2962 [ + + + - ]: 6 : else if ((subkey->sk_flags & SK_BT_REQFWD) &&
2963 : : ScanDirectionIsForward(dir))
2964 : 3 : *continuescan = false;
2965 [ + - + - ]: 3 : else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
2966 : : ScanDirectionIsBackward(dir))
2967 : 3 : *continuescan = false;
2968 : 33 : return false;
2969 : : }
2970 : :
2359 2971 [ + + ]: 1341 : if (subkey->sk_attno > tupnatts)
2972 : : {
2973 : : /*
2974 : : * This attribute is truncated (must be high key). The value for
2975 : : * this attribute in the first non-pivot tuple on the page to the
2976 : : * right could be any possible value. Assume that truncated
2977 : : * attribute passes the qual.
2978 : : */
2019 2979 [ - + ]: 3 : Assert(BTreeTupleIsPivot(tuple));
66 2980 : 3 : return true;
2981 : : }
2982 : :
7164 tgl@sss.pgh.pa.us 2983 : 1338 : datum = index_getattr(tuple,
2984 : 1338 : subkey->sk_attno,
2985 : : tupdesc,
2986 : : &isNull);
2987 : :
2988 [ + + ]: 1338 : if (isNull)
2989 : : {
2990 : : int reqflags;
2991 : :
87 pg@bowt.ie 2992 [ + - ]: 24 : if (forcenonrequired)
2993 : : {
2994 : : /* treating scan's keys as non-required */
2995 : : }
2996 [ - + ]: 24 : else if (subkey->sk_flags & SK_BT_NULLS_FIRST)
2997 : : {
2998 : : /*
2999 : : * Since NULLs are sorted before non-NULLs, we know we have
3000 : : * reached the lower limit of the range of values for this
3001 : : * index attr. On a backward scan, we can stop if this qual
3002 : : * is one of the "must match" subset. However, on a forwards
3003 : : * scan, we must keep going, because we may have initially
3004 : : * positioned to the start of the index.
3005 : : *
3006 : : * All required NULLS FIRST > row members can use NULL tuple
3007 : : * values to end backwards scans, just like with other values.
3008 : : * A qual "WHERE (a, b, c) > (9, 42, 'foo')" can terminate a
3009 : : * backwards scan upon reaching the index's rightmost "a = 9"
3010 : : * tuple whose "b" column contains a NULL (if not sooner).
3011 : : * Since "b" is NULLS FIRST, we can treat its NULLs as "<" 42.
3012 : : */
66 pg@bowt.ie 3013 :UBC 0 : reqflags = SK_BT_REQBKWD;
3014 : :
3015 : : /*
3016 : : * When a most significant required NULLS FIRST < row compare
3017 : : * member sees NULL tuple values during a backwards scan, it
3018 : : * signals the end of matches for the whole row compare/scan.
3019 : : * A qual "WHERE (a, b, c) < (9, 42, 'foo')" will terminate a
3020 : : * backwards scan upon reaching the rightmost tuple whose "a"
3021 : : * column has a NULL. The "a" NULL value is "<" 9, and yet
3022 : : * our < row compare will still end the scan. (This isn't
3023 : : * safe with later/lower-order row members. Notice that it
3024 : : * can only happen with an "a" NULL some time after the scan
3025 : : * completely stops needing to use its "b" and "c" members.)
3026 : : */
3027 [ # # ]: 0 : if (subkey == (ScanKey) DatumGetPointer(skey->sk_argument))
3028 : 0 : reqflags |= SK_BT_REQFWD; /* safe, first row member */
3029 : :
3030 [ # # # # ]: 0 : if ((subkey->sk_flags & reqflags) &&
3031 : : ScanDirectionIsBackward(dir))
5057 tgl@sss.pgh.pa.us 3032 : 0 : *continuescan = false;
3033 : : }
3034 : : else
3035 : : {
3036 : : /*
3037 : : * Since NULLs are sorted after non-NULLs, we know we have
3038 : : * reached the upper limit of the range of values for this
3039 : : * index attr. On a forward scan, we can stop if this qual is
3040 : : * one of the "must match" subset. However, on a backward
3041 : : * scan, we must keep going, because we may have initially
3042 : : * positioned to the end of the index.
3043 : : *
3044 : : * All required NULLS LAST < row members can use NULL tuple
3045 : : * values to end forwards scans, just like with other values.
3046 : : * A qual "WHERE (a, b, c) < (9, 42, 'foo')" can terminate a
3047 : : * forwards scan upon reaching the index's leftmost "a = 9"
3048 : : * tuple whose "b" column contains a NULL (if not sooner).
3049 : : * Since "b" is NULLS LAST, we can treat its NULLs as ">" 42.
3050 : : */
66 pg@bowt.ie 3051 :CBC 24 : reqflags = SK_BT_REQFWD;
3052 : :
3053 : : /*
3054 : : * When a most significant required NULLS LAST > row compare
3055 : : * member sees NULL tuple values during a forwards scan, it
3056 : : * signals the end of matches for the whole row compare/scan.
3057 : : * A qual "WHERE (a, b, c) > (9, 42, 'foo')" will terminate a
3058 : : * forwards scan upon reaching the leftmost tuple whose "a"
3059 : : * column has a NULL. The "a" NULL value is ">" 9, and yet
3060 : : * our > row compare will end the scan. (This isn't safe with
3061 : : * later/lower-order row members. Notice that it can only
3062 : : * happen with an "a" NULL some time after the scan completely
3063 : : * stops needing to use its "b" and "c" members.)
3064 : : */
3065 [ - + ]: 24 : if (subkey == (ScanKey) DatumGetPointer(skey->sk_argument))
66 pg@bowt.ie 3066 :UBC 0 : reqflags |= SK_BT_REQBKWD; /* safe, first row member */
3067 : :
66 pg@bowt.ie 3068 [ - + - - ]:CBC 24 : if ((subkey->sk_flags & reqflags) &&
3069 : : ScanDirectionIsForward(dir))
5057 tgl@sss.pgh.pa.us 3070 :UBC 0 : *continuescan = false;
3071 : : }
3072 : :
3073 : : /*
3074 : : * In any case, this indextuple doesn't match the qual.
3075 : : */
7164 tgl@sss.pgh.pa.us 3076 :CBC 24 : return false;
3077 : : }
3078 : :
3079 : : /* Perform the test --- three-way comparison not bool operator */
5261 3080 : 1314 : cmpresult = DatumGetInt32(FunctionCall2Coll(&subkey->sk_func,
3081 : : subkey->sk_collation,
3082 : : datum,
3083 : : subkey->sk_argument));
3084 : :
6815 3085 [ - + ]: 1314 : if (subkey->sk_flags & SK_BT_DESC)
2528 tgl@sss.pgh.pa.us 3086 [ # # ]:UBC 0 : INVERT_COMPARE_RESULT(cmpresult);
3087 : :
3088 : : /* Done comparing if unequal, else advance to next column */
7164 tgl@sss.pgh.pa.us 3089 [ + + ]:CBC 1314 : if (cmpresult != 0)
3090 : 1194 : break;
3091 : :
3092 [ - + ]: 120 : if (subkey->sk_flags & SK_ROW_END)
7164 tgl@sss.pgh.pa.us 3093 :UBC 0 : break;
7164 tgl@sss.pgh.pa.us 3094 :CBC 120 : subkey++;
3095 : : }
3096 : :
3097 : : /*
3098 : : * At this point cmpresult indicates the overall result of the row
3099 : : * comparison, and subkey points to the deciding column (or the last
3100 : : * column if the result is "=").
3101 : : */
3102 [ + + + + : 1194 : switch (subkey->sk_strategy)
- ]
3103 : : {
3104 : : /* EQ and NE cases aren't allowed here */
3105 : 93 : case BTLessStrategyNumber:
3106 : 93 : result = (cmpresult < 0);
3107 : 93 : break;
3108 : 792 : case BTLessEqualStrategyNumber:
3109 : 792 : result = (cmpresult <= 0);
3110 : 792 : break;
3111 : 123 : case BTGreaterEqualStrategyNumber:
3112 : 123 : result = (cmpresult >= 0);
3113 : 123 : break;
3114 : 186 : case BTGreaterStrategyNumber:
3115 : 186 : result = (cmpresult > 0);
3116 : 186 : break;
7164 tgl@sss.pgh.pa.us 3117 :UBC 0 : default:
283 peter@eisentraut.org 3118 [ # # ]: 0 : elog(ERROR, "unexpected strategy number %d", subkey->sk_strategy);
3119 : : result = 0; /* keep compiler quiet */
3120 : : break;
3121 : : }
3122 : :
87 pg@bowt.ie 3123 [ + + + - ]:CBC 1194 : if (!result && !forcenonrequired)
3124 : : {
3125 : : /*
3126 : : * Tuple fails this qual. If it's a required qual for the current
3127 : : * scan direction, then we can conclude no further tuples will pass,
3128 : : * either. Note we have to look at the deciding column, not
3129 : : * necessarily the first or last column of the row condition.
3130 : : */
7164 tgl@sss.pgh.pa.us 3131 [ + - + - ]: 3 : if ((subkey->sk_flags & SK_BT_REQFWD) &&
3132 : : ScanDirectionIsForward(dir))
3133 : 3 : *continuescan = false;
7164 tgl@sss.pgh.pa.us 3134 [ # # # # ]:UBC 0 : else if ((subkey->sk_flags & SK_BT_REQBKWD) &&
3135 : : ScanDirectionIsBackward(dir))
3136 : 0 : *continuescan = false;
3137 : : }
3138 : :
7164 tgl@sss.pgh.pa.us 3139 :CBC 1194 : return result;
3140 : : }
3141 : :
3142 : : /*
3143 : : * Determine if a scan with array keys should skip over uninteresting tuples.
3144 : : *
3145 : : * This is a subroutine for _bt_checkkeys. Called when _bt_readpage's linear
3146 : : * search process (started after it finishes reading an initial group of
3147 : : * matching tuples, used to locate the start of the next group of tuples
3148 : : * matching the next set of required array keys) has already scanned an
3149 : : * excessive number of tuples whose key space is "between arrays".
3150 : : *
3151 : : * When we perform look ahead successfully, we'll sets pstate.skip, which
3152 : : * instructs _bt_readpage to skip ahead to that tuple next (could be past the
3153 : : * end of the scan's leaf page). Pages where the optimization is effective
3154 : : * will generally still need to skip several times. Each call here performs
3155 : : * only a single "look ahead" comparison of a later tuple, whose distance from
3156 : : * the current tuple's offset number is determined by applying heuristics.
3157 : : */
3158 : : static void
518 pg@bowt.ie 3159 : 5625 : _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate,
3160 : : int tupnatts, TupleDesc tupdesc)
3161 : : {
311 3162 : 5625 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
3163 : 5625 : ScanDirection dir = so->currPos.dir;
3164 : : OffsetNumber aheadoffnum;
3165 : : IndexTuple ahead;
3166 : :
155 3167 [ - + ]: 5625 : Assert(!pstate->forcenonrequired);
3168 : :
3169 : : /* Avoid looking ahead when comparing the page high key */
518 3170 [ - + ]: 5625 : if (pstate->offnum < pstate->minoff)
518 pg@bowt.ie 3171 :UBC 0 : return;
3172 : :
3173 : : /*
3174 : : * Don't look ahead when there aren't enough tuples remaining on the page
3175 : : * (in the current scan direction) for it to be worth our while
3176 : : */
518 pg@bowt.ie 3177 [ + + ]:CBC 5625 : if (ScanDirectionIsForward(dir) &&
3178 [ + + ]: 5586 : pstate->offnum >= pstate->maxoff - LOOK_AHEAD_DEFAULT_DISTANCE)
3179 : 250 : return;
3180 [ + + ]: 5375 : else if (ScanDirectionIsBackward(dir) &&
3181 [ + + ]: 39 : pstate->offnum <= pstate->minoff + LOOK_AHEAD_DEFAULT_DISTANCE)
3182 : 12 : return;
3183 : :
3184 : : /*
3185 : : * The look ahead distance starts small, and ramps up as each call here
3186 : : * allows _bt_readpage to skip over more tuples
3187 : : */
3188 [ + + ]: 5363 : if (!pstate->targetdistance)
3189 : 3209 : pstate->targetdistance = LOOK_AHEAD_DEFAULT_DISTANCE;
376 3190 [ + - ]: 2154 : else if (pstate->targetdistance < MaxIndexTuplesPerPage / 2)
518 3191 : 2154 : pstate->targetdistance *= 2;
3192 : :
3193 : : /* Don't read past the end (or before the start) of the page, though */
3194 [ + + ]: 5363 : if (ScanDirectionIsForward(dir))
3195 : 5336 : aheadoffnum = Min((int) pstate->maxoff,
3196 : : (int) pstate->offnum + pstate->targetdistance);
3197 : : else
3198 : 27 : aheadoffnum = Max((int) pstate->minoff,
3199 : : (int) pstate->offnum - pstate->targetdistance);
3200 : :
3201 : 5363 : ahead = (IndexTuple) PageGetItem(pstate->page,
3202 : 5363 : PageGetItemId(pstate->page, aheadoffnum));
3203 [ + + ]: 5363 : if (_bt_tuple_before_array_skeys(scan, dir, ahead, tupdesc, tupnatts,
3204 : : false, 0, NULL))
3205 : : {
3206 : : /*
3207 : : * Success -- instruct _bt_readpage to skip ahead to very next tuple
3208 : : * after the one we determined was still before the current array keys
3209 : : */
3210 [ + + ]: 1780 : if (ScanDirectionIsForward(dir))
3211 : 1762 : pstate->skip = aheadoffnum + 1;
3212 : : else
3213 : 18 : pstate->skip = aheadoffnum - 1;
3214 : : }
3215 : : else
3216 : : {
3217 : : /*
3218 : : * Failure -- "ahead" tuple is too far ahead (we were too aggressive).
3219 : : *
3220 : : * Reset the number of rechecks, and aggressively reduce the target
3221 : : * distance (we're much more aggressive here than we were when the
3222 : : * distance was initially ramped up).
3223 : : */
3224 : 3583 : pstate->rechecks = 0;
3225 [ + + ]: 3583 : pstate->targetdistance = Max(pstate->targetdistance / 8, 1);
3226 : : }
3227 : : }
3228 : :
3229 : : /*
3230 : : * _bt_killitems - set LP_DEAD state for items an indexscan caller has
3231 : : * told us were killed
3232 : : *
3233 : : * scan->opaque, referenced locally through so, contains information about the
3234 : : * current page and killed tuples thereon (generally, this should only be
3235 : : * called if so->numKilled > 0).
3236 : : *
3237 : : * Caller should not have a lock on the so->currPos page, but must hold a
3238 : : * buffer pin when !so->dropPin. When we return, it still won't be locked.
3239 : : * It'll continue to hold whatever pins were held before calling here.
3240 : : *
3241 : : * We match items by heap TID before assuming they are the right ones to set
3242 : : * LP_DEAD. If the scan is one that holds a buffer pin on the target page
3243 : : * continuously from initially reading the items until applying this function
3244 : : * (if it is a !so->dropPin scan), VACUUM cannot have deleted any items on the
3245 : : * page, so the page's TIDs can't have been recycled by now. There's no risk
3246 : : * that we'll confuse a new index tuple that happens to use a recycled TID
3247 : : * with a now-removed tuple with the same TID (that used to be on this same
3248 : : * page). We can't rely on that during scans that drop buffer pins eagerly
3249 : : * (so->dropPin scans), though, so we must condition setting LP_DEAD bits on
3250 : : * the page LSN having not changed since back when _bt_readpage saw the page.
3251 : : * We totally give up on setting LP_DEAD bits when the page LSN changed.
3252 : : *
3253 : : * We give up much less often during !so->dropPin scans, but it still happens.
3254 : : * We cope with cases where items have moved right due to insertions. If an
3255 : : * item has moved off the current page due to a split, we'll fail to find it
3256 : : * and just give up on it.
3257 : : */
3258 : : void
3818 kgrittn@postgresql.o 3259 : 86642 : _bt_killitems(IndexScanDesc scan)
3260 : : {
92 pg@bowt.ie 3261 : 86642 : Relation rel = scan->indexRelation;
7062 tgl@sss.pgh.pa.us 3262 : 86642 : BTScanOpaque so = (BTScanOpaque) scan->opaque;
3263 : : Page page;
3264 : : BTPageOpaque opaque;
3265 : : OffsetNumber minoff;
3266 : : OffsetNumber maxoff;
3818 kgrittn@postgresql.o 3267 : 86642 : int numKilled = so->numKilled;
7062 tgl@sss.pgh.pa.us 3268 : 86642 : bool killedsomething = false;
3269 : : Buffer buf;
3270 : :
92 pg@bowt.ie 3271 [ - + ]: 86642 : Assert(numKilled > 0);
3818 kgrittn@postgresql.o 3272 [ - + - - : 86642 : Assert(BTScanPosIsValid(so->currPos));
- + ]
92 pg@bowt.ie 3273 [ - + ]: 86642 : Assert(scan->heapRelation != NULL); /* can't be a bitmap index scan */
3274 : :
3275 : : /* Always invalidate so->killedItems[] before leaving so->currPos */
3818 kgrittn@postgresql.o 3276 : 86642 : so->numKilled = 0;
3277 : :
92 pg@bowt.ie 3278 [ + + ]: 86642 : if (!so->dropPin)
3279 : : {
3280 : : /*
3281 : : * We have held the pin on this page since we read the index tuples,
3282 : : * so all we need to do is lock it. The pin will have prevented
3283 : : * concurrent VACUUMs from recycling any of the TIDs on the page.
3284 : : */
3285 [ - + - - : 19622 : Assert(BTScanPosIsPinned(so->currPos));
- + ]
87 3286 : 19622 : buf = so->currPos.buf;
3287 : 19622 : _bt_lockbuf(rel, buf, BT_READ);
3288 : : }
3289 : : else
3290 : : {
3291 : : XLogRecPtr latestlsn;
3292 : :
92 3293 [ - + - - : 67020 : Assert(!BTScanPosIsPinned(so->currPos));
- + ]
3294 [ + - + + : 67020 : Assert(RelationNeedsWAL(rel));
+ - - + ]
3295 : 67020 : buf = _bt_getbuf(rel, so->currPos.currPage, BT_READ);
3296 : :
3297 : 67020 : latestlsn = BufferGetLSNAtomic(buf);
3298 [ - + ]: 67020 : Assert(!XLogRecPtrIsInvalid(so->currPos.lsn));
3299 [ - + ]: 67020 : Assert(so->currPos.lsn <= latestlsn);
3300 [ + + ]: 67020 : if (so->currPos.lsn != latestlsn)
3301 : : {
3302 : : /* Modified, give up on hinting */
3303 : 65 : _bt_relbuf(rel, buf);
3818 kgrittn@postgresql.o 3304 : 65 : return;
3305 : : }
3306 : :
3307 : : /* Unmodified, hinting is safe */
3308 : : }
3309 : :
87 pg@bowt.ie 3310 : 86577 : page = BufferGetPage(buf);
1254 michael@paquier.xyz 3311 : 86577 : opaque = BTPageGetOpaque(page);
7062 tgl@sss.pgh.pa.us 3312 [ + + ]: 86577 : minoff = P_FIRSTDATAKEY(opaque);
3313 : 86577 : maxoff = PageGetMaxOffsetNumber(page);
3314 : :
92 pg@bowt.ie 3315 [ + + ]: 287933 : for (int i = 0; i < numKilled; i++)
3316 : : {
6912 bruce@momjian.us 3317 : 201356 : int itemIndex = so->killedItems[i];
3318 : 201356 : BTScanPosItem *kitem = &so->currPos.items[itemIndex];
3319 : 201356 : OffsetNumber offnum = kitem->indexOffset;
3320 : :
7062 tgl@sss.pgh.pa.us 3321 [ + - - + ]: 201356 : Assert(itemIndex >= so->currPos.firstItem &&
3322 : : itemIndex <= so->currPos.lastItem);
3323 [ - + ]: 201356 : if (offnum < minoff)
7062 tgl@sss.pgh.pa.us 3324 :UBC 0 : continue; /* pure paranoia */
7062 tgl@sss.pgh.pa.us 3325 [ + + ]:CBC 4009542 : while (offnum <= maxoff)
3326 : : {
3327 : 3981167 : ItemId iid = PageGetItemId(page, offnum);
3328 : 3981167 : IndexTuple ituple = (IndexTuple) PageGetItem(page, iid);
2019 pg@bowt.ie 3329 : 3981167 : bool killtuple = false;
3330 : :
3331 [ + + ]: 3981167 : if (BTreeTupleIsPosting(ituple))
3332 : : {
3333 : 1012434 : int pi = i + 1;
3334 : 1012434 : int nposting = BTreeTupleGetNPosting(ituple);
3335 : : int j;
3336 : :
3337 : : /*
3338 : : * We rely on the convention that heap TIDs in the scanpos
3339 : : * items array are stored in ascending heap TID order for a
3340 : : * group of TIDs that originally came from a posting list
3341 : : * tuple. This convention even applies during backwards
3342 : : * scans, where returning the TIDs in descending order might
3343 : : * seem more natural. This is about effectiveness, not
3344 : : * correctness.
3345 : : *
3346 : : * Note that the page may have been modified in almost any way
3347 : : * since we first read it (in the !so->dropPin case), so it's
3348 : : * possible that this posting list tuple wasn't a posting list
3349 : : * tuple when we first encountered its heap TIDs.
3350 : : */
3351 [ + + ]: 1038860 : for (j = 0; j < nposting; j++)
3352 : : {
3353 : 1038070 : ItemPointer item = BTreeTupleGetPostingN(ituple, j);
3354 : :
3355 [ + + ]: 1038070 : if (!ItemPointerEquals(item, &kitem->heapTid))
3356 : 1011644 : break; /* out of posting list loop */
3357 : :
3358 : : /*
3359 : : * kitem must have matching offnum when heap TIDs match,
3360 : : * though only in the common case where the page can't
3361 : : * have been concurrently modified
3362 : : */
92 3363 [ - + - - ]: 26426 : Assert(kitem->indexOffset == offnum || !so->dropPin);
3364 : :
3365 : : /*
3366 : : * Read-ahead to later kitems here.
3367 : : *
3368 : : * We rely on the assumption that not advancing kitem here
3369 : : * will prevent us from considering the posting list tuple
3370 : : * fully dead by not matching its next heap TID in next
3371 : : * loop iteration.
3372 : : *
3373 : : * If, on the other hand, this is the final heap TID in
3374 : : * the posting list tuple, then tuple gets killed
3375 : : * regardless (i.e. we handle the case where the last
3376 : : * kitem is also the last heap TID in the last index tuple
3377 : : * correctly -- posting tuple still gets killed).
3378 : : */
2019 3379 [ + + ]: 26426 : if (pi < numKilled)
3380 : 9286 : kitem = &so->currPos.items[so->killedItems[pi++]];
3381 : : }
3382 : :
3383 : : /*
3384 : : * Don't bother advancing the outermost loop's int iterator to
3385 : : * avoid processing killed items that relate to the same
3386 : : * offnum/posting list tuple. This micro-optimization hardly
3387 : : * seems worth it. (Further iterations of the outermost loop
3388 : : * will fail to match on this same posting list's first heap
3389 : : * TID instead, so we'll advance to the next offnum/index
3390 : : * tuple pretty quickly.)
3391 : : */
3392 [ + + ]: 1012434 : if (j == nposting)
3393 : 790 : killtuple = true;
3394 : : }
3395 [ + + ]: 2968733 : else if (ItemPointerEquals(&ituple->t_tid, &kitem->heapTid))
3396 : 172566 : killtuple = true;
3397 : :
3398 : : /*
3399 : : * Mark index item as dead, if it isn't already. Since this
3400 : : * happens while holding a buffer lock possibly in shared mode,
3401 : : * it's possible that multiple processes attempt to do this
3402 : : * simultaneously, leading to multiple full-page images being sent
3403 : : * to WAL (if wal_log_hints or data checksums are enabled), which
3404 : : * is undesirable.
3405 : : */
1940 alvherre@alvh.no-ip. 3406 [ + + + + ]: 3981167 : if (killtuple && !ItemIdIsDead(iid))
3407 : : {
3408 : : /* found the item/all posting list items */
6569 tgl@sss.pgh.pa.us 3409 : 172981 : ItemIdMarkDead(iid);
7062 3410 : 172981 : killedsomething = true;
3411 : 172981 : break; /* out of inner search loop */
3412 : : }
3413 : 3808186 : offnum = OffsetNumberNext(offnum);
3414 : : }
3415 : : }
3416 : :
3417 : : /*
3418 : : * Since this can be redone later if needed, mark as dirty hint.
3419 : : *
3420 : : * Whenever we mark anything LP_DEAD, we also set the page's
3421 : : * BTP_HAS_GARBAGE flag, which is likewise just a hint. (Note that we
3422 : : * only rely on the page-level flag in !heapkeyspace indexes.)
3423 : : */
3424 [ + + ]: 86577 : if (killedsomething)
3425 : : {
6983 3426 : 68665 : opaque->btpo_flags |= BTP_HAS_GARBAGE;
87 pg@bowt.ie 3427 : 68665 : MarkBufferDirtyHint(buf, true);
3428 : : }
3429 : :
3430 [ + + ]: 86577 : if (!so->dropPin)
3431 : 19622 : _bt_unlockbuf(rel, buf);
3432 : : else
3433 : 66955 : _bt_relbuf(rel, buf);
3434 : : }
3435 : :
3436 : :
3437 : : /*
3438 : : * The following routines manage a shared-memory area in which we track
3439 : : * assignment of "vacuum cycle IDs" to currently-active btree vacuuming
3440 : : * operations. There is a single counter which increments each time we
3441 : : * start a vacuum to assign it a cycle ID. Since multiple vacuums could
3442 : : * be active concurrently, we have to track the cycle ID for each active
3443 : : * vacuum; this requires at most MaxBackends entries (usually far fewer).
3444 : : * We assume at most one vacuum can be active for a given index.
3445 : : *
3446 : : * Access to the shared memory area is controlled by BtreeVacuumLock.
3447 : : * In principle we could use a separate lmgr locktag for each index,
3448 : : * but a single LWLock is much cheaper, and given the short time that
3449 : : * the lock is ever held, the concurrency hit should be minimal.
3450 : : */
3451 : :
3452 : : typedef struct BTOneVacInfo
3453 : : {
3454 : : LockRelId relid; /* global identifier of an index */
3455 : : BTCycleId cycleid; /* cycle ID for its active VACUUM */
3456 : : } BTOneVacInfo;
3457 : :
3458 : : typedef struct BTVacInfo
3459 : : {
3460 : : BTCycleId cycle_ctr; /* cycle ID most recently assigned */
3461 : : int num_vacuums; /* number of currently active VACUUMs */
3462 : : int max_vacuums; /* allocated length of vacuums[] array */
3463 : : BTOneVacInfo vacuums[FLEXIBLE_ARRAY_MEMBER];
3464 : : } BTVacInfo;
3465 : :
3466 : : static BTVacInfo *btvacinfo;
3467 : :
3468 : :
3469 : : /*
3470 : : * _bt_vacuum_cycleid --- get the active vacuum cycle ID for an index,
3471 : : * or zero if there is no active VACUUM
3472 : : *
3473 : : * Note: for correct interlocking, the caller must already hold pin and
3474 : : * exclusive lock on each buffer it will store the cycle ID into. This
3475 : : * ensures that even if a VACUUM starts immediately afterwards, it cannot
3476 : : * process those pages until the page split is complete.
3477 : : */
3478 : : BTCycleId
7061 tgl@sss.pgh.pa.us 3479 : 11436 : _bt_vacuum_cycleid(Relation rel)
3480 : : {
3481 : 11436 : BTCycleId result = 0;
3482 : : int i;
3483 : :
3484 : : /* Share lock is enough since this is a read-only operation */
3485 : 11436 : LWLockAcquire(BtreeVacuumLock, LW_SHARED);
3486 : :
3487 [ + + ]: 11445 : for (i = 0; i < btvacinfo->num_vacuums; i++)
3488 : : {
3489 : 10 : BTOneVacInfo *vac = &btvacinfo->vacuums[i];
3490 : :
3491 [ + + ]: 10 : if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
7061 tgl@sss.pgh.pa.us 3492 [ + - ]:GBC 1 : vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
3493 : : {
3494 : 1 : result = vac->cycleid;
3495 : 1 : break;
3496 : : }
3497 : : }
3498 : :
7061 tgl@sss.pgh.pa.us 3499 :CBC 11436 : LWLockRelease(BtreeVacuumLock);
3500 : 11436 : return result;
3501 : : }
3502 : :
3503 : : /*
3504 : : * _bt_start_vacuum --- assign a cycle ID to a just-starting VACUUM operation
3505 : : *
3506 : : * Note: the caller must guarantee that it will eventually call
3507 : : * _bt_end_vacuum, else we'll permanently leak an array slot. To ensure
3508 : : * that this happens even in elog(FATAL) scenarios, the appropriate coding
3509 : : * is not just a PG_TRY, but
3510 : : * PG_ENSURE_ERROR_CLEANUP(_bt_end_vacuum_callback, PointerGetDatum(rel))
3511 : : */
3512 : : BTCycleId
3513 : 1521 : _bt_start_vacuum(Relation rel)
3514 : : {
3515 : : BTCycleId result;
3516 : : int i;
3517 : : BTOneVacInfo *vac;
3518 : :
3519 : 1521 : LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
3520 : :
3521 : : /*
3522 : : * Assign the next cycle ID, being careful to avoid zero as well as the
3523 : : * reserved high values.
3524 : : */
6725 3525 : 1521 : result = ++(btvacinfo->cycle_ctr);
3526 [ + - - + ]: 1521 : if (result == 0 || result > MAX_BT_CYCLE_ID)
6725 tgl@sss.pgh.pa.us 3527 :UBC 0 : result = btvacinfo->cycle_ctr = 1;
3528 : :
3529 : : /* Let's just make sure there's no entry already for this index */
7061 tgl@sss.pgh.pa.us 3530 [ - + ]:CBC 1521 : for (i = 0; i < btvacinfo->num_vacuums; i++)
3531 : : {
7061 tgl@sss.pgh.pa.us 3532 :UBC 0 : vac = &btvacinfo->vacuums[i];
3533 [ # # ]: 0 : if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
3534 [ # # ]: 0 : vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
3535 : : {
3536 : : /*
3537 : : * Unlike most places in the backend, we have to explicitly
3538 : : * release our LWLock before throwing an error. This is because
3539 : : * we expect _bt_end_vacuum() to be called before transaction
3540 : : * abort cleanup can run to release LWLocks.
3541 : : */
6735 3542 : 0 : LWLockRelease(BtreeVacuumLock);
7061 3543 [ # # ]: 0 : elog(ERROR, "multiple active vacuums for index \"%s\"",
3544 : : RelationGetRelationName(rel));
3545 : : }
3546 : : }
3547 : :
3548 : : /* OK, add an entry */
7061 tgl@sss.pgh.pa.us 3549 [ - + ]:CBC 1521 : if (btvacinfo->num_vacuums >= btvacinfo->max_vacuums)
3550 : : {
6735 tgl@sss.pgh.pa.us 3551 :UBC 0 : LWLockRelease(BtreeVacuumLock);
7061 3552 [ # # ]: 0 : elog(ERROR, "out of btvacinfo slots");
3553 : : }
7061 tgl@sss.pgh.pa.us 3554 :CBC 1521 : vac = &btvacinfo->vacuums[btvacinfo->num_vacuums];
3555 : 1521 : vac->relid = rel->rd_lockInfo.lockRelId;
3556 : 1521 : vac->cycleid = result;
3557 : 1521 : btvacinfo->num_vacuums++;
3558 : :
3559 : 1521 : LWLockRelease(BtreeVacuumLock);
3560 : 1521 : return result;
3561 : : }
3562 : :
3563 : : /*
3564 : : * _bt_end_vacuum --- mark a btree VACUUM operation as done
3565 : : *
3566 : : * Note: this is deliberately coded not to complain if no entry is found;
3567 : : * this allows the caller to put PG_TRY around the start_vacuum operation.
3568 : : */
3569 : : void
3570 : 1521 : _bt_end_vacuum(Relation rel)
3571 : : {
3572 : : int i;
3573 : :
3574 : 1521 : LWLockAcquire(BtreeVacuumLock, LW_EXCLUSIVE);
3575 : :
3576 : : /* Find the array entry */
3577 [ + - ]: 1521 : for (i = 0; i < btvacinfo->num_vacuums; i++)
3578 : : {
3579 : 1521 : BTOneVacInfo *vac = &btvacinfo->vacuums[i];
3580 : :
3581 [ + - ]: 1521 : if (vac->relid.relId == rel->rd_lockInfo.lockRelId.relId &&
3582 [ + - ]: 1521 : vac->relid.dbId == rel->rd_lockInfo.lockRelId.dbId)
3583 : : {
3584 : : /* Remove it by shifting down the last entry */
3585 : 1521 : *vac = btvacinfo->vacuums[btvacinfo->num_vacuums - 1];
3586 : 1521 : btvacinfo->num_vacuums--;
3587 : 1521 : break;
3588 : : }
3589 : : }
3590 : :
3591 : 1521 : LWLockRelease(BtreeVacuumLock);
3592 : 1521 : }
3593 : :
3594 : : /*
3595 : : * _bt_end_vacuum wrapped as an on_shmem_exit callback function
3596 : : */
3597 : : void
6352 tgl@sss.pgh.pa.us 3598 :UBC 0 : _bt_end_vacuum_callback(int code, Datum arg)
3599 : : {
3600 : 0 : _bt_end_vacuum((Relation) DatumGetPointer(arg));
3601 : 0 : }
3602 : :
3603 : : /*
3604 : : * BTreeShmemSize --- report amount of shared memory space needed
3605 : : */
3606 : : Size
7061 tgl@sss.pgh.pa.us 3607 :CBC 2938 : BTreeShmemSize(void)
3608 : : {
3609 : : Size size;
3610 : :
3851 3611 : 2938 : size = offsetof(BTVacInfo, vacuums);
1243 rhaas@postgresql.org 3612 : 2938 : size = add_size(size, mul_size(MaxBackends, sizeof(BTOneVacInfo)));
7061 tgl@sss.pgh.pa.us 3613 : 2938 : return size;
3614 : : }
3615 : :
3616 : : /*
3617 : : * BTreeShmemInit --- initialize this module's shared memory
3618 : : */
3619 : : void
3620 : 1029 : BTreeShmemInit(void)
3621 : : {
3622 : : bool found;
3623 : :
3624 : 1029 : btvacinfo = (BTVacInfo *) ShmemInitStruct("BTree Vacuum State",
3625 : : BTreeShmemSize(),
3626 : : &found);
3627 : :
3628 [ + - ]: 1029 : if (!IsUnderPostmaster)
3629 : : {
3630 : : /* Initialize shared memory area */
3631 [ - + ]: 1029 : Assert(!found);
3632 : :
3633 : : /*
3634 : : * It doesn't really matter what the cycle counter starts at, but
3635 : : * having it always start the same doesn't seem good. Seed with
3636 : : * low-order bits of time() instead.
3637 : : */
3638 : 1029 : btvacinfo->cycle_ctr = (BTCycleId) time(NULL);
3639 : :
3640 : 1029 : btvacinfo->num_vacuums = 0;
1243 rhaas@postgresql.org 3641 : 1029 : btvacinfo->max_vacuums = MaxBackends;
3642 : : }
3643 : : else
7061 tgl@sss.pgh.pa.us 3644 [ # # ]:UBC 0 : Assert(found);
7061 tgl@sss.pgh.pa.us 3645 :CBC 1029 : }
3646 : :
3647 : : bytea *
3520 3648 : 165 : btoptions(Datum reloptions, bool validate)
3649 : : {
3650 : : static const relopt_parse_elt tab[] = {
3651 : : {"fillfactor", RELOPT_TYPE_INT, offsetof(BTOptions, fillfactor)},
3652 : : {"vacuum_cleanup_index_scale_factor", RELOPT_TYPE_REAL,
3653 : : offsetof(BTOptions, vacuum_cleanup_index_scale_factor)},
3654 : : {"deduplicate_items", RELOPT_TYPE_BOOL,
3655 : : offsetof(BTOptions, deduplicate_items)}
3656 : : };
3657 : :
2112 michael@paquier.xyz 3658 : 165 : return (bytea *) build_reloptions(reloptions, validate,
3659 : : RELOPT_KIND_BTREE,
3660 : : sizeof(BTOptions),
3661 : : tab, lengthof(tab));
3662 : : }
3663 : :
3664 : : /*
3665 : : * btproperty() -- Check boolean properties of indexes.
3666 : : *
3667 : : * This is optional, but handling AMPROP_RETURNABLE here saves opening the rel
3668 : : * to call btcanreturn.
3669 : : */
3670 : : bool
3311 tgl@sss.pgh.pa.us 3671 : 378 : btproperty(Oid index_oid, int attno,
3672 : : IndexAMProperty prop, const char *propname,
3673 : : bool *res, bool *isnull)
3674 : : {
3675 [ + + ]: 378 : switch (prop)
3676 : : {
3677 : 21 : case AMPROP_RETURNABLE:
3678 : : /* answer only for columns, not AM or whole index */
3679 [ + + ]: 21 : if (attno == 0)
3680 : 6 : return false;
3681 : : /* otherwise, btree can always return data */
3682 : 15 : *res = true;
3683 : 15 : return true;
3684 : :
3685 : 357 : default:
3686 : 357 : return false; /* punt to generic code */
3687 : : }
3688 : : }
3689 : :
3690 : : /*
3691 : : * btbuildphasename() -- Return name of index build phase.
3692 : : */
3693 : : char *
2349 alvherre@alvh.no-ip. 3694 :UBC 0 : btbuildphasename(int64 phasenum)
3695 : : {
3696 [ # # # # : 0 : switch (phasenum)
# # ]
3697 : : {
3698 : 0 : case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE:
3699 : 0 : return "initializing";
3700 : 0 : case PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN:
3701 : 0 : return "scanning table";
3702 : 0 : case PROGRESS_BTREE_PHASE_PERFORMSORT_1:
3703 : 0 : return "sorting live tuples";
3704 : 0 : case PROGRESS_BTREE_PHASE_PERFORMSORT_2:
3705 : 0 : return "sorting dead tuples";
3706 : 0 : case PROGRESS_BTREE_PHASE_LEAF_LOAD:
3707 : 0 : return "loading tuples in tree";
3708 : 0 : default:
3709 : 0 : return NULL;
3710 : : }
3711 : : }
3712 : :
3713 : : /*
3714 : : * _bt_truncate() -- create tuple without unneeded suffix attributes.
3715 : : *
3716 : : * Returns truncated pivot index tuple allocated in caller's memory context,
3717 : : * with key attributes copied from caller's firstright argument. If rel is
3718 : : * an INCLUDE index, non-key attributes will definitely be truncated away,
3719 : : * since they're not part of the key space. More aggressive suffix
3720 : : * truncation can take place when it's clear that the returned tuple does not
3721 : : * need one or more suffix key attributes. We only need to keep firstright
3722 : : * attributes up to and including the first non-lastleft-equal attribute.
3723 : : * Caller's insertion scankey is used to compare the tuples; the scankey's
3724 : : * argument values are not considered here.
3725 : : *
3726 : : * Note that returned tuple's t_tid offset will hold the number of attributes
3727 : : * present, so the original item pointer offset is not represented. Caller
3728 : : * should only change truncated tuple's downlink. Note also that truncated
3729 : : * key attributes are treated as containing "minus infinity" values by
3730 : : * _bt_compare().
3731 : : *
3732 : : * In the worst case (when a heap TID must be appended to distinguish lastleft
3733 : : * from firstright), the size of the returned tuple is the size of firstright
3734 : : * plus the size of an additional MAXALIGN()'d item pointer. This guarantee
3735 : : * is important, since callers need to stay under the 1/3 of a page
3736 : : * restriction on tuple size. If this routine is ever taught to truncate
3737 : : * within an attribute/datum, it will need to avoid returning an enlarged
3738 : : * tuple to caller when truncation + TOAST compression ends up enlarging the
3739 : : * final datum.
3740 : : */
3741 : : IndexTuple
2362 pg@bowt.ie 3742 :CBC 31252 : _bt_truncate(Relation rel, IndexTuple lastleft, IndexTuple firstright,
3743 : : BTScanInsert itup_key)
3744 : : {
3745 : 31252 : TupleDesc itupdesc = RelationGetDescr(rel);
3746 : 31252 : int16 nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
3747 : : int keepnatts;
3748 : : IndexTuple pivot;
3749 : : IndexTuple tidpivot;
3750 : : ItemPointer pivotheaptid;
3751 : : Size newsize;
3752 : :
3753 : : /*
3754 : : * We should only ever truncate non-pivot tuples from leaf pages. It's
3755 : : * never okay to truncate when splitting an internal page.
3756 : : */
2019 3757 [ + - - + ]: 31252 : Assert(!BTreeTupleIsPivot(lastleft) && !BTreeTupleIsPivot(firstright));
3758 : :
3759 : : /* Determine how many attributes must be kept in truncated tuple */
2362 3760 : 31252 : keepnatts = _bt_keep_natts(rel, lastleft, firstright, itup_key);
3761 : :
3762 : : #ifdef DEBUG_NO_TRUNCATE
3763 : : /* Force truncation to be ineffective for testing purposes */
3764 : : keepnatts = nkeyatts + 1;
3765 : : #endif
3766 : :
1986 3767 : 31252 : pivot = index_truncate_tuple(itupdesc, firstright,
3768 : : Min(keepnatts, nkeyatts));
3769 : :
3770 [ + + ]: 31252 : if (BTreeTupleIsPosting(pivot))
3771 : : {
3772 : : /*
3773 : : * index_truncate_tuple() just returns a straight copy of firstright
3774 : : * when it has no attributes to truncate. When that happens, we may
3775 : : * need to truncate away a posting list here instead.
3776 : : */
3777 [ + + - + ]: 602 : Assert(keepnatts == nkeyatts || keepnatts == nkeyatts + 1);
3778 [ - + ]: 602 : Assert(IndexRelationGetNumberOfAttributes(rel) == nkeyatts);
3779 : 602 : pivot->t_info &= ~INDEX_SIZE_MASK;
3780 : 602 : pivot->t_info |= MAXALIGN(BTreeTupleGetPostingOffset(firstright));
3781 : : }
3782 : :
3783 : : /*
3784 : : * If there is a distinguishing key attribute within pivot tuple, we're
3785 : : * done
3786 : : */
3787 [ + + ]: 31252 : if (keepnatts <= nkeyatts)
3788 : : {
1978 3789 : 30705 : BTreeTupleSetNAtts(pivot, keepnatts, false);
1986 3790 : 30705 : return pivot;
3791 : : }
3792 : :
3793 : : /*
3794 : : * We have to store a heap TID in the new pivot tuple, since no non-TID
3795 : : * key attribute value in firstright distinguishes the right side of the
3796 : : * split from the left side. nbtree conceptualizes this case as an
3797 : : * inability to truncate away any key attributes, since heap TID is
3798 : : * treated as just another key attribute (despite lacking a pg_attribute
3799 : : * entry).
3800 : : *
3801 : : * Use enlarged space that holds a copy of pivot. We need the extra space
3802 : : * to store a heap TID at the end (using the special pivot tuple
3803 : : * representation). Note that the original pivot already has firstright's
3804 : : * possible posting list/non-key attribute values removed at this point.
3805 : : */
3806 : 547 : newsize = MAXALIGN(IndexTupleSize(pivot)) + MAXALIGN(sizeof(ItemPointerData));
3807 : 547 : tidpivot = palloc0(newsize);
3808 : 547 : memcpy(tidpivot, pivot, MAXALIGN(IndexTupleSize(pivot)));
3809 : : /* Cannot leak memory here */
3810 : 547 : pfree(pivot);
3811 : :
3812 : : /*
3813 : : * Store all of firstright's key attribute values plus a tiebreaker heap
3814 : : * TID value in enlarged pivot tuple
3815 : : */
3816 : 547 : tidpivot->t_info &= ~INDEX_SIZE_MASK;
3817 : 547 : tidpivot->t_info |= newsize;
1978 3818 : 547 : BTreeTupleSetNAtts(tidpivot, nkeyatts, true);
1986 3819 : 547 : pivotheaptid = BTreeTupleGetHeapTID(tidpivot);
3820 : :
3821 : : /*
3822 : : * Lehman & Yao use lastleft as the leaf high key in all cases, but don't
3823 : : * consider suffix truncation. It seems like a good idea to follow that
3824 : : * example in cases where no truncation takes place -- use lastleft's heap
3825 : : * TID. (This is also the closest value to negative infinity that's
3826 : : * legally usable.)
3827 : : */
2019 3828 : 547 : ItemPointerCopy(BTreeTupleGetMaxHeapTID(lastleft), pivotheaptid);
3829 : :
3830 : : /*
3831 : : * We're done. Assert() that heap TID invariants hold before returning.
3832 : : *
3833 : : * Lehman and Yao require that the downlink to the right page, which is to
3834 : : * be inserted into the parent page in the second phase of a page split be
3835 : : * a strict lower bound on items on the right page, and a non-strict upper
3836 : : * bound for items on the left page. Assert that heap TIDs follow these
3837 : : * invariants, since a heap TID value is apparently needed as a
3838 : : * tiebreaker.
3839 : : */
3840 : : #ifndef DEBUG_NO_TRUNCATE
3841 [ - + ]: 547 : Assert(ItemPointerCompare(BTreeTupleGetMaxHeapTID(lastleft),
3842 : : BTreeTupleGetHeapTID(firstright)) < 0);
3843 [ - + ]: 547 : Assert(ItemPointerCompare(pivotheaptid,
3844 : : BTreeTupleGetHeapTID(lastleft)) >= 0);
3845 [ - + ]: 547 : Assert(ItemPointerCompare(pivotheaptid,
3846 : : BTreeTupleGetHeapTID(firstright)) < 0);
3847 : : #else
3848 : :
3849 : : /*
3850 : : * Those invariants aren't guaranteed to hold for lastleft + firstright
3851 : : * heap TID attribute values when they're considered here only because
3852 : : * DEBUG_NO_TRUNCATE is defined (a heap TID is probably not actually
3853 : : * needed as a tiebreaker). DEBUG_NO_TRUNCATE must therefore use a heap
3854 : : * TID value that always works as a strict lower bound for items to the
3855 : : * right. In particular, it must avoid using firstright's leading key
3856 : : * attribute values along with lastleft's heap TID value when lastleft's
3857 : : * TID happens to be greater than firstright's TID.
3858 : : */
3859 : : ItemPointerCopy(BTreeTupleGetHeapTID(firstright), pivotheaptid);
3860 : :
3861 : : /*
3862 : : * Pivot heap TID should never be fully equal to firstright. Note that
3863 : : * the pivot heap TID will still end up equal to lastleft's heap TID when
3864 : : * that's the only usable value.
3865 : : */
3866 : : ItemPointerSetOffsetNumber(pivotheaptid,
3867 : : OffsetNumberPrev(ItemPointerGetOffsetNumber(pivotheaptid)));
3868 : : Assert(ItemPointerCompare(pivotheaptid,
3869 : : BTreeTupleGetHeapTID(firstright)) < 0);
3870 : : #endif
3871 : :
1986 3872 : 547 : return tidpivot;
3873 : : }
3874 : :
3875 : : /*
3876 : : * _bt_keep_natts - how many key attributes to keep when truncating.
3877 : : *
3878 : : * Caller provides two tuples that enclose a split point. Caller's insertion
3879 : : * scankey is used to compare the tuples; the scankey's argument values are
3880 : : * not considered here.
3881 : : *
3882 : : * This can return a number of attributes that is one greater than the
3883 : : * number of key attributes for the index relation. This indicates that the
3884 : : * caller must use a heap TID as a unique-ifier in new pivot tuple.
3885 : : */
3886 : : static int
2362 3887 : 31252 : _bt_keep_natts(Relation rel, IndexTuple lastleft, IndexTuple firstright,
3888 : : BTScanInsert itup_key)
3889 : : {
3890 : 31252 : int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
3891 : 31252 : TupleDesc itupdesc = RelationGetDescr(rel);
3892 : : int keepnatts;
3893 : : ScanKey scankey;
3894 : :
3895 : : /*
3896 : : * _bt_compare() treats truncated key attributes as having the value minus
3897 : : * infinity, which would break searches within !heapkeyspace indexes. We
3898 : : * must still truncate away non-key attribute values, though.
3899 : : */
3900 [ - + ]: 31252 : if (!itup_key->heapkeyspace)
2362 pg@bowt.ie 3901 :UBC 0 : return nkeyatts;
3902 : :
2362 pg@bowt.ie 3903 :CBC 31252 : scankey = itup_key->scankeys;
3904 : 31252 : keepnatts = 1;
3905 [ + + ]: 37672 : for (int attnum = 1; attnum <= nkeyatts; attnum++, scankey++)
3906 : : {
3907 : : Datum datum1,
3908 : : datum2;
3909 : : bool isNull1,
3910 : : isNull2;
3911 : :
3912 : 37125 : datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
3913 : 37125 : datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
3914 : :
3915 [ - + ]: 37125 : if (isNull1 != isNull2)
3916 : 30705 : break;
3917 : :
3918 [ + + + + ]: 74235 : if (!isNull1 &&
3919 : 37110 : DatumGetInt32(FunctionCall2Coll(&scankey->sk_func,
3920 : : scankey->sk_collation,
3921 : : datum1,
3922 : : datum2)) != 0)
3923 : 30705 : break;
3924 : :
3925 : 6420 : keepnatts++;
3926 : : }
3927 : :
3928 : : /*
3929 : : * Assert that _bt_keep_natts_fast() agrees with us in passing. This is
3930 : : * expected in an allequalimage index.
3931 : : */
2019 3932 [ + + - + ]: 31252 : Assert(!itup_key->allequalimage ||
3933 : : keepnatts == _bt_keep_natts_fast(rel, lastleft, firstright));
3934 : :
2362 3935 : 31252 : return keepnatts;
3936 : : }
3937 : :
3938 : : /*
3939 : : * _bt_keep_natts_fast - fast bitwise variant of _bt_keep_natts.
3940 : : *
3941 : : * This is exported so that a candidate split point can have its effect on
3942 : : * suffix truncation inexpensively evaluated ahead of time when finding a
3943 : : * split location. A naive bitwise approach to datum comparisons is used to
3944 : : * save cycles.
3945 : : *
3946 : : * The approach taken here usually provides the same answer as _bt_keep_natts
3947 : : * will (for the same pair of tuples from a heapkeyspace index), since the
3948 : : * majority of btree opclasses can never indicate that two datums are equal
3949 : : * unless they're bitwise equal after detoasting. When an index only has
3950 : : * "equal image" columns, routine is guaranteed to give the same result as
3951 : : * _bt_keep_natts would.
3952 : : *
3953 : : * Callers can rely on the fact that attributes considered equal here are
3954 : : * definitely also equal according to _bt_keep_natts, even when the index uses
3955 : : * an opclass or collation that is not "allequalimage"/deduplication-safe.
3956 : : * This weaker guarantee is good enough for nbtsplitloc.c caller, since false
3957 : : * negatives generally only have the effect of making leaf page splits use a
3958 : : * more balanced split point.
3959 : : */
3960 : : int
3961 : 6605521 : _bt_keep_natts_fast(Relation rel, IndexTuple lastleft, IndexTuple firstright)
3962 : : {
3963 : 6605521 : TupleDesc itupdesc = RelationGetDescr(rel);
3964 : 6605521 : int keysz = IndexRelationGetNumberOfKeyAttributes(rel);
3965 : : int keepnatts;
3966 : :
3967 : 6605521 : keepnatts = 1;
3968 [ + + ]: 11053249 : for (int attnum = 1; attnum <= keysz; attnum++)
3969 : : {
3970 : : Datum datum1,
3971 : : datum2;
3972 : : bool isNull1,
3973 : : isNull2;
3974 : : CompactAttribute *att;
3975 : :
3976 : 9881832 : datum1 = index_getattr(lastleft, attnum, itupdesc, &isNull1);
3977 : 9881832 : datum2 = index_getattr(firstright, attnum, itupdesc, &isNull2);
260 drowley@postgresql.o 3978 : 9881832 : att = TupleDescCompactAttr(itupdesc, attnum - 1);
3979 : :
2362 pg@bowt.ie 3980 [ + + ]: 9881832 : if (isNull1 != isNull2)
3981 : 5434104 : break;
3982 : :
3983 [ + + ]: 9881730 : if (!isNull1 &&
2125 3984 [ + + ]: 9858187 : !datum_image_eq(datum1, datum2, att->attbyval, att->attlen))
2362 3985 : 5434002 : break;
3986 : :
3987 : 4447728 : keepnatts++;
3988 : : }
3989 : :
3990 : 6605521 : return keepnatts;
3991 : : }
3992 : :
3993 : : /*
3994 : : * _bt_check_natts() -- Verify tuple has expected number of attributes.
3995 : : *
3996 : : * Returns value indicating if the expected number of attributes were found
3997 : : * for a particular offset on page. This can be used as a general purpose
3998 : : * sanity check.
3999 : : *
4000 : : * Testing a tuple directly with BTreeTupleGetNAtts() should generally be
4001 : : * preferred to calling here. That's usually more convenient, and is always
4002 : : * more explicit. Call here instead when offnum's tuple may be a negative
4003 : : * infinity tuple that uses the pre-v11 on-disk representation, or when a low
4004 : : * context check is appropriate. This routine is as strict as possible about
4005 : : * what is expected on each version of btree.
4006 : : */
4007 : : bool
4008 : 130758024 : _bt_check_natts(Relation rel, bool heapkeyspace, Page page, OffsetNumber offnum)
4009 : : {
2690 tgl@sss.pgh.pa.us 4010 : 130758024 : int16 natts = IndexRelationGetNumberOfAttributes(rel);
4011 : 130758024 : int16 nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
1254 michael@paquier.xyz 4012 : 130758024 : BTPageOpaque opaque = BTPageGetOpaque(page);
4013 : : IndexTuple itup;
4014 : : int tupnatts;
4015 : :
4016 : : /*
4017 : : * We cannot reliably test a deleted or half-dead page, since they have
4018 : : * dummy high keys
4019 : : */
2697 teodor@sigaev.ru 4020 [ - + ]: 130758024 : if (P_IGNORE(opaque))
2697 teodor@sigaev.ru 4021 :UBC 0 : return true;
4022 : :
2697 teodor@sigaev.ru 4023 [ + - - + ]:CBC 130758024 : Assert(offnum >= FirstOffsetNumber &&
4024 : : offnum <= PageGetMaxOffsetNumber(page));
4025 : :
4026 : 130758024 : itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum));
2362 pg@bowt.ie 4027 [ + + ]: 130758024 : tupnatts = BTreeTupleGetNAtts(itup, rel);
4028 : :
4029 : : /* !heapkeyspace indexes do not support deduplication */
2019 4030 [ - + - - ]: 130758024 : if (!heapkeyspace && BTreeTupleIsPosting(itup))
2019 pg@bowt.ie 4031 :UBC 0 : return false;
4032 : :
4033 : : /* Posting list tuples should never have "pivot heap TID" bit set */
2019 pg@bowt.ie 4034 [ + + ]:CBC 130758024 : if (BTreeTupleIsPosting(itup) &&
4035 [ - + ]: 1578485 : (ItemPointerGetOffsetNumberNoCheck(&itup->t_tid) &
4036 : : BT_PIVOT_HEAP_TID_ATTR) != 0)
2019 pg@bowt.ie 4037 :UBC 0 : return false;
4038 : :
4039 : : /* INCLUDE indexes do not support deduplication */
2019 pg@bowt.ie 4040 [ + + - + ]:CBC 130758024 : if (natts != nkeyatts && BTreeTupleIsPosting(itup))
2019 pg@bowt.ie 4041 :UBC 0 : return false;
4042 : :
2697 teodor@sigaev.ru 4043 [ + + ]:CBC 130758024 : if (P_ISLEAF(opaque))
4044 : : {
4045 [ + + + + ]: 96282271 : if (offnum >= P_FIRSTDATAKEY(opaque))
4046 : : {
4047 : : /*
4048 : : * Non-pivot tuple should never be explicitly marked as a pivot
4049 : : * tuple
4050 : : */
2019 pg@bowt.ie 4051 [ - + ]: 88581868 : if (BTreeTupleIsPivot(itup))
2362 pg@bowt.ie 4052 :UBC 0 : return false;
4053 : :
4054 : : /*
4055 : : * Leaf tuples that are not the page high key (non-pivot tuples)
4056 : : * should never be truncated. (Note that tupnatts must have been
4057 : : * inferred, even with a posting list tuple, because only pivot
4058 : : * tuples store tupnatts directly.)
4059 : : */
2362 pg@bowt.ie 4060 :CBC 88581868 : return tupnatts == natts;
4061 : : }
4062 : : else
4063 : : {
4064 : : /*
4065 : : * Rightmost page doesn't contain a page high key, so tuple was
4066 : : * checked above as ordinary leaf tuple
4067 : : */
2697 teodor@sigaev.ru 4068 [ - + ]: 7700403 : Assert(!P_RIGHTMOST(opaque));
4069 : :
4070 : : /*
4071 : : * !heapkeyspace high key tuple contains only key attributes. Note
4072 : : * that tupnatts will only have been explicitly represented in
4073 : : * !heapkeyspace indexes that happen to have non-key attributes.
4074 : : */
2362 pg@bowt.ie 4075 [ - + ]: 7700403 : if (!heapkeyspace)
2362 pg@bowt.ie 4076 :UBC 0 : return tupnatts == nkeyatts;
4077 : :
4078 : : /* Use generic heapkeyspace pivot tuple handling */
4079 : : }
4080 : : }
4081 : : else /* !P_ISLEAF(opaque) */
4082 : : {
2697 teodor@sigaev.ru 4083 [ + + + + ]:CBC 34475753 : if (offnum == P_FIRSTDATAKEY(opaque))
4084 : : {
4085 : : /*
4086 : : * The first tuple on any internal page (possibly the first after
4087 : : * its high key) is its negative infinity tuple. Negative
4088 : : * infinity tuples are always truncated to zero attributes. They
4089 : : * are a particular kind of pivot tuple.
4090 : : */
2362 pg@bowt.ie 4091 [ + - ]: 1482464 : if (heapkeyspace)
4092 : 1482464 : return tupnatts == 0;
4093 : :
4094 : : /*
4095 : : * The number of attributes won't be explicitly represented if the
4096 : : * negative infinity tuple was generated during a page split that
4097 : : * occurred with a version of Postgres before v11. There must be
4098 : : * a problem when there is an explicit representation that is
4099 : : * non-zero, or when there is no explicit representation and the
4100 : : * tuple is evidently not a pre-pg_upgrade tuple.
4101 : : *
4102 : : * Prior to v11, downlinks always had P_HIKEY as their offset.
4103 : : * Accept that as an alternative indication of a valid
4104 : : * !heapkeyspace negative infinity tuple.
4105 : : */
2362 pg@bowt.ie 4106 [ # # # # ]:UBC 0 : return tupnatts == 0 ||
2019 4107 : 0 : ItemPointerGetOffsetNumber(&(itup->t_tid)) == P_HIKEY;
4108 : : }
4109 : : else
4110 : : {
4111 : : /*
4112 : : * !heapkeyspace downlink tuple with separator key contains only
4113 : : * key attributes. Note that tupnatts will only have been
4114 : : * explicitly represented in !heapkeyspace indexes that happen to
4115 : : * have non-key attributes.
4116 : : */
2362 pg@bowt.ie 4117 [ - + ]:CBC 32993289 : if (!heapkeyspace)
2362 pg@bowt.ie 4118 :UBC 0 : return tupnatts == nkeyatts;
4119 : :
4120 : : /* Use generic heapkeyspace pivot tuple handling */
4121 : : }
4122 : : }
4123 : :
4124 : : /* Handle heapkeyspace pivot tuples (excluding minus infinity items) */
2362 pg@bowt.ie 4125 [ - + ]:CBC 40693692 : Assert(heapkeyspace);
4126 : :
4127 : : /*
4128 : : * Explicit representation of the number of attributes is mandatory with
4129 : : * heapkeyspace index pivot tuples, regardless of whether or not there are
4130 : : * non-key attributes.
4131 : : */
2019 4132 [ - + ]: 40693692 : if (!BTreeTupleIsPivot(itup))
2019 pg@bowt.ie 4133 :UBC 0 : return false;
4134 : :
4135 : : /* Pivot tuple should not use posting list representation (redundant) */
2019 pg@bowt.ie 4136 [ - + ]:CBC 40693692 : if (BTreeTupleIsPosting(itup))
2362 pg@bowt.ie 4137 :UBC 0 : return false;
4138 : :
4139 : : /*
4140 : : * Heap TID is a tiebreaker key attribute, so it cannot be untruncated
4141 : : * when any other key attribute is truncated
4142 : : */
2362 pg@bowt.ie 4143 [ + + - + ]:CBC 40693692 : if (BTreeTupleGetHeapTID(itup) != NULL && tupnatts != nkeyatts)
2362 pg@bowt.ie 4144 :UBC 0 : return false;
4145 : :
4146 : : /*
4147 : : * Pivot tuple must have at least one untruncated key attribute (minus
4148 : : * infinity pivot tuples are the only exception). Pivot tuples can never
4149 : : * represent that there is a value present for a key attribute that
4150 : : * exceeds pg_index.indnkeyatts for the index.
4151 : : */
2362 pg@bowt.ie 4152 [ + - + - ]:CBC 40693692 : return tupnatts > 0 && tupnatts <= nkeyatts;
4153 : : }
4154 : :
4155 : : /*
4156 : : *
4157 : : * _bt_check_third_page() -- check whether tuple fits on a btree page at all.
4158 : : *
4159 : : * We actually need to be able to fit three items on every page, so restrict
4160 : : * any one item to 1/3 the per-page available space. Note that itemsz should
4161 : : * not include the ItemId overhead.
4162 : : *
4163 : : * It might be useful to apply TOAST methods rather than throw an error here.
4164 : : * Using out of line storage would break assumptions made by suffix truncation
4165 : : * and by contrib/amcheck, though.
4166 : : */
4167 : : void
4168 : 132 : _bt_check_third_page(Relation rel, Relation heap, bool needheaptidspace,
4169 : : Page page, IndexTuple newtup)
4170 : : {
4171 : : Size itemsz;
4172 : : BTPageOpaque opaque;
4173 : :
4174 : 132 : itemsz = MAXALIGN(IndexTupleSize(newtup));
4175 : :
4176 : : /* Double check item size against limit */
179 4177 [ - + ]: 132 : if (itemsz <= BTMaxItemSize)
2362 pg@bowt.ie 4178 :UBC 0 : return;
4179 : :
4180 : : /*
4181 : : * Tuple is probably too large to fit on page, but it's possible that the
4182 : : * index uses version 2 or version 3, or that page is an internal page, in
4183 : : * which case a slightly higher limit applies.
4184 : : */
179 pg@bowt.ie 4185 [ + - + - ]:CBC 132 : if (!needheaptidspace && itemsz <= BTMaxItemSizeNoHeapTid)
2362 4186 : 132 : return;
4187 : :
4188 : : /*
4189 : : * Internal page insertions cannot fail here, because that would mean that
4190 : : * an earlier leaf level insertion that should have failed didn't
4191 : : */
1254 michael@paquier.xyz 4192 :UBC 0 : opaque = BTPageGetOpaque(page);
2362 pg@bowt.ie 4193 [ # # ]: 0 : if (!P_ISLEAF(opaque))
4194 [ # # ]: 0 : elog(ERROR, "cannot insert oversized tuple of size %zu on internal page of index \"%s\"",
4195 : : itemsz, RelationGetRelationName(rel));
4196 : :
4197 [ # # # # : 0 : ereport(ERROR,
# # ]
4198 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4199 : : errmsg("index row size %zu exceeds btree version %u maximum %zu for index \"%s\"",
4200 : : itemsz,
4201 : : needheaptidspace ? BTREE_VERSION : BTREE_NOVAC_VERSION,
4202 : : needheaptidspace ? BTMaxItemSize : BTMaxItemSizeNoHeapTid,
4203 : : RelationGetRelationName(rel)),
4204 : : errdetail("Index row references tuple (%u,%u) in relation \"%s\".",
4205 : : ItemPointerGetBlockNumber(BTreeTupleGetHeapTID(newtup)),
4206 : : ItemPointerGetOffsetNumber(BTreeTupleGetHeapTID(newtup)),
4207 : : RelationGetRelationName(heap)),
4208 : : errhint("Values larger than 1/3 of a buffer page cannot be indexed.\n"
4209 : : "Consider a function index of an MD5 hash of the value, "
4210 : : "or use full text indexing."),
4211 : : errtableconstraint(heap, RelationGetRelationName(rel))));
4212 : : }
4213 : :
4214 : : /*
4215 : : * Are all attributes in rel "equality is image equality" attributes?
4216 : : *
4217 : : * We use each attribute's BTEQUALIMAGE_PROC opclass procedure. If any
4218 : : * opclass either lacks a BTEQUALIMAGE_PROC procedure or returns false, we
4219 : : * return false; otherwise we return true.
4220 : : *
4221 : : * Returned boolean value is stored in index metapage during index builds.
4222 : : * Deduplication can only be used when we return true.
4223 : : */
4224 : : bool
2019 pg@bowt.ie 4225 :CBC 29032 : _bt_allequalimage(Relation rel, bool debugmessage)
4226 : : {
4227 : 29032 : bool allequalimage = true;
4228 : :
4229 : : /* INCLUDE indexes can never support deduplication */
4230 : 29032 : if (IndexRelationGetNumberOfAttributes(rel) !=
4231 [ + + ]: 29032 : IndexRelationGetNumberOfKeyAttributes(rel))
4232 : 136 : return false;
4233 : :
4234 [ + + ]: 76256 : for (int i = 0; i < IndexRelationGetNumberOfKeyAttributes(rel); i++)
4235 : : {
4236 : 47618 : Oid opfamily = rel->rd_opfamily[i];
4237 : 47618 : Oid opcintype = rel->rd_opcintype[i];
4238 : 47618 : Oid collation = rel->rd_indcollation[i];
4239 : : Oid equalimageproc;
4240 : :
4241 : 47618 : equalimageproc = get_opfamily_proc(opfamily, opcintype, opcintype,
4242 : : BTEQUALIMAGE_PROC);
4243 : :
4244 : : /*
4245 : : * If there is no BTEQUALIMAGE_PROC then deduplication is assumed to
4246 : : * be unsafe. Otherwise, actually call proc and see what it says.
4247 : : */
4248 [ + + ]: 47618 : if (!OidIsValid(equalimageproc) ||
4249 [ + + ]: 47382 : !DatumGetBool(OidFunctionCall1Coll(equalimageproc, collation,
4250 : : ObjectIdGetDatum(opcintype))))
4251 : : {
4252 : 258 : allequalimage = false;
4253 : 258 : break;
4254 : : }
4255 : : }
4256 : :
4257 [ + + ]: 28896 : if (debugmessage)
4258 : : {
4259 [ + + ]: 24889 : if (allequalimage)
4260 [ + + ]: 24631 : elog(DEBUG1, "index \"%s\" can safely use deduplication",
4261 : : RelationGetRelationName(rel));
4262 : : else
4263 [ - + ]: 258 : elog(DEBUG1, "index \"%s\" cannot use deduplication",
4264 : : RelationGetRelationName(rel));
4265 : : }
4266 : :
4267 : 28896 : return allequalimage;
4268 : : }
|