-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathpg_btree.c
1257 lines (1100 loc) · 31.3 KB
/
pg_btree.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
/*
* pg_bulkload: lib/pg_btree.c
*
* Copyright (c) 2007-2025, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*/
/**
* @file
* @brief implementation of B-Tree index processing module
*/
#include "pg_bulkload.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/nbtree.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "executor/executor.h"
#include "storage/fd.h"
#include "storage/lmgr.h"
#if PG_VERSION_NUM >= 170000
#include "storage/bulk_write.h"
#else
#include "storage/smgr.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "storage/md.h"
#endif
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#if PG_VERSION_NUM < 120000
#include "utils/tqual.h"
#endif
#if PG_VERSION_NUM >= 80400
#include "utils/snapmgr.h"
#endif
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
#include "logger.h"
#if PG_VERSION_NUM >= 180000
#error unsupported PostgreSQL version
#elif PG_VERSION_NUM >= 170000
#include "nbtree/nbtsort-17.c"
#elif PG_VERSION_NUM >= 160000
#include "nbtree/nbtsort-16.c"
#elif PG_VERSION_NUM >= 150000
#include "nbtree/nbtsort-15.c"
#elif PG_VERSION_NUM >= 140000
#include "nbtree/nbtsort-14.c"
#elif PG_VERSION_NUM >= 130000
#include "nbtree/nbtsort-13.c"
#elif PG_VERSION_NUM >= 120000
#include "nbtree/nbtsort-12.c"
#elif PG_VERSION_NUM >= 110000
#include "nbtree/nbtsort-11.c"
#elif PG_VERSION_NUM >= 100000
#include "nbtree/nbtsort-10.c"
#elif PG_VERSION_NUM >= 90600
#include "nbtree/nbtsort-9.6.c"
#elif PG_VERSION_NUM >= 90500
#include "nbtree/nbtsort-9.5.c"
#elif PG_VERSION_NUM >= 90400
#include "nbtree/nbtsort-9.4.c"
#elif PG_VERSION_NUM >= 90300
#include "nbtree/nbtsort-9.3.c"
#elif PG_VERSION_NUM >= 90200
#include "nbtree/nbtsort-9.2.c"
#elif PG_VERSION_NUM >= 90100
#include "nbtree/nbtsort-9.1.c"
#elif PG_VERSION_NUM >= 90000
#include "nbtree/nbtsort-9.0.c"
#elif PG_VERSION_NUM >= 80400
#include "nbtree/nbtsort-8.4.c"
#elif PG_VERSION_NUM >= 80300
#include "nbtree/nbtsort-8.3.c"
#else
#error unsupported PostgreSQL version
#endif
#if PG_VERSION_NUM >= 140000
#include "nbtree/nbtsort-common.c"
#endif
#include "pg_btree.h"
#include "pg_profile.h"
#include "pgut/pgut-be.h"
/**
* @brief Reader for existing B-Tree index
*
* The 'page' field should be allocate with palloc(BLCKSZ) to
* avoid bus error.
*/
typedef struct BTReader
{
SMgrRelationData smgr; /**< Index file */
BlockNumber blkno; /**< Current block number */
OffsetNumber offnum; /**< Current item offset */
char *page; /**< Cached page */
} BTReader;
static BTSpool **IndexSpoolBegin(ResultRelInfo *relinfo, bool enforceUnique);
static void IndexSpoolEnd(Spooler *self);
static void IndexSpoolInsert(BTSpool **spools, TupleTableSlot *slot,
ItemPointer tupleid, EState *estate,
ResultRelInfo *relinfo);
static IndexTuple BTSpoolGetNextItem(BTSpool *spool, IndexTuple itup, bool *should_free);
static int BTReaderInit(BTReader *reader, Relation rel);
static void BTReaderTerm(BTReader *reader);
static void BTReaderReadPage(BTReader *reader, BlockNumber blkno);
static IndexTuple BTReaderGetNextItem(BTReader *reader);
static bool _bt_mergebuild(Spooler *self, BTSpool *btspool);
static void _bt_mergeload(Spooler *self, BTWriteState *wstate, BTSpool *btspool,
BTReader *btspool2, Relation heapRel);
static int compare_indextuple(const IndexTuple itup1, const IndexTuple itup2,
ScanKey entry, int keysz, TupleDesc tupdes, bool *hasnull);
static bool heap_is_visible(Relation heapRel, ItemPointer htid);
static void remove_duplicate(Spooler *self, Relation heap, IndexTuple itup, const char *relname);
void
SpoolerOpen(Spooler *self,
Relation rel,
bool use_wal,
ON_DUPLICATE on_duplicate,
int64 max_dup_errors,
const char *dup_badfile)
{
memset(self, 0, sizeof(Spooler));
self->on_duplicate = on_duplicate;
self->use_wal = use_wal;
self->max_dup_errors = max_dup_errors;
self->dup_old = 0;
self->dup_new = 0;
self->dup_badfile = pstrdup(dup_badfile);
self->dup_fp = NULL;
self->relinfo = makeNode(ResultRelInfo);
self->relinfo->ri_RangeTableIndex = 1; /* dummy */
self->relinfo->ri_RelationDesc = rel;
self->relinfo->ri_TrigDesc = NULL; /* TRIGGER is not supported */
self->relinfo->ri_TrigInstrument = NULL;
#if PG_VERSION_NUM >= 90500
ExecOpenIndices(self->relinfo, false);
#else
ExecOpenIndices(self->relinfo);
#endif
self->estate = CreateExecutorState();
#if PG_VERSION_NUM >= 140000
self->estate->es_opened_result_relations =
lappend(self->estate->es_opened_result_relations, self->relinfo);
#else
self->estate->es_num_result_relations = 1;
self->estate->es_result_relations = self->relinfo;
self->estate->es_result_relation_info = self->relinfo;
#endif
#if PG_VERSION_NUM >= 120000
self->slot = MakeSingleTupleTableSlot(RelationGetDescr(rel), &TTSOpsHeapTuple);
#else
self->slot = MakeSingleTupleTableSlot(RelationGetDescr(rel));
#endif
self->spools = IndexSpoolBegin(self->relinfo,
max_dup_errors == 0);
}
void
SpoolerClose(Spooler *self)
{
/* Merge indexes */
if (self->spools != NULL)
IndexSpoolEnd(self);
/* Terminate spooler. */
ExecDropSingleTupleTableSlot(self->slot);
#if PG_VERSION_NUM >= 140000
if (self->relinfo)
ExecCloseResultRelations(self->estate);
#else
if (self->estate->es_result_relation_info)
ExecCloseIndices(self->estate->es_result_relation_info);
#endif
FreeExecutorState(self->estate);
/* Close and release members. */
if (self->dup_fp != NULL && FreeFile(self->dup_fp) < 0)
ereport(WARNING,
(errcode_for_file_access(),
errmsg("could not close duplicate bad file \"%s\": %m",
self->dup_badfile)));
if (self->dup_badfile != NULL)
pfree(self->dup_badfile);
}
void
SpoolerInsert(Spooler *self, HeapTuple tuple)
{
ResultRelInfo *relinfo;
/* Spool keys in the tuple */
#if PG_VERSION_NUM >= 120000
ExecStoreHeapTuple(tuple, self->slot, false);
#else
ExecStoreTuple(tuple, self->slot, InvalidBuffer, false);
#endif
#if PG_VERSION_NUM >= 140000
relinfo = self->relinfo;
#else
relinfo = self->estate->es_result_relation_info;
#endif
IndexSpoolInsert(self->spools, self->slot,
&(tuple->t_self), self->estate,
relinfo);
BULKLOAD_PROFILE(&prof_writer_index);
}
/*
* IndexSpoolBegin - Initialize spools.
*/
static BTSpool **
IndexSpoolBegin(ResultRelInfo *relinfo, bool enforceUnique)
{
int i;
int numIndices = relinfo->ri_NumIndices;
RelationPtr indices = relinfo->ri_IndexRelationDescs;
BTSpool **spools;
#if PG_VERSION_NUM >= 90300
Relation heapRel = relinfo->ri_RelationDesc;
#endif
spools = palloc(numIndices * sizeof(BTSpool *));
for (i = 0; i < numIndices; i++)
{
/* TODO: Support hash, gist and gin. */
if (indices[i]->rd_index->indisvalid &&
indices[i]->rd_rel->relam == BTREE_AM_OID)
{
elog(DEBUG1, "pg_bulkload: spool \"%s\"",
RelationGetRelationName(indices[i]));
#if PG_VERSION_NUM >= 90300
spools[i] = _bt_spoolinit(heapRel,indices[i],
enforceUnique ? indices[i]->rd_index->indisunique: false,
#if PG_VERSION_NUM >= 150000
indices[i]->rd_index->indnullsnotdistinct,
#endif
false);
#else
spools[i] = _bt_spoolinit(indices[i],
enforceUnique ? indices[i]->rd_index->indisunique: false,
false);
#endif
spools[i]->isunique = indices[i]->rd_index->indisunique;
}
else
spools[i] = NULL;
}
return spools;
}
/*
* IndexSpoolEnd - Flush and delete spools or reindex if not a btree index.
*/
void
IndexSpoolEnd(Spooler *self)
{
BTSpool **spools = self->spools;
int i;
RelationPtr indices = self->relinfo->ri_IndexRelationDescs;
#if PG_VERSION_NUM >= 90500
char persistence;
#endif
Assert(spools != NULL);
Assert(self->relinfo != NULL);
for (i = 0; i < self->relinfo->ri_NumIndices; i++)
{
if (spools[i] != NULL && _bt_mergebuild(self, spools[i]))
{
_bt_spooldestroy(spools[i]);
}
else
{
Oid indexOid = RelationGetRelid(indices[i]);
#if PG_VERSION_NUM >= 140000
ReindexParams params = {0};
#endif
/* Close index before reindex to pass CheckTableNotInUse. */
relation_close(indices[i], NoLock);
#if PG_VERSION_NUM >= 90500
persistence = indices[i]->rd_rel->relpersistence;
#endif
indices[i] = NULL;
#if PG_VERSION_NUM >= 170000
reindex_index(NULL, indexOid, false, persistence, ¶ms);
#elif PG_VERSION_NUM >= 140000
reindex_index(indexOid, false, persistence, ¶ms);
#elif PG_VERSION_NUM >= 90500
reindex_index(indexOid, false, persistence, 0);
#else
reindex_index(indexOid, false);
#endif
CommandCounterIncrement();
BULKLOAD_PROFILE(&prof_reindex);
}
}
pfree(spools);
}
/*
* IndexSpoolInsert -
*
* Copied from ExecInsertIndexTuples.
*/
static void
IndexSpoolInsert(BTSpool **spools, TupleTableSlot *slot,
ItemPointer tupleid, EState *estate,
ResultRelInfo *relinfo)
{
int i;
int numIndices;
RelationPtr indices;
IndexInfo **indexInfoArray;
ExprContext *econtext;
/*
* Get information from the result relation relinfo structure.
*/
numIndices = relinfo->ri_NumIndices;
indices = relinfo->ri_IndexRelationDescs;
indexInfoArray = relinfo->ri_IndexRelationInfo;
/*
* We will use the EState's per-tuple context for evaluating predicates
* and index expressions (creating it if it's not already there).
*/
econtext = GetPerTupleExprContext(estate);
/* Arrange for econtext's scan tuple to be the tuple under test */
econtext->ecxt_scantuple = slot;
for (i = 0; i < numIndices; i++)
{
Datum values[INDEX_MAX_KEYS];
bool isnull[INDEX_MAX_KEYS];
IndexInfo *indexInfo;
IndexTuple itup;
/*
* Skip non-btree indexes. Such indexes are handled with reindex
* at the end.
*/
if (spools[i] == NULL)
continue;
indexInfo = indexInfoArray[i];
/* If the index is marked as read-only, ignore it */
if (!indexInfo->ii_ReadyForInserts)
continue;
/* Check for partial index */
if (indexInfo->ii_Predicate != NIL)
{
#if PG_VERSION_NUM >= 100000
ExprState *predicate;
#else
List *predicate;
#endif
/*
* If predicate state not set up yet, create it (in the estate's
* per-query context)
*/
predicate = indexInfo->ii_PredicateState;
#if PG_VERSION_NUM >= 100000
if (predicate == NULL)
{
predicate = ExecPrepareQual(indexInfo->ii_Predicate, estate);
#else
if (predicate == NIL)
{
predicate = (List *) ExecPrepareExpr((Expr *) indexInfo->ii_Predicate, estate);
#endif
indexInfo->ii_PredicateState = predicate;
}
/* Skip this index-update if the predicate isn'loader satisfied */
#if PG_VERSION_NUM >= 100000
if (!ExecQual(predicate, econtext))
#else
if (!ExecQual(predicate, econtext, false))
#endif
continue;
}
FormIndexDatum(indexInfo, slot, estate, values, isnull);
/* Spool the tuple. */
itup = index_form_tuple(RelationGetDescr(indices[i]), values, isnull);
itup->t_tid = *tupleid;
#if PG_VERSION_NUM >= 90500
_bt_spool(spools[i], &itup->t_tid, values, isnull);
#else
_bt_spool(itup, spools[i]);
#endif
pfree(itup);
}
}
static bool
_bt_mergebuild(Spooler *self, BTSpool *btspool)
{
Relation heapRel = self->relinfo->ri_RelationDesc;
BTWriteState wstate;
BTReader reader;
int merge;
#if PG_VERSION_NUM >= 170000
bool use_wal;
#endif
Assert(btspool->index->rd_index->indisvalid);
tuplesort_performsort(btspool->sortstate);
#if PG_VERSION_NUM >= 90300
/*
* As of 9.3, error messages (in general) and btree error messages (in
* particular) want to display the table name, for which we must save
* a reference to heap as well so that error message generating code
* can use it.
*/
wstate.heap = btspool->heap;
#endif
wstate.index = btspool->index;
#if PG_VERSION_NUM >= 120000
wstate.inskey = _bt_mkscankey(wstate.index, NULL);
#endif
/*
* We need to log index creation in WAL iff WAL archiving is enabled AND
* it's not a temp index.
*/
#if PG_VERSION_NUM >= 170000
use_wal = self->use_wal &&
XLogIsNeeded() && !RELATION_IS_LOCAL(wstate.index);
#elif PG_VERSION_NUM >= 90000
wstate.btws_use_wal = self->use_wal &&
XLogIsNeeded() && !RELATION_IS_LOCAL(wstate.index);
#else
wstate.btws_use_wal = self->use_wal &&
XLogArchivingActive() && !RELATION_IS_LOCAL(wstate.index);
#endif
/* reserve the metapage */
wstate.btws_pages_alloced = BTREE_METAPAGE + 1;
#if PG_VERSION_NUM < 170000
wstate.btws_pages_written = 0;
wstate.btws_zeropage = NULL; /* until needed */
#endif
/*
* Flush dirty buffers so that we will read the index files directly
* in order to get pre-existing data. We must acquire AccessExclusiveLock
* for the target table for calling FlushRelationBuffer().
*/
LockRelation(wstate.index, AccessExclusiveLock);
FlushRelationBuffers(wstate.index);
BULKLOAD_PROFILE(&prof_flush);
merge = BTReaderInit(&reader, wstate.index);
if (merge == -1)
return false;
elog(DEBUG1, "pg_bulkload: build \"%s\" %s merge (%s wal)",
RelationGetRelationName(wstate.index),
merge ? "with" : "without",
#if PG_VERSION_NUM >= 170000
use_wal ? "with" : "without");
#else
wstate.btws_use_wal ? "with" : "without");
#endif
/* Assign a new file node. */
RelationSetNewRelfilenode(wstate.index, InvalidTransactionId);
if (merge || (btspool->isunique && self->max_dup_errors > 0))
{
/* Merge two streams into the new file node that we assigned. */
BULKLOAD_PROFILE_PUSH();
_bt_mergeload(self, &wstate, btspool, &reader, heapRel);
BULKLOAD_PROFILE_POP();
BULKLOAD_PROFILE(&prof_merge);
}
else
{
/* Fast path for newly created index. */
_bt_load(&wstate, btspool, NULL);
BULKLOAD_PROFILE(&prof_index);
}
BTReaderTerm(&reader);
return true;
}
/*
* _bt_mergeload - Merge two streams of index tuples into new index files.
*/
static void
_bt_mergeload(Spooler *self, BTWriteState *wstate, BTSpool *btspool, BTReader *btspool2, Relation heapRel)
{
BTPageState *state = NULL;
IndexTuple itup,
itup2;
bool should_free = false;
TupleDesc tupdes = RelationGetDescr(wstate->index);
int keysz = RelationGetNumberOfAttributes(wstate->index);
#if PG_VERSION_NUM >= 120000
BTScanInsert btIndexScanKey;
#endif
ScanKey indexScanKey;
ON_DUPLICATE on_duplicate = self->on_duplicate;
Assert(btspool != NULL);
#if PG_VERSION_NUM >= 170000
wstate->bulkstate = smgr_bulk_start_rel(wstate->index, MAIN_FORKNUM);
#endif
/* the preparation of merge */
itup = BTSpoolGetNextItem(btspool, NULL, &should_free);
itup2 = BTReaderGetNextItem(btspool2);
#if PG_VERSION_NUM >= 120000
btIndexScanKey = _bt_mkscankey(wstate->index, NULL);
indexScanKey = btIndexScanKey->scankeys;
#else
indexScanKey = _bt_mkscankey_nodata(wstate->index);
#endif
for (;;)
{
bool load1 = true; /* load BTSpool next ? */
bool hasnull;
int32 compare;
if (self->dup_old + self->dup_new > self->max_dup_errors)
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Maximum duplicate error count exceeded")));
if (itup2 == NULL)
{
if (itup == NULL)
break;
}
else if (itup != NULL)
{
compare = compare_indextuple(itup, itup2, indexScanKey,
keysz, tupdes, &hasnull);
if (compare == 0 &&
#if PG_VERSION_NUM >= 150000
(!hasnull || btspool->nulls_not_distinct)
#else
!hasnull
#endif
&& btspool->isunique)
{
ItemPointerData t_tid2;
/*
* t_tid is update by heap_is_visible(), because use it for an
* index, t_tid backup
*/
ItemPointerCopy(&itup2->t_tid, &t_tid2);
/* The tuple pointed by the old index should not be visible. */
if (!heap_is_visible(heapRel, &itup->t_tid))
{
itup = BTSpoolGetNextItem(btspool, itup, &should_free);
}
else if (!heap_is_visible(heapRel, &itup2->t_tid))
{
itup2 = BTReaderGetNextItem(btspool2);
}
else
{
if (on_duplicate == ON_DUPLICATE_KEEP_NEW)
{
self->dup_old++;
remove_duplicate(self, heapRel, itup2,
RelationGetRelationName(wstate->index));
itup2 = BTReaderGetNextItem(btspool2);
}
else
{
ItemPointerCopy(&t_tid2, &itup2->t_tid);
self->dup_new++;
remove_duplicate(self, heapRel, itup,
RelationGetRelationName(wstate->index));
itup = BTSpoolGetNextItem(btspool, itup, &should_free);
}
}
continue;
}
else if (compare > 0)
load1 = false;
}
else
load1 = false;
BULKLOAD_PROFILE(&prof_merge_unique);
/* When we see first tuple, create first index page */
if (state == NULL)
state = _bt_pagestate(wstate, 0);
if (load1)
{
IndexTuple next_itup = NULL, tmp_itup = NULL;
bool next_should_free = false;
for (;;)
{
/* get next item */
if (itup)
{
tmp_itup = CopyIndexTuple(itup);
if (should_free)
pfree(itup);
should_free = true;
itup = tmp_itup;
}
next_itup = BTSpoolGetNextItem(btspool, next_itup,
&next_should_free);
if (!btspool->isunique || next_itup == NULL)
break;
compare = compare_indextuple(itup, next_itup, indexScanKey,
keysz, tupdes, &hasnull);
if (compare < 0 ||
#if PG_VERSION_NUM >= 150000
(hasnull && !btspool->nulls_not_distinct)
#else
hasnull
#endif
)
break;
if (compare > 0)
{
/* shouldn't happen */
elog(ERROR, "faild in tuplesort_performsort");
}
/*
* If tupple is deleted by other unique indexes, not visible
*/
if (!heap_is_visible(heapRel, &next_itup->t_tid))
{
continue;
}
if (!heap_is_visible(heapRel, &itup->t_tid))
{
if (should_free)
pfree(itup);
itup = next_itup;
should_free = next_should_free;
next_should_free = false;
continue;
}
/* not unique between input files */
self->dup_new++;
remove_duplicate(self, heapRel, next_itup,
RelationGetRelationName(wstate->index));
if (self->dup_old + self->dup_new > self->max_dup_errors)
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("Maximum duplicate error count exceeded")));
}
#if PG_VERSION_NUM >= 130000
_bt_buildadd(wstate, state, itup, 0);
#else
_bt_buildadd(wstate, state, itup);
#endif
if (should_free)
pfree(itup);
itup = next_itup;
should_free = next_should_free;
}
else
{
#if PG_VERSION_NUM >= 130000
_bt_buildadd(wstate, state, itup2, 0);
#else
_bt_buildadd(wstate, state, itup2);
#endif
itup2 = BTReaderGetNextItem(btspool2);
}
BULKLOAD_PROFILE(&prof_merge_insert);
}
#if PG_VERSION_NUM >= 120000
pfree(btIndexScanKey);
#else
_bt_freeskey(indexScanKey);
#endif
/* Close down final pages and write the metapage */
_bt_uppershutdown(wstate, state);
/*
* If the index isn't temp, we must fsync it down to disk before it's safe
* to commit the transaction. (For a temp index we don't care since the
* index will be uninteresting after a crash anyway.)
*
* It's obvious that we must do this when not WAL-logging the build. It's
* less obvious that we have to do it even if we did WAL-log the index
* pages. The reason is that since we're building outside shared buffers,
* a CHECKPOINT occurring during the build has no way to flush the
* previously written data to disk (indeed it won't know the index even
* exists). A crash later on would replay WAL from the checkpoint,
* therefore it wouldn't replay our earlier WAL entries. If we do not
* fsync those pages here, they might still not be on disk when the crash
* occurs.
*/
#if PG_VERSION_NUM >= 170000
smgr_bulk_finish(wstate->bulkstate);
#else
#if PG_VERSION_NUM >= 90100
if (!RELATION_IS_LOCAL(wstate->index)&& !(wstate->index->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED))
{
#if PG_VERSION_NUM >= 150000
RelationGetSmgr(wstate->index);
#else
RelationOpenSmgr(wstate->index);
#endif
smgrimmedsync(wstate->index->rd_smgr, MAIN_FORKNUM);
}
#else
if (!RELATION_IS_LOCAL(wstate->index))
{
RelationOpenSmgr(wstate->index);
smgrimmedsync(wstate->index->rd_smgr, MAIN_FORKNUM);
}
#endif
#endif
BULKLOAD_PROFILE(&prof_merge_term);
}
static IndexTuple
BTSpoolGetNextItem(BTSpool *spool, IndexTuple itup, bool *should_free)
{
if (*should_free)
pfree(itup);
#if PG_VERSION_NUM >= 100000
return tuplesort_getindextuple(spool->sortstate, true);
#else
return tuplesort_getindextuple(spool->sortstate, true, should_free);
#endif
}
/**
* @brief Read the left-most leaf page by walking down on index tree structure
* from root node.
*
* Process flow
* -# Open index file and read meta page
* -# Get block number of root page
* -# Read "fast root" page
* -# Read left child page until reaching left-most leaf page
*
* After calling this function, the members of BTReader are the following:
* - smgr : Smgr relation of the existing index file.
* - blkno : block number of left-most leaf page. If there is no leaf page,
* InvalidBlockNumber is set.
* - offnum : InvalidOffsetNumber is set.
* - page : Left-most leaf page, or undefined if no leaf page.
*
* @param reader [in/out] B-Tree index reader
* @return 1 iff there are some tuples, -1 if unexpected failure, or 0 otherwise
*/
static int
BTReaderInit(BTReader *reader, Relation rel)
{
BTPageOpaque metaopaque;
BTMetaPageData *metad;
BTPageOpaque opaque;
BlockNumber blkno;
/*
* HACK: We cannot use smgropen because smgrs returned from it
* will be closed automatically when we assign a new file node.
*
* XXX: It might be better to open the previous relfilenode with
* smgropen *after* RelationSetNewRelfilenode.
*/
memset(&reader->smgr, 0, sizeof(reader->smgr));
#if PG_VERSION_NUM >= 170000
reader->smgr.smgr_rlocator.locator = rel->rd_locator;
reader->smgr.smgr_rlocator.backend = rel->rd_backend == MyBackendType ? MyBackendType : InvalidCommandId;
#elif PG_VERSION_NUM >= 160000
reader->smgr.smgr_rlocator.locator = rel->rd_locator;
reader->smgr.smgr_rlocator.backend = rel->rd_backend == MyBackendId ? MyBackendId : InvalidBackendId;
#elif PG_VERSION_NUM >= 90100
reader->smgr.smgr_rnode.node = rel->rd_node;
reader->smgr.smgr_rnode.backend =
rel->rd_backend == MyBackendId ? MyBackendId : InvalidBackendId;
#else
reader->smgr.smgr_rnode = rel->rd_node;
#endif
reader->smgr.smgr_which = 0; /* md.c */
reader->blkno = InvalidBlockNumber;
reader->offnum = InvalidOffsetNumber;
#if PG_VERSION_NUM >= 160000
reader->page = (Page) palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE, 0);
#else
reader->page = palloc(BLCKSZ);
#endif
/*
* Read meta page and check sanity of it.
*
* XXX: It might be better to do REINDEX against corrupted indexes
* instead of raising errors because we've spent long time for data
* loading...
*/
BTReaderReadPage(reader, BTREE_METAPAGE);
metaopaque = (BTPageOpaque) PageGetSpecialPointer(reader->page);
metad = BTPageGetMeta(reader->page);
if (!(metaopaque->btpo_flags & BTP_META) ||
metad->btm_magic != BTREE_MAGIC)
ereport(ERROR,
(errcode(ERRCODE_INDEX_CORRUPTED),
errmsg("index \"%s\" is not a reader",
RelationGetRelationName(rel))));
if (metad->btm_version != BTREE_VERSION)
ereport(ERROR,
(errcode(ERRCODE_INDEX_CORRUPTED),
errmsg("version mismatch in index \"%s\": file version %d,"
" code version %d",
RelationGetRelationName(rel),
metad->btm_version, BTREE_VERSION)));
if (metad->btm_root == P_NONE)
{
/* No root page; We ignore the index in the subsequent build. */
reader->blkno = InvalidBlockNumber;
return 0;
}
/* Go to the fast root page. */
blkno = metad->btm_fastroot;
BTReaderReadPage(reader, blkno);
opaque = (BTPageOpaque) PageGetSpecialPointer(reader->page);
/* Walk down to the left-most leaf page */
while (!P_ISLEAF(opaque))
{
ItemId firstid;
IndexTuple itup;
/* Get the block number of the left child */
firstid = PageGetItemId(reader->page, P_FIRSTDATAKEY(opaque));
itup = (IndexTuple) PageGetItem(reader->page, firstid);
#if PG_VERSION_NUM >= 130000
blkno = BTreeTupleGetDownLink(itup);
#elif PG_VERSION_NUM >= 110000
blkno = BTreeInnerTupleGetDownLink(itup);
#else
blkno = ItemPointerGetBlockNumber(&(itup->t_tid));
#endif
/* Go down to children */
for (;;)
{
BTReaderReadPage(reader, blkno);
opaque = (BTPageOpaque) PageGetSpecialPointer(reader->page);
if (!P_IGNORE(opaque))
break;
if (P_RIGHTMOST(opaque))
{
/* We reach end of the index without any valid leaves. */
reader->blkno = InvalidBlockNumber;
return 0;
}
blkno = opaque->btpo_next;
}
}
return 1;
}
/**
* @brief Release resources used in the reader
*/
static void
BTReaderTerm(BTReader *reader)
{
/* FIXME: We should use smgrclose, but it is not managed in smgr. */
Assert(reader->smgr.smgr_which == 0);
mdclose(&reader->smgr, MAIN_FORKNUM);
pfree(reader->page);
}
/**
* @brief Read the indicated block into BTReader structure
*/
static void
BTReaderReadPage(BTReader *reader, BlockNumber blkno)
{
smgrread(&reader->smgr, MAIN_FORKNUM, blkno, reader->page);
reader->blkno = blkno;
reader->offnum = InvalidOffsetNumber;
}
/**
* @brief Get the next smaller item from the old index
*
* Process flow
* -# Examine the max offset position in the page
* -# Search the next item
* -# If the item has deleted flag, seearch the next one
* -# If we can't find items any more, read the leaf page on the right side
* and search the next again
*
* These members are updated:
* - page : page which includes picked-up item
* - offnum : item offset number of the picked-up item
*
* @param reader [in/out] BTReader structure
* @return next index tuple, or null if no more tuples
*/
static IndexTuple
BTReaderGetNextItem(BTReader *reader)
{
OffsetNumber maxoff;
ItemId itemid;
BTPageOpaque opaque;
/*
* If any leaf page isn't read, the state is treated like as EOF
*/
if (reader->blkno == InvalidBlockNumber)
return NULL;
maxoff = PageGetMaxOffsetNumber(reader->page);
for (;;)
{
/*
* If no one items are picked up, offnum is set to InvalidOffsetNumber.
*/
if (reader->offnum == InvalidOffsetNumber)
{
opaque = (BTPageOpaque) PageGetSpecialPointer(reader->page);
reader->offnum = P_FIRSTDATAKEY(opaque);
}
else
reader->offnum = OffsetNumberNext(reader->offnum);