forked from postgres/postgres
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnbtutils.c
5178 lines (4671 loc) · 175 KB
/
nbtutils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* nbtutils.c
* Utility code for Postgres btree implementation.
*
* Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/access/nbtree/nbtutils.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <time.h>
#include "access/nbtree.h"
#include "access/reloptions.h"
#include "access/relscan.h"
#include "commands/progress.h"
#include "lib/qunique.h"
#include "miscadmin.h"
#include "utils/array.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#define LOOK_AHEAD_REQUIRED_RECHECKS 3
#define LOOK_AHEAD_DEFAULT_DISTANCE 5
typedef struct BTSortArrayContext
{
FmgrInfo *sortproc;
Oid collation;
bool reverse;
} BTSortArrayContext;
typedef struct BTScanKeyPreproc
{
ScanKey skey;
int ikey;
int arrayidx;
} BTScanKeyPreproc;
static void _bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
FmgrInfo *orderproc, FmgrInfo **sortprocp);
static Datum _bt_find_extreme_element(IndexScanDesc scan, ScanKey skey,
Oid elemtype, StrategyNumber strat,
Datum *elems, int nelems);
static int _bt_sort_array_elements(ScanKey skey, FmgrInfo *sortproc,
bool reverse, Datum *elems, int nelems);
static bool _bt_merge_arrays(IndexScanDesc scan, ScanKey skey,
FmgrInfo *sortproc, bool reverse,
Oid origelemtype, Oid nextelemtype,
Datum *elems_orig, int *nelems_orig,
Datum *elems_next, int nelems_next);
static bool _bt_compare_array_scankey_args(IndexScanDesc scan,
ScanKey arraysk, ScanKey skey,
FmgrInfo *orderproc, BTArrayKeyInfo *array,
bool *qual_ok);
static ScanKey _bt_preprocess_array_keys(IndexScanDesc scan);
static void _bt_preprocess_array_keys_final(IndexScanDesc scan, int *keyDataMap);
static int _bt_compare_array_elements(const void *a, const void *b, void *arg);
static inline int32 _bt_compare_array_skey(FmgrInfo *orderproc,
Datum tupdatum, bool tupnull,
Datum arrdatum, ScanKey cur);
static int _bt_binsrch_array_skey(FmgrInfo *orderproc,
bool cur_elem_trig, ScanDirection dir,
Datum tupdatum, bool tupnull,
BTArrayKeyInfo *array, ScanKey cur,
int32 *set_elem_result);
static bool _bt_advance_array_keys_increment(IndexScanDesc scan, ScanDirection dir);
static void _bt_rewind_nonrequired_arrays(IndexScanDesc scan, ScanDirection dir);
static bool _bt_tuple_before_array_skeys(IndexScanDesc scan, ScanDirection dir,
IndexTuple tuple, TupleDesc tupdesc, int tupnatts,
bool readpagetup, int sktrig, bool *scanBehind);
static bool _bt_advance_array_keys(IndexScanDesc scan, BTReadPageState *pstate,
IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
int sktrig, bool sktrig_required);
#ifdef USE_ASSERT_CHECKING
static bool _bt_verify_arrays_bt_first(IndexScanDesc scan, ScanDirection dir);
static bool _bt_verify_keys_with_arraykeys(IndexScanDesc scan);
#endif
static bool _bt_compare_scankey_args(IndexScanDesc scan, ScanKey op,
ScanKey leftarg, ScanKey rightarg,
BTArrayKeyInfo *array, FmgrInfo *orderproc,
bool *result);
static bool _bt_fix_scankey_strategy(ScanKey skey, int16 *indoption);
static void _bt_mark_scankey_required(ScanKey skey);
static bool _bt_check_compare(IndexScanDesc scan, ScanDirection dir,
IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
bool advancenonrequired, bool prechecked, bool firstmatch,
bool *continuescan, int *ikey);
static bool _bt_check_rowcompare(ScanKey skey,
IndexTuple tuple, int tupnatts, TupleDesc tupdesc,
ScanDirection dir, bool *continuescan);
static void _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate,
int tupnatts, TupleDesc tupdesc);
static int _bt_keep_natts(Relation rel, IndexTuple lastleft,
IndexTuple firstright, BTScanInsert itup_key);
/*
* _bt_mkscankey
* Build an insertion scan key that contains comparison data from itup
* as well as comparator routines appropriate to the key datatypes.
*
* The result is intended for use with _bt_compare() and _bt_truncate().
* Callers that don't need to fill out the insertion scankey arguments
* (e.g. they use an ad-hoc comparison routine, or only need a scankey
* for _bt_truncate()) can pass a NULL index tuple. The scankey will
* be initialized as if an "all truncated" pivot tuple was passed
* instead.
*
* Note that we may occasionally have to share lock the metapage to
* determine whether or not the keys in the index are expected to be
* unique (i.e. if this is a "heapkeyspace" index). We assume a
* heapkeyspace index when caller passes a NULL tuple, allowing index
* build callers to avoid accessing the non-existent metapage. We
* also assume that the index is _not_ allequalimage when a NULL tuple
* is passed; CREATE INDEX callers call _bt_allequalimage() to set the
* field themselves.
*/
BTScanInsert
_bt_mkscankey(Relation rel, IndexTuple itup)
{
BTScanInsert key;
ScanKey skey;
TupleDesc itupdesc;
int indnkeyatts;
int16 *indoption;
int tupnatts;
int i;
itupdesc = RelationGetDescr(rel);
indnkeyatts = IndexRelationGetNumberOfKeyAttributes(rel);
indoption = rel->rd_indoption;
tupnatts = itup ? BTreeTupleGetNAtts(itup, rel) : 0;
Assert(tupnatts <= IndexRelationGetNumberOfAttributes(rel));
/*
* We'll execute search using scan key constructed on key columns.
* Truncated attributes and non-key attributes are omitted from the final
* scan key.
*/
key = palloc(offsetof(BTScanInsertData, scankeys) +
sizeof(ScanKeyData) * indnkeyatts);
if (itup)
_bt_metaversion(rel, &key->heapkeyspace, &key->allequalimage);
else
{
/* Utility statement callers can set these fields themselves */
key->heapkeyspace = true;
key->allequalimage = false;
}
key->anynullkeys = false; /* initial assumption */
key->nextkey = false; /* usual case, required by btinsert */
key->backward = false; /* usual case, required by btinsert */
key->keysz = Min(indnkeyatts, tupnatts);
key->scantid = key->heapkeyspace && itup ?
BTreeTupleGetHeapTID(itup) : NULL;
skey = key->scankeys;
for (i = 0; i < indnkeyatts; i++)
{
FmgrInfo *procinfo;
Datum arg;
bool null;
int flags;
/*
* We can use the cached (default) support procs since no cross-type
* comparison can be needed.
*/
procinfo = index_getprocinfo(rel, i + 1, BTORDER_PROC);
/*
* Key arguments built from truncated attributes (or when caller
* provides no tuple) are defensively represented as NULL values. They
* should never be used.
*/
if (i < tupnatts)
arg = index_getattr(itup, i + 1, itupdesc, &null);
else
{
arg = (Datum) 0;
null = true;
}
flags = (null ? SK_ISNULL : 0) | (indoption[i] << SK_BT_INDOPTION_SHIFT);
ScanKeyEntryInitializeWithInfo(&skey[i],
flags,
(AttrNumber) (i + 1),
InvalidStrategy,
InvalidOid,
rel->rd_indcollation[i],
procinfo,
arg);
/* Record if any key attribute is NULL (or truncated) */
if (null)
key->anynullkeys = true;
}
/*
* In NULLS NOT DISTINCT mode, we pretend that there are no null keys, so
* that full uniqueness check is done.
*/
if (rel->rd_index->indnullsnotdistinct)
key->anynullkeys = false;
return key;
}
/*
* free a retracement stack made by _bt_search.
*/
void
_bt_freestack(BTStack stack)
{
BTStack ostack;
while (stack != NULL)
{
ostack = stack;
stack = stack->bts_parent;
pfree(ostack);
}
}
/*
* _bt_preprocess_array_keys() -- Preprocess SK_SEARCHARRAY scan keys
*
* If there are any SK_SEARCHARRAY scan keys, deconstruct the array(s) and
* set up BTArrayKeyInfo info for each one that is an equality-type key.
* Returns modified scan keys as input for further, standard preprocessing.
*
* Currently we perform two kinds of preprocessing to deal with redundancies.
* For inequality array keys, it's sufficient to find the extreme element
* value and replace the whole array with that scalar value. This eliminates
* all but one array element as redundant. Similarly, we are capable of
* "merging together" multiple equality array keys (from two or more input
* scan keys) into a single output scan key containing only the intersecting
* array elements. This can eliminate many redundant array elements, as well
* as eliminating whole array scan keys as redundant. It can also allow us to
* detect contradictory quals.
*
* It is convenient for _bt_preprocess_keys caller to have to deal with no
* more than one equality strategy array scan key per index attribute. We'll
* always be able to set things up that way when complete opfamilies are used.
* Eliminated array scan keys can be recognized as those that have had their
* sk_strategy field set to InvalidStrategy here by us. Caller should avoid
* including these in the scan's so->keyData[] output array.
*
* We set the scan key references from the scan's BTArrayKeyInfo info array to
* offsets into the temp modified input array returned to caller. Scans that
* have array keys should call _bt_preprocess_array_keys_final when standard
* preprocessing steps are complete. This will convert the scan key offset
* references into references to the scan's so->keyData[] output scan keys.
*
* Note: the reason we need to return a temp scan key array, rather than just
* scribbling on scan->keyData, is that callers are permitted to call btrescan
* without supplying a new set of scankey data.
*/
static ScanKey
_bt_preprocess_array_keys(IndexScanDesc scan)
{
BTScanOpaque so = (BTScanOpaque) scan->opaque;
Relation rel = scan->indexRelation;
int numberOfKeys = scan->numberOfKeys;
int16 *indoption = rel->rd_indoption;
int numArrayKeys;
int origarrayatt = InvalidAttrNumber,
origarraykey = -1;
Oid origelemtype = InvalidOid;
ScanKey cur;
MemoryContext oldContext;
ScanKey arrayKeyData; /* modified copy of scan->keyData */
Assert(numberOfKeys);
/* Quick check to see if there are any array keys */
numArrayKeys = 0;
for (int i = 0; i < numberOfKeys; i++)
{
cur = &scan->keyData[i];
if (cur->sk_flags & SK_SEARCHARRAY)
{
numArrayKeys++;
Assert(!(cur->sk_flags & (SK_ROW_HEADER | SK_SEARCHNULL | SK_SEARCHNOTNULL)));
/* If any arrays are null as a whole, we can quit right now. */
if (cur->sk_flags & SK_ISNULL)
{
so->qual_ok = false;
return NULL;
}
}
}
/* Quit if nothing to do. */
if (numArrayKeys == 0)
return NULL;
/*
* Make a scan-lifespan context to hold array-associated data, or reset it
* if we already have one from a previous rescan cycle.
*/
if (so->arrayContext == NULL)
so->arrayContext = AllocSetContextCreate(CurrentMemoryContext,
"BTree array context",
ALLOCSET_SMALL_SIZES);
else
MemoryContextReset(so->arrayContext);
oldContext = MemoryContextSwitchTo(so->arrayContext);
/* Create modifiable copy of scan->keyData in the workspace context */
arrayKeyData = (ScanKey) palloc(numberOfKeys * sizeof(ScanKeyData));
memcpy(arrayKeyData, scan->keyData, numberOfKeys * sizeof(ScanKeyData));
/* Allocate space for per-array data in the workspace context */
so->arrayKeys = (BTArrayKeyInfo *) palloc(numArrayKeys * sizeof(BTArrayKeyInfo));
/* Allocate space for ORDER procs used to help _bt_checkkeys */
so->orderProcs = (FmgrInfo *) palloc(numberOfKeys * sizeof(FmgrInfo));
/* Now process each array key */
numArrayKeys = 0;
for (int i = 0; i < numberOfKeys; i++)
{
FmgrInfo sortproc;
FmgrInfo *sortprocp = &sortproc;
Oid elemtype;
bool reverse;
ArrayType *arrayval;
int16 elmlen;
bool elmbyval;
char elmalign;
int num_elems;
Datum *elem_values;
bool *elem_nulls;
int num_nonnulls;
int j;
cur = &arrayKeyData[i];
if (!(cur->sk_flags & SK_SEARCHARRAY))
continue;
/*
* First, deconstruct the array into elements. Anything allocated
* here (including a possibly detoasted array value) is in the
* workspace context.
*/
arrayval = DatumGetArrayTypeP(cur->sk_argument);
/* We could cache this data, but not clear it's worth it */
get_typlenbyvalalign(ARR_ELEMTYPE(arrayval),
&elmlen, &elmbyval, &elmalign);
deconstruct_array(arrayval,
ARR_ELEMTYPE(arrayval),
elmlen, elmbyval, elmalign,
&elem_values, &elem_nulls, &num_elems);
/*
* Compress out any null elements. We can ignore them since we assume
* all btree operators are strict.
*/
num_nonnulls = 0;
for (j = 0; j < num_elems; j++)
{
if (!elem_nulls[j])
elem_values[num_nonnulls++] = elem_values[j];
}
/* We could pfree(elem_nulls) now, but not worth the cycles */
/* If there's no non-nulls, the scan qual is unsatisfiable */
if (num_nonnulls == 0)
{
so->qual_ok = false;
break;
}
/*
* Determine the nominal datatype of the array elements. We have to
* support the convention that sk_subtype == InvalidOid means the
* opclass input type; this is a hack to simplify life for
* ScanKeyInit().
*/
elemtype = cur->sk_subtype;
if (elemtype == InvalidOid)
elemtype = rel->rd_opcintype[cur->sk_attno - 1];
/*
* If the comparison operator is not equality, then the array qual
* degenerates to a simple comparison against the smallest or largest
* non-null array element, as appropriate.
*/
switch (cur->sk_strategy)
{
case BTLessStrategyNumber:
case BTLessEqualStrategyNumber:
cur->sk_argument =
_bt_find_extreme_element(scan, cur, elemtype,
BTGreaterStrategyNumber,
elem_values, num_nonnulls);
continue;
case BTEqualStrategyNumber:
/* proceed with rest of loop */
break;
case BTGreaterEqualStrategyNumber:
case BTGreaterStrategyNumber:
cur->sk_argument =
_bt_find_extreme_element(scan, cur, elemtype,
BTLessStrategyNumber,
elem_values, num_nonnulls);
continue;
default:
elog(ERROR, "unrecognized StrategyNumber: %d",
(int) cur->sk_strategy);
break;
}
/*
* We'll need a 3-way ORDER proc to perform binary searches for the
* next matching array element. Set that up now.
*
* Array scan keys with cross-type equality operators will require a
* separate same-type ORDER proc for sorting their array. Otherwise,
* sortproc just points to the same proc used during binary searches.
*/
_bt_setup_array_cmp(scan, cur, elemtype,
&so->orderProcs[i], &sortprocp);
/*
* Sort the non-null elements and eliminate any duplicates. We must
* sort in the same ordering used by the index column, so that the
* arrays can be advanced in lockstep with the scan's progress through
* the index's key space.
*/
reverse = (indoption[cur->sk_attno - 1] & INDOPTION_DESC) != 0;
num_elems = _bt_sort_array_elements(cur, sortprocp, reverse,
elem_values, num_nonnulls);
if (origarrayatt == cur->sk_attno)
{
BTArrayKeyInfo *orig = &so->arrayKeys[origarraykey];
/*
* This array scan key is redundant with a previous equality
* operator array scan key. Merge the two arrays together to
* eliminate contradictory non-intersecting elements (or try to).
*
* We merge this next array back into attribute's original array.
*/
Assert(arrayKeyData[orig->scan_key].sk_attno == cur->sk_attno);
Assert(arrayKeyData[orig->scan_key].sk_collation ==
cur->sk_collation);
if (_bt_merge_arrays(scan, cur, sortprocp, reverse,
origelemtype, elemtype,
orig->elem_values, &orig->num_elems,
elem_values, num_elems))
{
/* Successfully eliminated this array */
pfree(elem_values);
/*
* If no intersecting elements remain in the original array,
* the scan qual is unsatisfiable
*/
if (orig->num_elems == 0)
{
so->qual_ok = false;
break;
}
/*
* Indicate to _bt_preprocess_keys caller that it must ignore
* this scan key
*/
cur->sk_strategy = InvalidStrategy;
continue;
}
/*
* Unable to merge this array with previous array due to a lack of
* suitable cross-type opfamily support. Will need to keep both
* scan keys/arrays.
*/
}
else
{
/*
* This array is the first for current index attribute.
*
* If it turns out to not be the last array (that is, if the next
* array is redundantly applied to this same index attribute),
* we'll then treat this array as the attribute's "original" array
* when merging.
*/
origarrayatt = cur->sk_attno;
origarraykey = numArrayKeys;
origelemtype = elemtype;
}
/*
* And set up the BTArrayKeyInfo data.
*
* Note: _bt_preprocess_array_keys_final will fix-up each array's
* scan_key field later on, after so->keyData[] has been finalized.
*/
so->arrayKeys[numArrayKeys].scan_key = i;
so->arrayKeys[numArrayKeys].num_elems = num_elems;
so->arrayKeys[numArrayKeys].elem_values = elem_values;
numArrayKeys++;
}
so->numArrayKeys = numArrayKeys;
MemoryContextSwitchTo(oldContext);
return arrayKeyData;
}
/*
* _bt_preprocess_array_keys_final() -- fix up array scan key references
*
* When _bt_preprocess_array_keys performed initial array preprocessing, it
* set each array's array->scan_key to the array's arrayKeys[] entry offset
* (that also work as references into the original scan->keyData[] array).
* This function handles translation of the scan key references from the
* BTArrayKeyInfo info array, from input scan key references (to the keys in
* scan->keyData[]), into output references (to the keys in so->keyData[]).
* Caller's keyDataMap[] array tells us how to perform this remapping.
*
* Also finalizes so->orderProcs[] for the scan. Arrays already have an ORDER
* proc, which might need to be repositioned to its so->keyData[]-wise offset
* (very much like the remapping that we apply to array->scan_key references).
* Non-array equality strategy scan keys (that survived preprocessing) don't
* yet have an so->orderProcs[] entry, so we set one for them here.
*
* Also converts single-element array scan keys into equivalent non-array
* equality scan keys, which decrements so->numArrayKeys. It's possible that
* this will leave this new btrescan without any arrays at all. This isn't
* necessary for correctness; it's just an optimization. Non-array equality
* scan keys are slightly faster than equivalent array scan keys at runtime.
*/
static void
_bt_preprocess_array_keys_final(IndexScanDesc scan, int *keyDataMap)
{
BTScanOpaque so = (BTScanOpaque) scan->opaque;
Relation rel = scan->indexRelation;
int arrayidx = 0;
int last_equal_output_ikey PG_USED_FOR_ASSERTS_ONLY = -1;
Assert(so->qual_ok);
/*
* Nothing for us to do when _bt_preprocess_array_keys only had to deal
* with array inequalities
*/
if (so->numArrayKeys == 0)
return;
for (int output_ikey = 0; output_ikey < so->numberOfKeys; output_ikey++)
{
ScanKey outkey = so->keyData + output_ikey;
int input_ikey;
bool found PG_USED_FOR_ASSERTS_ONLY = false;
Assert(outkey->sk_strategy != InvalidStrategy);
if (outkey->sk_strategy != BTEqualStrategyNumber)
continue;
input_ikey = keyDataMap[output_ikey];
Assert(last_equal_output_ikey < output_ikey);
Assert(last_equal_output_ikey < input_ikey);
last_equal_output_ikey = output_ikey;
/*
* We're lazy about looking up ORDER procs for non-array keys, since
* not all input keys become output keys. Take care of it now.
*/
if (!(outkey->sk_flags & SK_SEARCHARRAY))
{
Oid elemtype;
/* No need for an ORDER proc given an IS NULL scan key */
if (outkey->sk_flags & SK_SEARCHNULL)
continue;
/*
* A non-required scan key doesn't need an ORDER proc, either
* (unless it's associated with an array, which this one isn't)
*/
if (!(outkey->sk_flags & SK_BT_REQFWD))
continue;
elemtype = outkey->sk_subtype;
if (elemtype == InvalidOid)
elemtype = rel->rd_opcintype[outkey->sk_attno - 1];
_bt_setup_array_cmp(scan, outkey, elemtype,
&so->orderProcs[output_ikey], NULL);
continue;
}
/*
* Reorder existing array scan key so->orderProcs[] entries.
*
* Doing this in-place is safe because preprocessing is required to
* output all equality strategy scan keys in original input order
* (among each group of entries against the same index attribute).
* This is also the order that the arrays themselves appear in.
*/
so->orderProcs[output_ikey] = so->orderProcs[input_ikey];
/* Fix-up array->scan_key references for arrays */
for (; arrayidx < so->numArrayKeys; arrayidx++)
{
BTArrayKeyInfo *array = &so->arrayKeys[arrayidx];
Assert(array->num_elems > 0);
if (array->scan_key == input_ikey)
{
/* found it */
array->scan_key = output_ikey;
found = true;
/*
* Transform array scan keys that have exactly 1 element
* remaining (following all prior preprocessing) into
* equivalent non-array scan keys.
*/
if (array->num_elems == 1)
{
outkey->sk_flags &= ~SK_SEARCHARRAY;
outkey->sk_argument = array->elem_values[0];
so->numArrayKeys--;
/* If we're out of array keys, we can quit right away */
if (so->numArrayKeys == 0)
return;
/* Shift other arrays forward */
memmove(array, array + 1,
sizeof(BTArrayKeyInfo) *
(so->numArrayKeys - arrayidx));
/*
* Don't increment arrayidx (there was an entry that was
* just shifted forward to the offset at arrayidx, which
* will still need to be matched)
*/
}
else
{
/* Match found, so done with this array */
arrayidx++;
}
break;
}
}
Assert(found);
}
/*
* Parallel index scans require space in shared memory to store the
* current array elements (for arrays kept by preprocessing) to schedule
* the next primitive index scan. The underlying structure is protected
* using a spinlock, so defensively limit its size. In practice this can
* only affect parallel scans that use an incomplete opfamily.
*/
if (scan->parallel_scan && so->numArrayKeys > INDEX_MAX_KEYS)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg_internal("number of array scan keys left by preprocessing (%d) exceeds the maximum allowed by parallel btree index scans (%d)",
so->numArrayKeys, INDEX_MAX_KEYS)));
}
/*
* _bt_setup_array_cmp() -- Set up array comparison functions
*
* Sets ORDER proc in caller's orderproc argument, which is used during binary
* searches of arrays during the index scan. Also sets a same-type ORDER proc
* in caller's *sortprocp argument, which is used when sorting the array.
*
* Preprocessing calls here with all equality strategy scan keys (when scan
* uses equality array keys), including those not associated with any array.
* See _bt_advance_array_keys for an explanation of why it'll need to treat
* simple scalar equality scan keys as degenerate single element arrays.
*
* Caller should pass an orderproc pointing to space that'll store the ORDER
* proc for the scan, and a *sortprocp pointing to its own separate space.
* When calling here for a non-array scan key, sortprocp arg should be NULL.
*
* In the common case where we don't need to deal with cross-type operators,
* only one ORDER proc is actually required by caller. We'll set *sortprocp
* to point to the same memory that caller's orderproc continues to point to.
* Otherwise, *sortprocp will continue to point to caller's own space. Either
* way, *sortprocp will point to a same-type ORDER proc (since that's the only
* safe way to sort/deduplicate the array associated with caller's scan key).
*/
static void
_bt_setup_array_cmp(IndexScanDesc scan, ScanKey skey, Oid elemtype,
FmgrInfo *orderproc, FmgrInfo **sortprocp)
{
BTScanOpaque so = (BTScanOpaque) scan->opaque;
Relation rel = scan->indexRelation;
RegProcedure cmp_proc;
Oid opcintype = rel->rd_opcintype[skey->sk_attno - 1];
Assert(skey->sk_strategy == BTEqualStrategyNumber);
Assert(OidIsValid(elemtype));
/*
* If scankey operator is not a cross-type comparison, we can use the
* cached comparison function; otherwise gotta look it up in the catalogs
*/
if (elemtype == opcintype)
{
/* Set same-type ORDER procs for caller */
*orderproc = *index_getprocinfo(rel, skey->sk_attno, BTORDER_PROC);
if (sortprocp)
*sortprocp = orderproc;
return;
}
/*
* Look up the appropriate cross-type comparison function in the opfamily.
*
* Use the opclass input type as the left hand arg type, and the array
* element type as the right hand arg type (since binary searches use an
* index tuple's attribute value to search for a matching array element).
*
* Note: it's possible that this would fail, if the opfamily is
* incomplete, but only in cases where it's quite likely that _bt_first
* would fail in just the same way (had we not failed before it could).
*/
cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
opcintype, elemtype, BTORDER_PROC);
if (!RegProcedureIsValid(cmp_proc))
elog(ERROR, "missing support function %d(%u,%u) for attribute %d of index \"%s\"",
BTORDER_PROC, opcintype, elemtype, skey->sk_attno,
RelationGetRelationName(rel));
/* Set cross-type ORDER proc for caller */
fmgr_info_cxt(cmp_proc, orderproc, so->arrayContext);
/* Done if caller doesn't actually have an array they'll need to sort */
if (!sortprocp)
return;
/*
* Look up the appropriate same-type comparison function in the opfamily.
*
* Note: it's possible that this would fail, if the opfamily is
* incomplete, but it seems quite unlikely that an opfamily would omit
* non-cross-type comparison procs for any datatype that it supports at
* all.
*/
cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
elemtype, elemtype, BTORDER_PROC);
if (!RegProcedureIsValid(cmp_proc))
elog(ERROR, "missing support function %d(%u,%u) for attribute %d of index \"%s\"",
BTORDER_PROC, elemtype, elemtype,
skey->sk_attno, RelationGetRelationName(rel));
/* Set same-type ORDER proc for caller */
fmgr_info_cxt(cmp_proc, *sortprocp, so->arrayContext);
}
/*
* _bt_find_extreme_element() -- get least or greatest array element
*
* scan and skey identify the index column, whose opfamily determines the
* comparison semantics. strat should be BTLessStrategyNumber to get the
* least element, or BTGreaterStrategyNumber to get the greatest.
*/
static Datum
_bt_find_extreme_element(IndexScanDesc scan, ScanKey skey, Oid elemtype,
StrategyNumber strat,
Datum *elems, int nelems)
{
Relation rel = scan->indexRelation;
Oid cmp_op;
RegProcedure cmp_proc;
FmgrInfo flinfo;
Datum result;
int i;
/*
* Look up the appropriate comparison operator in the opfamily.
*
* Note: it's possible that this would fail, if the opfamily is
* incomplete, but it seems quite unlikely that an opfamily would omit
* non-cross-type comparison operators for any datatype that it supports
* at all.
*/
Assert(skey->sk_strategy != BTEqualStrategyNumber);
Assert(OidIsValid(elemtype));
cmp_op = get_opfamily_member(rel->rd_opfamily[skey->sk_attno - 1],
elemtype,
elemtype,
strat);
if (!OidIsValid(cmp_op))
elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
strat, elemtype, elemtype,
rel->rd_opfamily[skey->sk_attno - 1]);
cmp_proc = get_opcode(cmp_op);
if (!RegProcedureIsValid(cmp_proc))
elog(ERROR, "missing oprcode for operator %u", cmp_op);
fmgr_info(cmp_proc, &flinfo);
Assert(nelems > 0);
result = elems[0];
for (i = 1; i < nelems; i++)
{
if (DatumGetBool(FunctionCall2Coll(&flinfo,
skey->sk_collation,
elems[i],
result)))
result = elems[i];
}
return result;
}
/*
* _bt_sort_array_elements() -- sort and de-dup array elements
*
* The array elements are sorted in-place, and the new number of elements
* after duplicate removal is returned.
*
* skey identifies the index column whose opfamily determines the comparison
* semantics, and sortproc is a corresponding ORDER proc. If reverse is true,
* we sort in descending order.
*/
static int
_bt_sort_array_elements(ScanKey skey, FmgrInfo *sortproc, bool reverse,
Datum *elems, int nelems)
{
BTSortArrayContext cxt;
if (nelems <= 1)
return nelems; /* no work to do */
/* Sort the array elements */
cxt.sortproc = sortproc;
cxt.collation = skey->sk_collation;
cxt.reverse = reverse;
qsort_arg(elems, nelems, sizeof(Datum),
_bt_compare_array_elements, &cxt);
/* Now scan the sorted elements and remove duplicates */
return qunique_arg(elems, nelems, sizeof(Datum),
_bt_compare_array_elements, &cxt);
}
/*
* _bt_merge_arrays() -- merge next array's elements into an original array
*
* Called when preprocessing encounters a pair of array equality scan keys,
* both against the same index attribute (during initial array preprocessing).
* Merging reorganizes caller's original array (the left hand arg) in-place,
* without ever copying elements from one array into the other. (Mixing the
* elements together like this would be wrong, since they don't necessarily
* use the same underlying element type, despite all the other similarities.)
*
* Both arrays must have already been sorted and deduplicated by calling
* _bt_sort_array_elements. sortproc is the same-type ORDER proc that was
* just used to sort and deduplicate caller's "next" array. We'll usually be
* able to reuse that order PROC to merge the arrays together now. If not,
* then we'll perform a separate ORDER proc lookup.
*
* If the opfamily doesn't supply a complete set of cross-type ORDER procs we
* may not be able to determine which elements are contradictory. If we have
* the required ORDER proc then we return true (and validly set *nelems_orig),
* guaranteeing that at least the next array can be considered redundant. We
* return false if the required comparisons cannot not be made (caller must
* keep both arrays when this happens).
*/
static bool
_bt_merge_arrays(IndexScanDesc scan, ScanKey skey, FmgrInfo *sortproc,
bool reverse, Oid origelemtype, Oid nextelemtype,
Datum *elems_orig, int *nelems_orig,
Datum *elems_next, int nelems_next)
{
Relation rel = scan->indexRelation;
BTScanOpaque so = (BTScanOpaque) scan->opaque;
BTSortArrayContext cxt;
int nelems_orig_start = *nelems_orig,
nelems_orig_merged = 0;
FmgrInfo *mergeproc = sortproc;
FmgrInfo crosstypeproc;
Assert(skey->sk_strategy == BTEqualStrategyNumber);
Assert(OidIsValid(origelemtype) && OidIsValid(nextelemtype));
if (origelemtype != nextelemtype)
{
RegProcedure cmp_proc;
/*
* Cross-array-element-type merging is required, so can't just reuse
* sortproc when merging
*/
cmp_proc = get_opfamily_proc(rel->rd_opfamily[skey->sk_attno - 1],
origelemtype, nextelemtype, BTORDER_PROC);
if (!RegProcedureIsValid(cmp_proc))
{
/* Can't make the required comparisons */
return false;
}
/* We have all we need to determine redundancy/contradictoriness */
mergeproc = &crosstypeproc;
fmgr_info_cxt(cmp_proc, mergeproc, so->arrayContext);
}
cxt.sortproc = mergeproc;
cxt.collation = skey->sk_collation;
cxt.reverse = reverse;
for (int i = 0, j = 0; i < nelems_orig_start && j < nelems_next;)
{
Datum *oelem = elems_orig + i,
*nelem = elems_next + j;
int res = _bt_compare_array_elements(oelem, nelem, &cxt);
if (res == 0)
{
elems_orig[nelems_orig_merged++] = *oelem;
i++;
j++;
}
else if (res < 0)
i++;
else /* res > 0 */
j++;
}
*nelems_orig = nelems_orig_merged;
return true;
}
/*
* Compare an array scan key to a scalar scan key, eliminating contradictory
* array elements such that the scalar scan key becomes redundant.
*
* Array elements can be eliminated as contradictory when excluded by some
* other operator on the same attribute. For example, with an index scan qual
* "WHERE a IN (1, 2, 3) AND a < 2", all array elements except the value "1"
* are eliminated, and the < scan key is eliminated as redundant. Cases where
* every array element is eliminated by a redundant scalar scan key have an
* unsatisfiable qual, which we handle by setting *qual_ok=false for caller.
*
* If the opfamily doesn't supply a complete set of cross-type ORDER procs we
* may not be able to determine which elements are contradictory. If we have
* the required ORDER proc then we return true (and validly set *qual_ok),
* guaranteeing that at least the scalar scan key can be considered redundant.
* We return false if the comparison could not be made (caller must keep both
* scan keys when this happens).
*/
static bool
_bt_compare_array_scankey_args(IndexScanDesc scan, ScanKey arraysk, ScanKey skey,
FmgrInfo *orderproc, BTArrayKeyInfo *array,
bool *qual_ok)
{
Relation rel = scan->indexRelation;
Oid opcintype = rel->rd_opcintype[arraysk->sk_attno - 1];
int cmpresult = 0,
cmpexact = 0,
matchelem,
new_nelems = 0;
FmgrInfo crosstypeproc;
FmgrInfo *orderprocp = orderproc;
Assert(arraysk->sk_attno == skey->sk_attno);
Assert(array->num_elems > 0);
Assert(!(arraysk->sk_flags & (SK_ISNULL | SK_ROW_HEADER | SK_ROW_MEMBER)));
Assert((arraysk->sk_flags & SK_SEARCHARRAY) &&
arraysk->sk_strategy == BTEqualStrategyNumber);
Assert(!(skey->sk_flags & (SK_ISNULL | SK_ROW_HEADER | SK_ROW_MEMBER)));
Assert(!(skey->sk_flags & SK_SEARCHARRAY) ||
skey->sk_strategy != BTEqualStrategyNumber);
/*
* _bt_binsrch_array_skey searches an array for the entry best matching a
* datum of opclass input type for the index's attribute (on-disk type).