nbtsort.c 19.2 KB
Newer Older
1
/*-------------------------------------------------------------------------
2
 *
3 4
 * nbtsort.c
 *		Build a btree from sorted input by loading leaf pages sequentially.
5 6 7
 *
 * NOTES
 *
8 9
 * We use tuplesort.c to sort the given index tuples into order.
 * Then we scan the index tuples in order and build the btree pages
B
Bruce Momjian 已提交
10
 * for each level.	We load source tuples into leaf-level pages.
11 12 13 14 15
 * Whenever we fill a page at one level, we add a link to it to its
 * parent level (starting a new parent level if necessary).  When
 * done, we write out each final page on each level, adding it to
 * its parent level.  When we have only one page on a level, it must be
 * the root -- it can be attached to the btree metapage and we are done.
16
 *
17 18
 * This code is moderately slow (~10% slower) compared to the regular
 * btree (insertion) build code on sorted or well-clustered data.  On
19 20
 * random data, however, the insertion build code is unusable -- the
 * difference on a 60MB heap is a factor of 15 because the random
21 22 23 24
 * probes into the btree thrash the buffer pool.  (NOTE: the above
 * "10%" estimate is probably obsolete, since it refers to an old and
 * not very good external sort implementation that used to exist in
 * this module.  tuplesort.c is almost certainly faster.)
25
 *
26 27 28 29 30 31 32
 * It is not wise to pack the pages entirely full, since then *any*
 * insertion would cause a split (and not only of the leaf page; the need
 * for a split would cascade right up the tree).  The steady-state load
 * factor for btrees is usually estimated at 70%.  We choose to pack leaf
 * pages to 90% and upper pages to 70%.  This gives us reasonable density
 * (there aren't many upper pages if the keys are reasonable-size) without
 * incurring a lot of cascading splits during early insertions.
33
 *
34
 *
B
Bruce Momjian 已提交
35
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
36
 * Portions Copyright (c) 1994, Regents of the University of California
37 38
 *
 * IDENTIFICATION
39
 *	  $Header: /cvsroot/pgsql/src/backend/access/nbtree/nbtsort.c,v 1.73 2003/07/21 20:29:39 tgl Exp $
40
 *
41 42 43
 *-------------------------------------------------------------------------
 */

44
#include "postgres.h"
45

46
#include "access/nbtree.h"
47
#include "miscadmin.h"
48
#include "utils/tuplesort.h"
49

50

51
/*
52
 * Status record for spooling.
53
 */
54
struct BTSpool
55
{
56 57
	Tuplesortstate *sortstate;	/* state data for tuplesort.c */
	Relation	index;
58
	bool		isunique;
59
};
60

61
/*
B
Bruce Momjian 已提交
62
 * Status record for a btree page being built.	We have one of these
63
 * for each active tree level.
64 65 66 67 68 69 70 71 72
 *
 * The reason we need to store a copy of the minimum key is that we'll
 * need to propagate it to the parent node when this page is linked
 * into its parent.  However, if the page is not a leaf page, the first
 * entry on the page doesn't need to contain a key, so we will not have
 * stored the key itself on the page.  (You might think we could skip
 * copying the minimum key on leaf pages, but actually we must have a
 * writable copy anyway because we'll poke the page's address into it
 * before passing it up to the parent...)
73 74 75 76 77
 */
typedef struct BTPageState
{
	Buffer		btps_buf;		/* current buffer & page */
	Page		btps_page;
B
Bruce Momjian 已提交
78 79
	BTItem		btps_minkey;	/* copy of minimum key (first item) on
								 * page */
80
	OffsetNumber btps_lastoff;	/* last item offset loaded */
81
	uint32		btps_level;		/* tree level (0 = leaf) */
B
Bruce Momjian 已提交
82 83 84
	Size		btps_full;		/* "full" if less than this much free
								 * space */
	struct BTPageState *btps_next;		/* link to parent level, if any */
85 86 87
} BTPageState;


88 89 90 91 92 93
#define BTITEMSZ(btitem) \
	((btitem) ? \
	 (IndexTupleDSize((btitem)->bti_itup) + \
	  (sizeof(BTItemData) - sizeof(IndexTupleData))) : \
	 0)

94

95 96 97
static void _bt_blnewpage(Relation index, Buffer *buf, Page *page,
						  uint32 level);
static BTPageState *_bt_pagestate(Relation index, uint32 level);
98 99
static void _bt_slideleft(Relation index, Buffer buf, Page page);
static void _bt_sortaddtup(Page page, Size itemsize,
B
Bruce Momjian 已提交
100
			   BTItem btitem, OffsetNumber itup_off);
101
static void _bt_buildadd(Relation index, BTPageState *state, BTItem bti);
102
static void _bt_uppershutdown(Relation index, BTPageState *state);
103
static void _bt_load(Relation index, BTSpool *btspool, BTSpool *btspool2);
104

105 106

/*
107
 * Interface routines
108 109 110 111
 */


/*
112
 * create and initialize a spool structure
113
 */
114
BTSpool *
115
_bt_spoolinit(Relation index, bool isunique)
116
{
117
	BTSpool    *btspool = (BTSpool *) palloc0(sizeof(BTSpool));
118

119 120
	btspool->index = index;
	btspool->isunique = isunique;
121

122
	btspool->sortstate = tuplesort_begin_index(index, isunique, false);
123

124
	/*
125 126 127
	 * Currently, tuplesort provides sort functions on IndexTuples. If we
	 * kept anything in a BTItem other than a regular IndexTuple, we'd
	 * need to modify tuplesort to understand BTItems as such.
128 129
	 */
	Assert(sizeof(BTItemData) == sizeof(IndexTupleData));
130

131
	return btspool;
132 133 134 135 136 137
}

/*
 * clean up a spool structure and its substructures.
 */
void
138
_bt_spooldestroy(BTSpool *btspool)
139
{
140
	tuplesort_end(btspool->sortstate);
141
	pfree((void *) btspool);
142 143 144
}

/*
145
 * spool a btitem into the sort file.
146
 */
147 148
void
_bt_spool(BTItem btitem, BTSpool *btspool)
149
{
150 151
	/* A BTItem is really just an IndexTuple */
	tuplesort_puttuple(btspool->sortstate, (void *) btitem);
152 153 154
}

/*
155 156
 * given a spool loaded by successive calls to _bt_spool,
 * create an entire btree.
157
 */
158
void
159
_bt_leafbuild(BTSpool *btspool, BTSpool *btspool2)
160
{
161
#ifdef BTREE_BUILD_STATS
162
	if (log_btree_build_stats)
163
	{
164
		ShowUsage("BTREE BUILD (Spool) STATISTICS");
165
		ResetUsage();
166
	}
167
#endif   /* BTREE_BUILD_STATS */
168

169
	tuplesort_performsort(btspool->sortstate);
170 171 172
	if (btspool2)
		tuplesort_performsort(btspool2->sortstate);
	_bt_load(btspool->index, btspool, btspool2);
173 174 175 176
}


/*
177
 * Internal routines.
178
 */
179

180 181 182 183 184

/*
 * allocate a new, clean btree page, not linked to any siblings.
 */
static void
185
_bt_blnewpage(Relation index, Buffer *buf, Page *page, uint32 level)
186
{
187
	BTPageOpaque opaque;
188

189 190
	*buf = _bt_getbuf(index, P_NEW, BT_WRITE);
	*page = BufferGetPage(*buf);
191 192

	/* Zero the page and set up standard page header info */
193
	_bt_pageinit(*page, BufferGetPageSize(*buf));
194 195

	/* Initialize BT opaque state */
196 197
	opaque = (BTPageOpaque) PageGetSpecialPointer(*page);
	opaque->btpo_prev = opaque->btpo_next = P_NONE;
198 199
	opaque->btpo.level = level;
	opaque->btpo_flags = (level > 0) ? 0 : BTP_LEAF;
200 201 202

	/* Make the P_HIKEY line pointer appear allocated */
	((PageHeader) *page)->pd_lower += sizeof(ItemIdData);
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
/*
 * emit a completed btree page, and release the lock and pin on it.
 * This is essentially _bt_wrtbuf except we also emit a WAL record.
 */
static void
_bt_blwritepage(Relation index, Buffer buf)
{
	Page		pg = BufferGetPage(buf);

	/* NO ELOG(ERROR) from here till newpage op is logged */
	START_CRIT_SECTION();

	/* XLOG stuff */
	if (!index->rd_istemp)
	{
		xl_btree_newpage xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];

		xlrec.node = index->rd_node;
		xlrec.blkno = BufferGetBlockNumber(buf);

		rdata[0].buffer = InvalidBuffer;
		rdata[0].data = (char *) &xlrec;
		rdata[0].len = SizeOfBtreeNewpage;
		rdata[0].next = &(rdata[1]);

		rdata[1].buffer = buf;
		rdata[1].data = (char *) pg;
		rdata[1].len = BLCKSZ;
		rdata[1].next = NULL;

		recptr = XLogInsert(RM_BTREE_ID, XLOG_BTREE_NEWPAGE, rdata);

		PageSetLSN(pg, recptr);
		PageSetSUI(pg, ThisStartUpID);
	}

	END_CRIT_SECTION();

	_bt_wrtbuf(index, buf);
}

248 249 250 251 252
/*
 * allocate and initialize a new BTPageState.  the returned structure
 * is suitable for immediate use by _bt_buildadd.
 */
static BTPageState *
253
_bt_pagestate(Relation index, uint32 level)
254
{
255
	BTPageState *state = (BTPageState *) palloc0(sizeof(BTPageState));
256 257

	/* create initial page */
258
	_bt_blnewpage(index, &(state->btps_buf), &(state->btps_page), level);
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

	state->btps_minkey = (BTItem) NULL;
	/* initialize lastoff so first item goes into P_FIRSTKEY */
	state->btps_lastoff = P_HIKEY;
	state->btps_level = level;
	/* set "full" threshold based on level.  See notes at head of file. */
	if (level > 0)
		state->btps_full = (PageGetPageSize(state->btps_page) * 3) / 10;
	else
		state->btps_full = PageGetPageSize(state->btps_page) / 10;
	/* no parent level, yet */
	state->btps_next = (BTPageState *) NULL;

	return state;
}

275 276
/*
 * slide an array of ItemIds back one slot (from P_FIRSTKEY to
277 278 279
 * P_HIKEY, overwriting P_HIKEY).  we need to do this when we discover
 * that we have built an ItemId array in what has turned out to be a
 * P_RIGHTMOST page.
280 281 282 283
 */
static void
_bt_slideleft(Relation index, Buffer buf, Page page)
{
284 285 286 287
	OffsetNumber off;
	OffsetNumber maxoff;
	ItemId		previi;
	ItemId		thisii;
288 289 290 291 292 293 294 295 296 297 298 299

	if (!PageIsEmpty(page))
	{
		maxoff = PageGetMaxOffsetNumber(page);
		previi = PageGetItemId(page, P_HIKEY);
		for (off = P_FIRSTKEY; off <= maxoff; off = OffsetNumberNext(off))
		{
			thisii = PageGetItemId(page, off);
			*previi = *thisii;
			previi = thisii;
		}
		((PageHeader) page)->pd_lower -= sizeof(ItemIdData);
300
	}
301 302
}

303
/*
304 305 306 307 308 309 310 311 312 313 314
 * Add an item to a page being built.
 *
 * The main difference between this routine and a bare PageAddItem call
 * is that this code knows that the leftmost data item on a non-leaf
 * btree page doesn't need to have a key.  Therefore, it strips such
 * items down to just the item header.
 *
 * This is almost like nbtinsert.c's _bt_pgaddtup(), but we can't use
 * that because it assumes that P_RIGHTMOST() will return the correct
 * answer for the page.  Here, we don't know yet if the page will be
 * rightmost.  Offset P_FIRSTKEY is always the first data key.
315
 */
316 317 318 319 320
static void
_bt_sortaddtup(Page page,
			   Size itemsize,
			   BTItem btitem,
			   OffsetNumber itup_off)
321
{
322
	BTPageOpaque opaque = (BTPageOpaque) PageGetSpecialPointer(page);
B
Bruce Momjian 已提交
323
	BTItemData	truncitem;
324

B
Bruce Momjian 已提交
325
	if (!P_ISLEAF(opaque) && itup_off == P_FIRSTKEY)
326 327 328 329 330 331
	{
		memcpy(&truncitem, btitem, sizeof(BTItemData));
		truncitem.bti_itup.t_info = sizeof(BTItemData);
		btitem = &truncitem;
		itemsize = sizeof(BTItemData);
	}
332

333 334
	if (PageAddItem(page, (Item) btitem, itemsize, itup_off,
					LP_USED) == InvalidOffsetNumber)
335
		elog(ERROR, "failed to add item to the index page");
336 337
}

338 339
/*----------
 * Add an item to a disk page from the sort output.
340
 *
341 342 343
 * We must be careful to observe the page layout conventions of nbtsearch.c:
 * - rightmost pages start data items at P_HIKEY instead of at P_FIRSTKEY.
 * - on non-leaf pages, the key portion of the first item need not be
B
Bruce Momjian 已提交
344
 *	 stored, we should store only the link.
345
 *
346
 * A leaf page being built looks like:
347 348
 *
 * +----------------+---------------------------------+
349
 * | PageHeaderData | linp0 linp1 linp2 ...			  |
350
 * +-----------+----+---------------------------------+
351
 * | ... linpN |									  |
352
 * +-----------+--------------------------------------+
353 354
 * |	 ^ last										  |
 * |												  |
355
 * +-------------+------------------------------------+
356
 * |			 | itemN ...						  |
357
 * +-------------+------------------+-----------------+
358
 * |		  ... item3 item2 item1 | "special space" |
359 360
 * +--------------------------------+-----------------+
 *
361 362
 * Contrast this with the diagram in bufpage.h; note the mismatch
 * between linps and items.  This is because we reserve linp0 as a
363 364
 * placeholder for the pointer to the "high key" item; when we have
 * filled up the page, we will set linp0 to point to itemN and clear
365 366
 * linpN.  On the other hand, if we find this is the last (rightmost)
 * page, we leave the items alone and slide the linp array over.
367
 *
368
 * 'last' pointer indicates the last offset added to the page.
369
 *----------
370
 */
371
static void
372
_bt_buildadd(Relation index, BTPageState *state, BTItem bti)
373
{
374 375 376 377 378
	Buffer		nbuf;
	Page		npage;
	OffsetNumber last_off;
	Size		pgspc;
	Size		btisz;
379 380 381 382 383 384 385

	nbuf = state->btps_buf;
	npage = state->btps_page;
	last_off = state->btps_lastoff;

	pgspc = PageGetFreeSpace(npage);
	btisz = BTITEMSZ(bti);
386
	btisz = MAXALIGN(btisz);
387 388

	/*
389 390 391 392 393
	 * Check whether the item can fit on a btree page at all. (Eventually,
	 * we ought to try to apply TOAST methods if not.) We actually need to
	 * be able to fit three items on every page, so restrict any one item
	 * to 1/3 the per-page available space. Note that at this point, btisz
	 * doesn't include the ItemId.
394 395
	 *
	 * NOTE: similar code appears in _bt_insertonpg() to defend against
396 397
	 * oversize items being inserted into an already-existing index. But
	 * during creation of an index, we don't go through there.
398
	 */
399
	if (btisz > BTMaxItemSize(npage))
400 401 402 403 404
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("index tuple size %lu exceeds btree maximum, %lu",
						(unsigned long) btisz,
						(unsigned long) BTMaxItemSize(npage))));
405

406
	if (pgspc < btisz || pgspc < state->btps_full)
407
	{
408
		/*
409 410
		 * Item won't fit on this page, or we feel the page is full enough
		 * already.  Finish off the page and write it out.
411
		 */
412 413 414 415
		Buffer		obuf = nbuf;
		Page		opage = npage;
		ItemId		ii;
		ItemId		hii;
416
		BTItem		obti;
417

418 419
		/* Create new page on same level */
		_bt_blnewpage(index, &nbuf, &npage, state->btps_level);
420 421

		/*
422 423
		 * We copy the last item on the page into the new page, and then
		 * rearrange the old page so that the 'last item' becomes its high
424 425 426 427
		 * key rather than a true data item.  There had better be at least
		 * two items on the page already, else the page would be empty of
		 * useful data.  (Hence, we must allow pages to be packed at least
		 * 2/3rds full; the 70% figure used above is close to minimum.)
428
		 */
429
		Assert(last_off > P_FIRSTKEY);
430
		ii = PageGetItemId(opage, last_off);
431 432
		obti = (BTItem) PageGetItem(opage, ii);
		_bt_sortaddtup(npage, ItemIdGetLength(ii), obti, P_FIRSTKEY);
433

434
		/*
435
		 * Move 'last' into the high key position on opage
436 437 438 439 440
		 */
		hii = PageGetItemId(opage, P_HIKEY);
		*hii = *ii;
		ii->lp_flags &= ~LP_USED;
		((PageHeader) opage)->pd_lower -= sizeof(ItemIdData);
441

442
		/*
B
Bruce Momjian 已提交
443 444 445
		 * Link the old buffer into its parent, using its minimum key. If
		 * we don't have a parent, we have to create one; this adds a new
		 * btree level.
446
		 */
447
		if (state->btps_next == (BTPageState *) NULL)
448 449
			state->btps_next = _bt_pagestate(index, state->btps_level + 1);

450 451 452 453 454
		Assert(state->btps_minkey != NULL);
		ItemPointerSet(&(state->btps_minkey->bti_itup.t_tid),
					   BufferGetBlockNumber(obuf), P_HIKEY);
		_bt_buildadd(index, state->btps_next, state->btps_minkey);
		pfree((void *) state->btps_minkey);
455

456
		/*
457
		 * Save a copy of the minimum key for the new page.  We have to
B
Bruce Momjian 已提交
458 459
		 * copy it off the old page, not the new one, in case we are not
		 * at leaf level.
460 461 462 463
		 */
		state->btps_minkey = _bt_formitem(&(obti->bti_itup));

		/*
464
		 * Set the sibling links for both pages.
465 466
		 */
		{
467 468
			BTPageOpaque oopaque = (BTPageOpaque) PageGetSpecialPointer(opage);
			BTPageOpaque nopaque = (BTPageOpaque) PageGetSpecialPointer(npage);
469 470 471

			oopaque->btpo_next = BufferGetBlockNumber(nbuf);
			nopaque->btpo_prev = BufferGetBlockNumber(obuf);
472
			nopaque->btpo_next = P_NONE; /* redundant */
473 474 475
		}

		/*
B
Bruce Momjian 已提交
476
		 * Write out the old page.	We never want to see it again, so we
477
		 * can give up our lock.
478
		 */
479
		_bt_blwritepage(index, obuf);
480 481

		/*
482
		 * Reset last_off to point to new page
483
		 */
484
		last_off = P_FIRSTKEY;
485 486
	}

487
	/*
488 489
	 * If the new item is the first for its page, stash a copy for later.
	 * Note this will only happen for the first item on a level; on later
B
Bruce Momjian 已提交
490 491
	 * pages, the first item for a page is copied from the prior page in
	 * the code above.
492
	 */
493
	if (last_off == P_HIKEY)
494
	{
495 496
		Assert(state->btps_minkey == NULL);
		state->btps_minkey = _bt_formitem(&(bti->bti_itup));
497
	}
498 499 500 501 502 503

	/*
	 * Add the new item into the current page.
	 */
	last_off = OffsetNumberNext(last_off);
	_bt_sortaddtup(npage, btisz, bti, last_off);
504 505 506 507

	state->btps_buf = nbuf;
	state->btps_page = npage;
	state->btps_lastoff = last_off;
508 509
}

510 511 512
/*
 * Finish writing out the completed btree.
 */
513
static void
514
_bt_uppershutdown(Relation index, BTPageState *state)
515
{
516
	BTPageState *s;
517

518 519 520
	/*
	 * Each iteration of this loop completes one more level of the tree.
	 */
521 522
	for (s = state; s != (BTPageState *) NULL; s = s->btps_next)
	{
523 524 525
		BlockNumber blkno;
		BTPageOpaque opaque;

526 527
		blkno = BufferGetBlockNumber(s->btps_buf);
		opaque = (BTPageOpaque) PageGetSpecialPointer(s->btps_page);
528

529
		/*
530 531 532 533
		 * We have to link the last page on this level to somewhere.
		 *
		 * If we're at the top, it's the root, so attach it to the metapage.
		 * Otherwise, add an entry for it to its parent using its minimum
B
Bruce Momjian 已提交
534 535
		 * key.  This may cause the last page of the parent level to
		 * split, but that's not a problem -- we haven't gotten to it yet.
536
		 */
537
		if (s->btps_next == (BTPageState *) NULL)
538
		{
539
			opaque->btpo_flags |= BTP_ROOT;
540
			_bt_metaproot(index, blkno, s->btps_level);
541 542 543
		}
		else
		{
544 545 546 547 548 549
			Assert(s->btps_minkey != NULL);
			ItemPointerSet(&(s->btps_minkey->bti_itup.t_tid),
						   blkno, P_HIKEY);
			_bt_buildadd(index, s->btps_next, s->btps_minkey);
			pfree((void *) s->btps_minkey);
			s->btps_minkey = NULL;
550
		}
551

552
		/*
553
		 * This is the rightmost page, so the ItemId array needs to be
B
Bruce Momjian 已提交
554
		 * slid back one slot.	Then we can dump out the page.
555 556
		 */
		_bt_slideleft(index, s->btps_buf, s->btps_page);
557
		_bt_blwritepage(index, s->btps_buf);
558
	}
559 560 561
}

/*
562 563
 * Read tuples in correct sort order from tuplesort, and load them into
 * btree leaves.
564
 */
565
static void
566
_bt_load(Relation index, BTSpool *btspool, BTSpool *btspool2)
567
{
568
	BTPageState *state = NULL;
569
	bool		merge = (btspool2 != NULL);
B
Bruce Momjian 已提交
570 571 572 573 574
	BTItem		bti,
				bti2 = NULL;
	bool		should_free,
				should_free2,
				load1;
575
	TupleDesc	tupdes = RelationGetDescr(index);
B
Bruce Momjian 已提交
576 577
	int			i,
				keysz = RelationGetNumberOfAttributes(index);
578 579 580
	ScanKey		indexScanKey = NULL;

	if (merge)
581
	{
582
		/*
B
Bruce Momjian 已提交
583 584 585 586 587 588 589 590 591
		 * Another BTSpool for dead tuples exists. Now we have to merge
		 * btspool and btspool2.
		 */
		ScanKey		entry;
		Datum		attrDatum1,
					attrDatum2;
		bool		isFirstNull,
					isSecondNull;
		int32		compare;
592 593 594 595 596 597 598

		/* the preparation of merge */
		bti = (BTItem) tuplesort_getindextuple(btspool->sortstate, true, &should_free);
		bti2 = (BTItem) tuplesort_getindextuple(btspool2->sortstate, true, &should_free2);
		indexScanKey = _bt_mkscankey_nodata(index);
		for (;;)
		{
B
Bruce Momjian 已提交
599
			load1 = true;		/* load BTSpool next ? */
600 601 602 603 604 605 606 607 608 609 610
			if (NULL == bti2)
			{
				if (NULL == bti)
					break;
			}
			else if (NULL != bti)
			{

				for (i = 1; i <= keysz; i++)
				{
					entry = indexScanKey + i - 1;
B
Bruce Momjian 已提交
611 612
					attrDatum1 = index_getattr((IndexTuple) bti, i, tupdes, &isFirstNull);
					attrDatum2 = index_getattr((IndexTuple) bti2, i, tupdes, &isSecondNull);
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
					if (isFirstNull)
					{
						if (!isSecondNull)
						{
							load1 = false;
							break;
						}
					}
					else if (isSecondNull)
						break;
					else
					{
						compare = DatumGetInt32(FunctionCall2(&entry->sk_func, attrDatum1, attrDatum2));
						if (compare > 0)
						{
							load1 = false;
							break;
						}
						else if (compare < 0)
							break;
B
Bruce Momjian 已提交
633
					}
634 635 636 637 638 639 640
				}
			}
			else
				load1 = false;

			/* When we see first tuple, create first index page */
			if (state == NULL)
641
				state = _bt_pagestate(index, 0);
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

			if (load1)
			{
				_bt_buildadd(index, state, bti);
				if (should_free)
					pfree((void *) bti);
				bti = (BTItem) tuplesort_getindextuple(btspool->sortstate, true, &should_free);
			}
			else
			{
				_bt_buildadd(index, state, bti2);
				if (should_free2)
					pfree((void *) bti2);
				bti2 = (BTItem) tuplesort_getindextuple(btspool2->sortstate, true, &should_free2);
			}
		}
		_bt_freeskey(indexScanKey);
	}
B
Bruce Momjian 已提交
660
	else
661
	{
662
		/* merge is unnecessary */
663 664 665 666
		while (bti = (BTItem) tuplesort_getindextuple(btspool->sortstate, true, &should_free), bti != (BTItem) NULL)
		{
			/* When we see first tuple, create first index page */
			if (state == NULL)
667
				state = _bt_pagestate(index, 0);
668

669 670 671 672
			_bt_buildadd(index, state, bti);
			if (should_free)
				pfree((void *) bti);
		}
673
	}
674

675
	/* Close down final pages, if we had any data at all */
676 677
	if (state != NULL)
		_bt_uppershutdown(index, state);
678
}