heapam.c 43.2 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * heapam.c
4
 *	  heap access method code
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/access/heap/heapam.c,v 1.57 1999/10/30 23:10:21 tgl Exp $
11 12 13
 *
 *
 * INTERFACE ROUTINES
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *		heapgettup		- fetch next heap tuple from a scan
 *		heap_open		- open a heap relation by relationId
 *		heap_openr		- open a heap relation by name
 *		heap_close		- close a heap relation
 *		heap_beginscan	- begin relation scan
 *		heap_rescan		- restart a relation scan
 *		heap_endscan	- end relation scan
 *		heap_getnext	- retrieve next tuple in scan
 *		heap_fetch		- retrive tuple with tid
 *		heap_insert		- insert tuple into a relation
 *		heap_delete		- delete a tuple from a relation
 *		heap_replace	- replace a tuple in a relation with another tuple
 *		heap_markpos	- mark scan position
 *		heap_restrpos	- restore position to marked location
 *
29
 * NOTES
30 31 32
 *	  This file contains the heap_ routines which implement
 *	  the POSTGRES heap access method used for all POSTGRES
 *	  relations.
33 34
 *
 * OLD COMMENTS
35
 *		struct relscan hints:  (struct should be made AM independent?)
36
 *
37 38 39 40
 *		rs_ctid is the tid of the last tuple returned by getnext.
 *		rs_ptid and rs_ntid are the tids of the previous and next tuples
 *		returned by getnext, respectively.	NULL indicates an end of
 *		scan (either direction); NON indicates an unknow value.
41
 *
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 *		possible combinations:
 *		rs_p	rs_c	rs_n			interpretation
 *		NULL	NULL	NULL			empty scan
 *		NULL	NULL	NON				at begining of scan
 *		NULL	NULL	t1				at begining of scan (with cached tid)
 *		NON		NULL	NULL			at end of scan
 *		t1		NULL	NULL			at end of scan (with cached tid)
 *		NULL	t1		NULL			just returned only tuple
 *		NULL	t1		NON				just returned first tuple
 *		NULL	t1		t2				returned first tuple (with cached tid)
 *		NON		t1		NULL			just returned last tuple
 *		t2		t1		NULL			returned last tuple (with cached tid)
 *		t1		t2		NON				in the middle of a forward scan
 *		NON		t2		t1				in the middle of a reverse scan
 *		ti		tj		tk				in the middle of a scan (w cached tid)
57
 *
58 59
 *		Here NULL is ...tup == NULL && ...buf == InvalidBuffer,
 *		and NON is ...tup == NULL && ...buf == UnknownBuffer.
60
 *
61 62 63
 *		Currently, the NONTID values are not cached with their actual
 *		values by getnext.	Values may be cached by markpos since it stores
 *		all three tids.
64
 *
65 66
 *		NOTE:  the calls to elog() must stop.  Should decide on an interface
 *		between the general and specific AM calls.
67
 *
68 69 70 71
 *		XXX probably do not need a free tuple routine for heaps.
 *		Huh?  Free tuple is not necessary for tuples returned by scans, but
 *		is necessary for tuples which are returned by
 *		RelationGetTupleByItemPointer. -hirohama
72 73 74 75
 *
 *-------------------------------------------------------------------------
 */

76
#include "postgres.h"
77

78 79
#include "access/heapam.h"
#include "access/hio.h"
B
Bruce Momjian 已提交
80
#include "access/valid.h"
81
#include "catalog/catalog.h"
B
Bruce Momjian 已提交
82 83
#include "miscadmin.h"
#include "storage/smgr.h"
84
#include "utils/builtins.h"
B
Bruce Momjian 已提交
85 86
#include "utils/inval.h"
#include "utils/relcache.h"
87

M
-Wall'd  
Marc G. Fournier 已提交
88

89
/* ----------------------------------------------------------------
90
 *						 heap support routines
91 92 93 94
 * ----------------------------------------------------------------
 */

/* ----------------
95
 *		initscan - scan code common to heap_beginscan and heap_rescan
96 97 98
 * ----------------
 */
static void
99
initscan(HeapScanDesc scan,
100 101 102 103
		 Relation relation,
		 int atend,
		 unsigned nkeys,
		 ScanKey key)
104
{
105 106 107 108 109 110 111 112 113 114
	/* ----------------
	 *	Make sure we have up-to-date idea of number of blocks in relation.
	 *	It is sufficient to do this once at scan start, since any tuples
	 *	added while the scan is in progress will be invisible to my
	 *	transaction anyway...
	 * ----------------
	 */
	relation->rd_nblocks = RelationGetNumberOfBlocks(relation);

	if (relation->rd_nblocks == 0)
115 116 117 118 119
	{
		/* ----------------
		 *	relation is empty
		 * ----------------
		 */
B
Bruce Momjian 已提交
120
		scan->rs_ntup.t_data = scan->rs_ctup.t_data =
121
		scan->rs_ptup.t_data = NULL;
122
		scan->rs_nbuf = scan->rs_cbuf = scan->rs_pbuf = InvalidBuffer;
123 124 125 126 127 128 129
	}
	else if (atend)
	{
		/* ----------------
		 *	reverse scan
		 * ----------------
		 */
130
		scan->rs_ntup.t_data = scan->rs_ctup.t_data = NULL;
131
		scan->rs_nbuf = scan->rs_cbuf = InvalidBuffer;
132
		scan->rs_ptup.t_data = NULL;
133
		scan->rs_pbuf = UnknownBuffer;
134 135 136 137 138 139 140
	}
	else
	{
		/* ----------------
		 *	forward scan
		 * ----------------
		 */
141
		scan->rs_ctup.t_data = scan->rs_ptup.t_data = NULL;
142
		scan->rs_cbuf = scan->rs_pbuf = InvalidBuffer;
143
		scan->rs_ntup.t_data = NULL;
144
		scan->rs_nbuf = UnknownBuffer;
145 146 147
	}							/* invalid too */

	/* we don't have a marked position... */
148 149 150 151
	ItemPointerSetInvalid(&(scan->rs_mptid));
	ItemPointerSetInvalid(&(scan->rs_mctid));
	ItemPointerSetInvalid(&(scan->rs_mntid));
	ItemPointerSetInvalid(&(scan->rs_mcd));
152

153
	/* ----------------
154
	 *	copy the scan key, if appropriate
155 156
	 * ----------------
	 */
157
	if (key != NULL)
158
		memmove(scan->rs_key, key, nkeys * sizeof(ScanKeyData));
159 160 161
}

/* ----------------
162
 *		unpinscan - code common to heap_rescan and heap_endscan
163 164 165
 * ----------------
 */
static void
166
unpinscan(HeapScanDesc scan)
167
{
168 169
	if (BufferIsValid(scan->rs_pbuf))
		ReleaseBuffer(scan->rs_pbuf);
170 171

	/* ------------------------------------
172
	 *	Scan will pin buffer once for each non-NULL tuple pointer
173 174 175 176
	 *	(ptup, ctup, ntup), so they have to be unpinned multiple
	 *	times.
	 * ------------------------------------
	 */
177 178
	if (BufferIsValid(scan->rs_cbuf))
		ReleaseBuffer(scan->rs_cbuf);
179

180 181
	if (BufferIsValid(scan->rs_nbuf))
		ReleaseBuffer(scan->rs_nbuf);
182 183 184 185

	/* we don't bother to clear rs_pbuf etc --- caller must
	 * reinitialize them if scan descriptor is not being deleted.
	 */
186 187 188
}

/* ------------------------------------------
189
 *		nextpage
190
 *
191 192 193
 *		figure out the next page to scan after the current page
 *		taking into account of possible adjustment of degrees of
 *		parallelism
194 195 196 197 198
 * ------------------------------------------
 */
static int
nextpage(int page, int dir)
{
199
	return (dir < 0) ? page - 1 : page + 1;
200 201 202
}

/* ----------------
203
 *		heapgettup - fetch next heap tuple
204
 *
205 206
 *		routine used by heap_getnext() which does most of the
 *		real work in scanning tuples.
207 208 209 210 211
 *
 *		The scan routines handle their own buffer lock/unlocking, so
 *		there is no reason to request the buffer number unless
 *		to want to perform some other operation with the result,
 *		like pass it to another function.
212 213
 * ----------------
 */
214
static void
215
heapgettup(Relation relation,
216
		   HeapTuple tuple,
217
		   int dir,
V
Vadim B. Mikheev 已提交
218
		   Buffer *buffer,
219
		   Snapshot snapshot,
220 221
		   int nkeys,
		   ScanKey key)
222
{
B
Bruce Momjian 已提交
223 224 225 226 227 228 229 230 231
	ItemId		lpp;
	Page		dp;
	int			page;
	int			pages;
	int			lines;
	OffsetNumber lineoff;
	int			linesleft;
	ItemPointer tid = (tuple->t_data == NULL) ?
	(ItemPointer) NULL : &(tuple->t_self);
232

233
	/* ----------------
234
	 *	increment access statistics
235 236
	 * ----------------
	 */
237 238 239
	IncrHeapAccessStat(local_heapgettup);
	IncrHeapAccessStat(global_heapgettup);

240
	/* ----------------
241 242 243 244
	 *	debugging stuff
	 *
	 * check validity of arguments, here and for other functions too
	 * Note: no locking manipulations needed--this is a local function
245 246
	 * ----------------
	 */
247 248 249
#ifdef	HEAPDEBUGALL
	if (ItemPointerIsValid(tid))
	{
250
		elog(DEBUG, "heapgettup(%s, tid=0x%x[%d,%d], dir=%d, ...)",
251 252
			 RelationGetRelationName(relation), tid, tid->ip_blkid,
			 tid->ip_posid, dir);
253
	}
254 255
	else
	{
256
		elog(DEBUG, "heapgettup(%s, tid=0x%x, dir=%d, ...)",
257
			 RelationGetRelationName(relation), tid, dir);
258
	}
V
Vadim B. Mikheev 已提交
259
	elog(DEBUG, "heapgettup(..., b=0x%x, nkeys=%d, key=0x%x", buffer, nkeys, key);
260

261
	elog(DEBUG, "heapgettup: relation(%c)=`%s', %p",
262
		 relation->rd_rel->relkind, &relation->rd_rel->relname,
263
		 snapshot);
264
#endif	 /* !defined(HEAPDEBUGALL) */
265 266 267

	if (!ItemPointerIsValid(tid))
		Assert(!PointerIsValid(tid));
268 269

	/* ----------------
270
	 *	return null immediately if relation is empty
271 272
	 * ----------------
	 */
273
	if (!(pages = relation->rd_nblocks))
274 275 276 277
	{
		tuple->t_data = NULL;
		return;
	}
278 279 280 281 282 283 284 285 286 287 288 289 290 291

	/* ----------------
	 *	calculate next starting lineoff, given scan direction
	 * ----------------
	 */
	if (!dir)
	{
		/* ----------------
		 * ``no movement'' scan direction
		 * ----------------
		 */
		/* assume it is a valid TID XXX */
		if (ItemPointerIsValid(tid) == false)
		{
V
Vadim B. Mikheev 已提交
292
			*buffer = InvalidBuffer;
293 294
			tuple->t_data = NULL;
			return;
295
		}
V
Vadim B. Mikheev 已提交
296
		*buffer = RelationGetBufferWithBuffer(relation,
B
Bruce Momjian 已提交
297 298
										  ItemPointerGetBlockNumber(tid),
											  *buffer);
299

V
Vadim B. Mikheev 已提交
300
		if (!BufferIsValid(*buffer))
301
			elog(ERROR, "heapgettup: failed ReadBuffer");
302

V
Vadim B. Mikheev 已提交
303 304 305
		LockBuffer(*buffer, BUFFER_LOCK_SHARE);

		dp = (Page) BufferGetPage(*buffer);
306 307 308
		lineoff = ItemPointerGetOffsetNumber(tid);
		lpp = PageGetItemId(dp, lineoff);

309 310
		tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
		tuple->t_len = ItemIdGetLength(lpp);
V
Vadim B. Mikheev 已提交
311
		LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
312
		return;
313

314
	}
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
	else if (dir < 0)
	{
		/* ----------------
		 *	reverse scan direction
		 * ----------------
		 */
		if (ItemPointerIsValid(tid) == false)
			tid = NULL;
		if (tid == NULL)
		{
			page = pages - 1;	/* final page */
		}
		else
		{
			page = ItemPointerGetBlockNumber(tid);		/* current page */
		}
		if (page < 0)
		{
V
Vadim B. Mikheev 已提交
333
			*buffer = InvalidBuffer;
334 335
			tuple->t_data = NULL;
			return;
336 337
		}

V
Vadim B. Mikheev 已提交
338 339
		*buffer = RelationGetBufferWithBuffer(relation, page, *buffer);
		if (!BufferIsValid(*buffer))
340
			elog(ERROR, "heapgettup: failed ReadBuffer");
341

V
Vadim B. Mikheev 已提交
342 343 344
		LockBuffer(*buffer, BUFFER_LOCK_SHARE);

		dp = (Page) BufferGetPage(*buffer);
345 346 347 348
		lines = PageGetMaxOffsetNumber(dp);
		if (tid == NULL)
		{
			lineoff = lines;	/* final offnum */
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
		else
		{
			lineoff =			/* previous offnum */
				OffsetNumberPrev(ItemPointerGetOffsetNumber(tid));
		}
		/* page and lineoff now reference the physically previous tid */

	}
	else
	{
		/* ----------------
		 *	forward scan direction
		 * ----------------
		 */
		if (ItemPointerIsValid(tid) == false)
		{
			page = 0;			/* first page */
			lineoff = FirstOffsetNumber;		/* first offnum */
		}
		else
		{
			page = ItemPointerGetBlockNumber(tid);		/* current page */
			lineoff =			/* next offnum */
				OffsetNumberNext(ItemPointerGetOffsetNumber(tid));
		}

		if (page >= pages)
		{
V
Vadim B. Mikheev 已提交
378
			*buffer = InvalidBuffer;
379 380
			tuple->t_data = NULL;
			return;
381 382 383
		}
		/* page and lineoff now reference the physically next tid */

V
Vadim B. Mikheev 已提交
384 385
		*buffer = RelationGetBufferWithBuffer(relation, page, *buffer);
		if (!BufferIsValid(*buffer))
386
			elog(ERROR, "heapgettup: failed ReadBuffer");
387

V
Vadim B. Mikheev 已提交
388 389 390
		LockBuffer(*buffer, BUFFER_LOCK_SHARE);

		dp = (Page) BufferGetPage(*buffer);
391
		lines = PageGetMaxOffsetNumber(dp);
392
	}
393 394 395

	/* 'dir' is now non-zero */

396
	/* ----------------
397 398
	 *	calculate line pointer and number of remaining items
	 *	to check on this page.
399 400
	 * ----------------
	 */
401 402 403 404 405 406
	lpp = PageGetItemId(dp, lineoff);
	if (dir < 0)
		linesleft = lineoff - 1;
	else
		linesleft = lines - lineoff;

407
	/* ----------------
408 409
	 *	advance the scan until we find a qualifying tuple or
	 *	run out of stuff to scan
410 411
	 * ----------------
	 */
412 413 414 415
	for (;;)
	{
		while (linesleft >= 0)
		{
416
			if (ItemIdIsUsed(lpp))
417
			{
418 419 420 421 422 423 424
				tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);
				tuple->t_len = ItemIdGetLength(lpp);
				ItemPointerSet(&(tuple->t_self), page, lineoff);
				/* ----------------
				 *	if current tuple qualifies, return it.
				 * ----------------
				 */
V
Vadim B. Mikheev 已提交
425
				HeapTupleSatisfies(tuple, relation, *buffer, (PageHeader) dp,
426 427
								   snapshot, nkeys, key);
				if (tuple->t_data != NULL)
V
Vadim B. Mikheev 已提交
428 429
				{
					LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
430
					return;
V
Vadim B. Mikheev 已提交
431
				}
432 433 434 435 436 437 438 439 440 441
			}

			/* ----------------
			 *	otherwise move to the next item on the page
			 * ----------------
			 */
			--linesleft;
			if (dir < 0)
			{
				--lpp;			/* move back in this page's ItemId array */
442
				--lineoff;
443 444 445
			}
			else
			{
B
Bruce Momjian 已提交
446 447
				++lpp;			/* move forward in this page's ItemId
								 * array */
448
				++lineoff;
449 450 451 452 453 454 455 456
			}
		}

		/* ----------------
		 *	if we get here, it means we've exhausted the items on
		 *	this page and it's time to move to the next..
		 * ----------------
		 */
V
Vadim B. Mikheev 已提交
457
		LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
458 459 460 461 462 463 464 465
		page = nextpage(page, dir);

		/* ----------------
		 *	return NULL if we've exhausted all the pages..
		 * ----------------
		 */
		if (page < 0 || page >= pages)
		{
V
Vadim B. Mikheev 已提交
466 467 468
			if (BufferIsValid(*buffer))
				ReleaseBuffer(*buffer);
			*buffer = InvalidBuffer;
469 470
			tuple->t_data = NULL;
			return;
471 472
		}

V
Vadim B. Mikheev 已提交
473
		*buffer = ReleaseAndReadBuffer(*buffer, relation, page);
474

V
Vadim B. Mikheev 已提交
475
		if (!BufferIsValid(*buffer))
476
			elog(ERROR, "heapgettup: failed ReadBuffer");
V
Vadim B. Mikheev 已提交
477 478
		LockBuffer(*buffer, BUFFER_LOCK_SHARE);
		dp = (Page) BufferGetPage(*buffer);
479
		lines = PageGetMaxOffsetNumber((Page) dp);
480 481
		linesleft = lines - 1;
		if (dir < 0)
482 483 484 485
		{
			lineoff = lines;
			lpp = PageGetItemId(dp, lines);
		}
486
		else
487 488
		{
			lineoff = FirstOffsetNumber;
489
			lpp = PageGetItemId(dp, FirstOffsetNumber);
490
		}
491 492 493 494 495
	}
}


/* ----------------------------------------------------------------
496
 *					 heap access method interface
497 498 499
 * ----------------------------------------------------------------
 */
/* ----------------
500
 *		heap_open - open a heap relation by relationId
501
 *
502 503 504 505 506
 *		If lockmode is "NoLock", no lock is obtained on the relation,
 *		and the caller must check for a NULL return value indicating
 *		that no such relation exists.
 *		Otherwise, an error is raised if the relation does not exist,
 *		and the specified kind of lock is obtained on the relation.
507 508 509
 * ----------------
 */
Relation
510
heap_open(Oid relationId, LOCKMODE lockmode)
511
{
512
	Relation	r;
513

514 515
	Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);

516 517 518 519 520 521 522
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_open);
	IncrHeapAccessStat(global_open);

523 524
	/* The relcache does all the real work... */
	r = RelationIdGetRelation(relationId);
525

526
	/* Under no circumstances will we return an index as a relation. */
527
	if (RelationIsValid(r) && r->rd_rel->relkind == RELKIND_INDEX)
528
		elog(ERROR, "%s is an index relation", r->rd_rel->relname.data);
529

530 531 532 533 534 535 536 537
	if (lockmode == NoLock)
		return r;				/* caller must check RelationIsValid! */

	if (! RelationIsValid(r))
		elog(ERROR, "Relation %u does not exist", relationId);

	LockRelation(r, lockmode);

538
	return r;
539 540 541
}

/* ----------------
542
 *		heap_openr - open a heap relation by name
543
 *
544 545 546 547 548
 *		If lockmode is "NoLock", no lock is obtained on the relation,
 *		and the caller must check for a NULL return value indicating
 *		that no such relation exists.
 *		Otherwise, an error is raised if the relation does not exist,
 *		and the specified kind of lock is obtained on the relation.
549 550 551
 * ----------------
 */
Relation
552
heap_openr(char *relationName, LOCKMODE lockmode)
553
{
554
	Relation	r;
555

556 557
	Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);

558 559 560 561 562 563 564
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_openr);
	IncrHeapAccessStat(global_openr);

565
	/* The relcache does all the real work... */
566 567
	r = RelationNameGetRelation(relationName);

568
	/* Under no circumstances will we return an index as a relation. */
569
	if (RelationIsValid(r) && r->rd_rel->relkind == RELKIND_INDEX)
570
		elog(ERROR, "%s is an index relation", r->rd_rel->relname.data);
571

572 573 574 575 576 577 578 579
	if (lockmode == NoLock)
		return r;				/* caller must check RelationIsValid! */

	if (! RelationIsValid(r))
		elog(ERROR, "Relation '%s' does not exist", relationName);

	LockRelation(r, lockmode);

580
	return r;
581 582 583
}

/* ----------------
584
 *		heap_close - close a heap relation
585
 *
586 587 588
 *		If lockmode is not "NoLock", we first release the specified lock.
 *		Note that it is often sensible to hold a lock beyond heap_close;
 *		in that case, the lock is released automatically at xact end.
589 590 591
 * ----------------
 */
void
592
heap_close(Relation relation, LOCKMODE lockmode)
593
{
594 595
	Assert(lockmode >= NoLock && lockmode < MAX_LOCKMODES);

596 597 598 599 600 601 602
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_close);
	IncrHeapAccessStat(global_close);

603 604 605 606
	if (lockmode != NoLock)
		UnlockRelation(relation, lockmode);

	/* The relcache does the real work... */
607
	RelationClose(relation);
608 609 610 611
}


/* ----------------
612
 *		heap_beginscan	- begin relation scan
613 614 615 616
 * ----------------
 */
HeapScanDesc
heap_beginscan(Relation relation,
617
			   int atend,
618
			   Snapshot snapshot,
619 620
			   unsigned nkeys,
			   ScanKey key)
621
{
622
	HeapScanDesc scan;
623 624 625 626 627 628 629 630 631 632 633

	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_beginscan);
	IncrHeapAccessStat(global_beginscan);

	/* ----------------
	 *	sanity checks
	 * ----------------
634
	 */
635
	if (! RelationIsValid(relation))
636
		elog(ERROR, "heap_beginscan: !RelationIsValid(relation)");
637 638 639 640 641 642 643

	/* ----------------
	 *	increment relation ref count while scanning relation
	 * ----------------
	 */
	RelationIncrementReferenceCount(relation);

644 645 646 647 648 649 650 651 652 653 654 655 656 657
	/* ----------------
	 *	Acquire AccessShareLock for the duration of the scan
	 *
	 *	Note: we could get an SI inval message here and consequently have
	 *	to rebuild the relcache entry.  The refcount increment above
	 *	ensures that we will rebuild it and not just flush it...
	 * ----------------
	 */
	LockRelation(relation, AccessShareLock);

	/* XXX someday assert SelfTimeQual if relkind == RELKIND_UNCATALOGED */
	if (relation->rd_rel->relkind == RELKIND_UNCATALOGED)
		snapshot = SnapshotSelf;

658 659 660 661
	/* ----------------
	 *	allocate and initialize scan descriptor
	 * ----------------
	 */
662
	scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
663

664
	scan->rs_rd = relation;
665 666 667
	scan->rs_atend = atend;
	scan->rs_snapshot = snapshot;
	scan->rs_nkeys = (short) nkeys;
668 669 670

	if (nkeys)
		/*
671 672
		 * we do this here instead of in initscan() because heap_rescan
		 * also calls initscan() and we don't want to allocate memory
673 674
		 * again
		 */
675
		scan->rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
676
	else
677
		scan->rs_key = NULL;
678

679
	initscan(scan, relation, atend, nkeys, key);
680

681
	return scan;
682 683 684
}

/* ----------------
685
 *		heap_rescan		- restart a relation scan
686 687 688
 * ----------------
 */
void
689
heap_rescan(HeapScanDesc scan,
690 691
			bool scanFromEnd,
			ScanKey key)
692
{
693 694 695 696 697 698 699 700 701 702 703 704 705
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_rescan);
	IncrHeapAccessStat(global_rescan);

	/* Note: set relation level read lock is still set */

	/* ----------------
	 *	unpin scan buffers
	 * ----------------
	 */
706
	unpinscan(scan);
707 708 709 710 711

	/* ----------------
	 *	reinitialize scan descriptor
	 * ----------------
	 */
712
	scan->rs_atend = (bool) scanFromEnd;
713
	initscan(scan, scan->rs_rd, scanFromEnd, scan->rs_nkeys, key);
714 715 716
}

/* ----------------
717
 *		heap_endscan	- end relation scan
718
 *
719 720
 *		See how to integrate with index scans.
 *		Check handling if reldesc caching.
721 722 723
 * ----------------
 */
void
724
heap_endscan(HeapScanDesc scan)
725
{
726 727 728 729 730 731 732 733 734 735 736 737 738
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_endscan);
	IncrHeapAccessStat(global_endscan);

	/* Note: no locking manipulations needed */

	/* ----------------
	 *	unpin scan buffers
	 * ----------------
	 */
739
	unpinscan(scan);
740

741 742 743 744 745 746
	/* ----------------
	 *	Release AccessShareLock acquired by heap_beginscan()
	 * ----------------
	 */
	UnlockRelation(scan->rs_rd, AccessShareLock);

747 748 749 750
	/* ----------------
	 *	decrement relation reference count and free scan descriptor storage
	 * ----------------
	 */
751
	RelationDecrementReferenceCount(scan->rs_rd);
752

753
	pfree(scan);
754 755 756
}

/* ----------------
757
 *		heap_getnext	- retrieve next tuple in scan
758
 *
759
 *		Fix to work with index relations.
760 761
 *		We don't return the buffer anymore, but you can get it from the
 *		returned HeapTuple.
762 763 764 765 766
 * ----------------
 */

#ifdef HEAPDEBUGALL
#define HEAPDEBUG_1 \
767 768
elog(DEBUG, "heap_getnext([%s,nkeys=%d],backw=%d) called", \
	 scan->rs_rd->rd_rel->relname.data, scan->rs_nkeys, backw)
769

770
#define HEAPDEBUG_2 \
771 772
	 elog(DEBUG, "heap_getnext called with backw (no tracing yet)")

773
#define HEAPDEBUG_3 \
774 775
	 elog(DEBUG, "heap_getnext returns NULL at end")

776
#define HEAPDEBUG_4 \
777 778
	 elog(DEBUG, "heap_getnext valid buffer UNPIN'd")

779
#define HEAPDEBUG_5 \
780 781
	 elog(DEBUG, "heap_getnext next tuple was cached")

782
#define HEAPDEBUG_6 \
783 784
	 elog(DEBUG, "heap_getnext returning EOS")

785
#define HEAPDEBUG_7 \
786
	 elog(DEBUG, "heap_getnext returning tuple");
787 788 789 790 791 792 793 794
#else
#define HEAPDEBUG_1
#define HEAPDEBUG_2
#define HEAPDEBUG_3
#define HEAPDEBUG_4
#define HEAPDEBUG_5
#define HEAPDEBUG_6
#define HEAPDEBUG_7
795
#endif	 /* !defined(HEAPDEBUGALL) */
796 797


798
HeapTuple
799
heap_getnext(HeapScanDesc scandesc, int backw)
800
{
801
	HeapScanDesc scan = scandesc;
802

803
	/* ----------------
804
	 *	increment access statistics
805 806
	 * ----------------
	 */
807 808 809 810 811 812 813 814
	IncrHeapAccessStat(local_getnext);
	IncrHeapAccessStat(global_getnext);

	/* Note: no locking manipulations needed */

	/* ----------------
	 *	argument checks
	 * ----------------
815
	 */
816
	if (scan == NULL)
817
		elog(ERROR, "heap_getnext: NULL relscan");
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

	/* ----------------
	 *	initialize return buffer to InvalidBuffer
	 * ----------------
	 */

	HEAPDEBUG_1;				/* heap_getnext( info ) */

	if (backw)
	{
		/* ----------------
		 *	handle reverse scan
		 * ----------------
		 */
		HEAPDEBUG_2;			/* heap_getnext called with backw */

834
		if (scan->rs_ptup.t_data == scan->rs_ctup.t_data &&
835
			BufferIsInvalid(scan->rs_pbuf))
836
		{
837 838
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
839 840
			scan->rs_ntup.t_data = NULL;
			scan->rs_nbuf = UnknownBuffer;
841
			return NULL;
842 843 844 845 846 847
		}

		/*
		 * Copy the "current" tuple/buffer to "next". Pin/unpin the
		 * buffers accordingly
		 */
848
		if (scan->rs_nbuf != scan->rs_cbuf)
849
		{
850 851 852 853
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
			if (BufferIsValid(scan->rs_cbuf))
				IncrBufferRefCount(scan->rs_cbuf);
854
		}
855 856
		scan->rs_ntup = scan->rs_ctup;
		scan->rs_nbuf = scan->rs_cbuf;
857

858
		if (scan->rs_ptup.t_data != NULL)
859
		{
860
			if (scan->rs_cbuf != scan->rs_pbuf)
861
			{
862 863 864 865
				if (BufferIsValid(scan->rs_cbuf))
					ReleaseBuffer(scan->rs_cbuf);
				if (BufferIsValid(scan->rs_pbuf))
					IncrBufferRefCount(scan->rs_pbuf);
866
			}
867 868
			scan->rs_ctup = scan->rs_ptup;
			scan->rs_cbuf = scan->rs_pbuf;
869 870 871
		}
		else
		{						/* NONTUP */
B
Bruce Momjian 已提交
872

873
			/*
874
			 * Don't release scan->rs_cbuf at this point, because
875 876 877 878 879 880 881
			 * heapgettup doesn't increase PrivateRefCount if it is
			 * already set. On a backward scan, both rs_ctup and rs_ntup
			 * usually point to the same buffer page, so
			 * PrivateRefCount[rs_cbuf] should be 2 (or more, if for
			 * instance ctup is stored in a TupleTableSlot).  - 01/09/94
			 */

882 883 884 885 886 887 888
			heapgettup(scan->rs_rd,
					   &(scan->rs_ctup),
					   -1,
					   &(scan->rs_cbuf),
					   scan->rs_snapshot,
					   scan->rs_nkeys,
					   scan->rs_key);
889 890
		}

891
		if (scan->rs_ctup.t_data == NULL && !BufferIsValid(scan->rs_cbuf))
892
		{
893 894
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
895
			scan->rs_ptup.t_data = NULL;
896 897 898
			scan->rs_pbuf = InvalidBuffer;
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
899
			scan->rs_ntup.t_data = NULL;
900
			scan->rs_nbuf = InvalidBuffer;
901
			return NULL;
902 903
		}

904 905
		if (BufferIsValid(scan->rs_pbuf))
			ReleaseBuffer(scan->rs_pbuf);
906
		scan->rs_ptup.t_data = NULL;
907
		scan->rs_pbuf = UnknownBuffer;
908 909 910 911 912 913 914 915

	}
	else
	{
		/* ----------------
		 *	handle forward scan
		 * ----------------
		 */
916
		if (scan->rs_ctup.t_data == scan->rs_ntup.t_data &&
917
			BufferIsInvalid(scan->rs_nbuf))
918
		{
919 920
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
921 922
			scan->rs_ptup.t_data = NULL;
			scan->rs_pbuf = UnknownBuffer;
923
			HEAPDEBUG_3;		/* heap_getnext returns NULL at end */
924
			return NULL;
925 926 927 928 929 930
		}

		/*
		 * Copy the "current" tuple/buffer to "previous". Pin/unpin the
		 * buffers accordingly
		 */
931
		if (scan->rs_pbuf != scan->rs_cbuf)
932
		{
933 934 935 936
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
			if (BufferIsValid(scan->rs_cbuf))
				IncrBufferRefCount(scan->rs_cbuf);
937
		}
938 939
		scan->rs_ptup = scan->rs_ctup;
		scan->rs_pbuf = scan->rs_cbuf;
940

941
		if (scan->rs_ntup.t_data != NULL)
942
		{
943
			if (scan->rs_cbuf != scan->rs_nbuf)
944
			{
945 946 947 948
				if (BufferIsValid(scan->rs_cbuf))
					ReleaseBuffer(scan->rs_cbuf);
				if (BufferIsValid(scan->rs_nbuf))
					IncrBufferRefCount(scan->rs_nbuf);
949
			}
950 951
			scan->rs_ctup = scan->rs_ntup;
			scan->rs_cbuf = scan->rs_nbuf;
952 953 954 955
			HEAPDEBUG_5;		/* heap_getnext next tuple was cached */
		}
		else
		{						/* NONTUP */
B
Bruce Momjian 已提交
956

957
			/*
958
			 * Don't release scan->rs_cbuf at this point, because
959 960 961 962 963 964 965
			 * heapgettup doesn't increase PrivateRefCount if it is
			 * already set. On a forward scan, both rs_ctup and rs_ptup
			 * usually point to the same buffer page, so
			 * PrivateRefCount[rs_cbuf] should be 2 (or more, if for
			 * instance ctup is stored in a TupleTableSlot).  - 01/09/93
			 */

966 967 968 969 970 971 972
			heapgettup(scan->rs_rd,
					   &(scan->rs_ctup),
					   1,
					   &scan->rs_cbuf,
					   scan->rs_snapshot,
					   scan->rs_nkeys,
					   scan->rs_key);
973 974
		}

975
		if (scan->rs_ctup.t_data == NULL && !BufferIsValid(scan->rs_cbuf))
976
		{
977 978
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
979
			scan->rs_ntup.t_data = NULL;
980 981 982
			scan->rs_nbuf = InvalidBuffer;
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
983
			scan->rs_ptup.t_data = NULL;
984
			scan->rs_pbuf = InvalidBuffer;
985
			HEAPDEBUG_6;		/* heap_getnext returning EOS */
986
			return NULL;
987 988
		}

989 990
		if (BufferIsValid(scan->rs_nbuf))
			ReleaseBuffer(scan->rs_nbuf);
991
		scan->rs_ntup.t_data = NULL;
992
		scan->rs_nbuf = UnknownBuffer;
993 994
	}

995
	/* ----------------
996 997
	 *	if we get here it means we have a new current scan tuple, so
	 *	point to the proper return buffer and return the tuple.
998 999
	 * ----------------
	 */
1000 1001 1002

	HEAPDEBUG_7;				/* heap_getnext returning tuple */

1003
	return ((scan->rs_ctup.t_data == NULL) ? NULL : &(scan->rs_ctup));
1004 1005 1006
}

/* ----------------
1007
 *		heap_fetch		- retrive tuple with tid
1008
 *
1009
 *		Currently ignores LP_IVALID during processing!
1010 1011 1012 1013
 *
 *		Because this is not part of a scan, there is no way to
 *		automatically lock/unlock the shared buffers.
 *		For this reason, we require that the user retrieve the buffer
1014
 *		value, and they are required to BufferRelease() it when they
1015 1016
 *		are done.  If they want to make a copy of it before releasing it,
 *		they can call heap_copytyple().
1017 1018
 * ----------------
 */
1019
void
1020
heap_fetch(Relation relation,
1021
		   Snapshot snapshot,
1022
		   HeapTuple tuple,
1023
		   Buffer *userbuf)
1024
{
B
Bruce Momjian 已提交
1025 1026 1027 1028 1029
	ItemId		lp;
	Buffer		buffer;
	PageHeader	dp;
	ItemPointer tid = &(tuple->t_self);
	OffsetNumber offnum;
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_fetch);
	IncrHeapAccessStat(global_fetch);

	/* ----------------
	 *	get the buffer from the relation descriptor
	 *	Note that this does a buffer pin.
	 * ----------------
	 */

	buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));

	if (!BufferIsValid(buffer))
1047
		elog(ERROR, "heap_fetch: %s relation: ReadBuffer(%lx) failed",
1048
			 &relation->rd_rel->relname, (long) tid);
V
Vadim B. Mikheev 已提交
1049 1050

	LockBuffer(buffer, BUFFER_LOCK_SHARE);
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

	/* ----------------
	 *	get the item line pointer corresponding to the requested tid
	 * ----------------
	 */
	dp = (PageHeader) BufferGetPage(buffer);
	offnum = ItemPointerGetOffsetNumber(tid);
	lp = PageGetItemId(dp, offnum);

	/* ----------------
	 *	more sanity checks
	 * ----------------
	 */

	Assert(ItemIdIsUsed(lp));

1067 1068 1069
	tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
	tuple->t_len = ItemIdGetLength(lp);

1070 1071 1072 1073 1074
	/* ----------------
	 *	check time qualification of tid
	 * ----------------
	 */

1075 1076
	HeapTupleSatisfies(tuple, relation, buffer, dp,
					   snapshot, 0, (ScanKey) NULL);
1077

V
Vadim B. Mikheev 已提交
1078 1079
	LockBuffer(buffer, BUFFER_LOCK_UNLOCK);

1080
	if (tuple->t_data == NULL)
1081
	{
1082
		/* Tuple failed time check, so we can release now. */
1083
		ReleaseBuffer(buffer);
1084 1085 1086 1087 1088 1089 1090 1091
		*userbuf = InvalidBuffer;
	}
	else
	{
		/* All checks passed, so return the tuple as valid.
		 * Caller is now responsible for releasing the buffer.
		 */
		*userbuf = buffer;
1092 1093 1094
	}
}

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
/* ----------------
 *	heap_get_latest_tid -  get the latest tid of a specified tuple
 *
 * ----------------
 */
ItemPointer
heap_get_latest_tid(Relation relation,
		   Snapshot snapshot,
		   ItemPointer tid)
{
1105
	ItemId		lp = NULL;
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
	Buffer		buffer;
	PageHeader	dp;
	OffsetNumber	offnum;
	HeapTupleData	tp;
	HeapTupleHeader	t_data;
	ItemPointerData	ctid;
	bool		invalidBlock,linkend;

	/* ----------------
	 *	get the buffer from the relation descriptor
	 *	Note that this does a buffer pin.
	 * ----------------
	 */

	buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));

	if (!BufferIsValid(buffer))
		elog(ERROR, "heap_get_latest_tid: %s relation: ReadBuffer(%lx) failed",
			 &relation->rd_rel->relname, (long) tid);

	LockBuffer(buffer, BUFFER_LOCK_SHARE);

	/* ----------------
	 *	get the item line pointer corresponding to the requested tid
	 * ----------------
	 */
	dp = (PageHeader) BufferGetPage(buffer);
	offnum = ItemPointerGetOffsetNumber(tid);
	invalidBlock = true;
	if (!PageIsNew(dp))
	{
		lp = PageGetItemId(dp, offnum);
		if (ItemIdIsUsed(lp))
			invalidBlock = false;
	}
	if (invalidBlock)
	{	
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
		ReleaseBuffer(buffer);
		return NULL;
	} 

	/* ----------------
	 *	more sanity checks
	 * ----------------
	 */

	t_data = tp.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
	tp.t_len = ItemIdGetLength(lp);
	tp.t_self = *tid;
	ctid = tp.t_data->t_ctid;

	/* ----------------
	 *	check time qualification of tid
	 * ----------------
	 */

	HeapTupleSatisfies(&tp, relation, buffer, dp,
					   snapshot, 0, (ScanKey) NULL);

	linkend = true;
	if ((t_data->t_infomask & HEAP_XMAX_COMMITTED) && 
		!ItemPointerEquals(tid, &ctid))
		linkend = false;

	LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
	ReleaseBuffer(buffer);

	if (tp.t_data == NULL)
	{
		if (linkend)
			return NULL;
		return heap_get_latest_tid(relation, snapshot, &ctid); 
	}

	return tid;
}

1184
/* ----------------
1185
 *		heap_insert		- insert tuple
1186
 *
1187 1188
 *		The assignment of t_min (and thus the others) should be
 *		removed eventually.
1189
 *
1190 1191 1192 1193
 *		Currently places the tuple onto the last page.	If there is no room,
 *		it is placed on new pages.	(Heap relations)
 *		Note that concurrent inserts during a scan will probably have
 *		unexpected results, though this will be fixed eventually.
1194
 *
1195
 *		Fix to work with indexes.
1196 1197 1198 1199 1200
 * ----------------
 */
Oid
heap_insert(Relation relation, HeapTuple tup)
{
1201 1202 1203 1204 1205 1206
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_insert);
	IncrHeapAccessStat(global_insert);
1207

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
	/* ----------------
	 *	If the object id of this tuple has already been assigned, trust
	 *	the caller.  There are a couple of ways this can happen.  At initial
	 *	db creation, the backend program sets oids for tuples.	When we
	 *	define an index, we set the oid.  Finally, in the future, we may
	 *	allow users to set their own object ids in order to support a
	 *	persistent object store (objects need to contain pointers to one
	 *	another).
	 * ----------------
	 */
1218
	if (!OidIsValid(tup->t_data->t_oid))
1219
	{
1220 1221
		tup->t_data->t_oid = newoid();
		LastOidProcessed = tup->t_data->t_oid;
1222 1223
	}
	else
1224
		CheckMaxObjectId(tup->t_data->t_oid);
1225

1226 1227 1228 1229 1230
	TransactionIdStore(GetCurrentTransactionId(), &(tup->t_data->t_xmin));
	tup->t_data->t_cmin = GetCurrentCommandId();
	StoreInvalidTransactionId(&(tup->t_data->t_xmax));
	tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
	tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
1231

V
Vadim B. Mikheev 已提交
1232
	RelationPutHeapTupleAtEnd(relation, tup);
1233 1234 1235 1236

	if (IsSystemRelationName(RelationGetRelationName(relation)->data))
		RelationInvalidateHeapTuple(relation, tup);

1237
	return tup->t_data->t_oid;
1238 1239
}

V
Vadim B. Mikheev 已提交
1240 1241
/*
 *	heap_delete		- delete a tuple
1242
 */
1243
int
V
Vadim B. Mikheev 已提交
1244
heap_delete(Relation relation, ItemPointer tid, ItemPointer ctid)
1245
{
B
Bruce Momjian 已提交
1246 1247 1248 1249 1250
	ItemId		lp;
	HeapTupleData tp;
	PageHeader	dp;
	Buffer		buffer;
	int			result;
1251

V
Vadim B. Mikheev 已提交
1252
	/* increment access statistics */
1253 1254 1255 1256 1257
	IncrHeapAccessStat(local_delete);
	IncrHeapAccessStat(global_delete);

	Assert(ItemPointerIsValid(tid));

V
Vadim B. Mikheev 已提交
1258
	buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1259

V
Vadim B. Mikheev 已提交
1260
	if (!BufferIsValid(buffer))
1261
		elog(ERROR, "heap_delete: failed ReadBuffer");
1262

V
Vadim B. Mikheev 已提交
1263
	LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1264

V
Vadim B. Mikheev 已提交
1265 1266
	dp = (PageHeader) BufferGetPage(buffer);
	lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(tid));
1267 1268 1269
	tp.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
	tp.t_len = ItemIdGetLength(lp);
	tp.t_self = *tid;
B
Bruce Momjian 已提交
1270

V
Vadim B. Mikheev 已提交
1271 1272
l1:
	result = HeapTupleSatisfiesUpdate(&tp);
B
Bruce Momjian 已提交
1273

V
Vadim B. Mikheev 已提交
1274
	if (result == HeapTupleInvisible)
1275
	{
V
Vadim B. Mikheev 已提交
1276 1277 1278
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
		ReleaseBuffer(buffer);
		elog(ERROR, "heap_delete: (am)invalid tid");
1279
	}
V
Vadim B. Mikheev 已提交
1280
	else if (result == HeapTupleBeingUpdated)
1281
	{
B
Bruce Momjian 已提交
1282
		TransactionId xwait = tp.t_data->t_xmax;
V
Vadim B. Mikheev 已提交
1283

B
Bruce Momjian 已提交
1284
		/* sleep until concurrent transaction ends */
V
Vadim B. Mikheev 已提交
1285 1286 1287 1288 1289 1290
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
		XactLockTableWait(xwait);

		LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
		if (TransactionIdDidAbort(xwait))
			goto l1;
1291 1292 1293 1294 1295 1296 1297
		/* 
		 * xwait is committed but if xwait had just marked
		 * the tuple for update then some other xaction could 
		 * update this tuple before we got to this point.
		 */
		if (tp.t_data->t_xmax != xwait)
			goto l1;
V
Vadim B. Mikheev 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
		if (!(tp.t_data->t_infomask & HEAP_XMAX_COMMITTED))
		{
			tp.t_data->t_infomask |= HEAP_XMAX_COMMITTED;
			SetBufferCommitInfoNeedsSave(buffer);
		}
		/* if tuple was marked for update but not updated... */
		if (tp.t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
			result = HeapTupleMayBeUpdated;
		else
			result = HeapTupleUpdated;
	}
	if (result != HeapTupleMayBeUpdated)
	{
		Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
		if (ctid != NULL)
			*ctid = tp.t_data->t_ctid;
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
		ReleaseBuffer(buffer);
		return result;
1317 1318
	}

V
Vadim B. Mikheev 已提交
1319
	/* store transaction information of xact deleting the tuple */
1320 1321
	TransactionIdStore(GetCurrentTransactionId(), &(tp.t_data->t_xmax));
	tp.t_data->t_cmax = GetCurrentCommandId();
B
Bruce Momjian 已提交
1322 1323
	tp.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
							 HEAP_XMAX_INVALID | HEAP_MARKED_FOR_UPDATE);
1324

V
Vadim B. Mikheev 已提交
1325 1326 1327
	LockBuffer(buffer, BUFFER_LOCK_UNLOCK);

	/* invalidate caches */
1328
	RelationInvalidateHeapTuple(relation, &tp);
1329

V
Vadim B. Mikheev 已提交
1330
	WriteBuffer(buffer);
1331

V
Vadim B. Mikheev 已提交
1332
	return HeapTupleMayBeUpdated;
1333 1334
}

V
Vadim B. Mikheev 已提交
1335 1336
/*
 *	heap_replace	- replace a tuple
1337 1338
 */
int
B
Bruce Momjian 已提交
1339 1340
heap_replace(Relation relation, ItemPointer otid, HeapTuple newtup,
			 ItemPointer ctid)
1341
{
B
Bruce Momjian 已提交
1342 1343 1344 1345 1346
	ItemId		lp;
	HeapTupleData oldtup;
	PageHeader	dp;
	Buffer		buffer;
	int			result;
1347

V
Vadim B. Mikheev 已提交
1348
	/* increment access statistics */
1349 1350 1351 1352 1353 1354 1355
	IncrHeapAccessStat(local_replace);
	IncrHeapAccessStat(global_replace);

	Assert(ItemPointerIsValid(otid));

	buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(otid));
	if (!BufferIsValid(buffer))
1356
		elog(ERROR, "amreplace: failed ReadBuffer");
V
Vadim B. Mikheev 已提交
1357
	LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1358

V
Vadim B. Mikheev 已提交
1359
	dp = (PageHeader) BufferGetPage(buffer);
1360 1361
	lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(otid));

1362 1363 1364
	oldtup.t_data = (HeapTupleHeader) PageGetItem(dp, lp);
	oldtup.t_len = ItemIdGetLength(lp);
	oldtup.t_self = *otid;
1365

V
Vadim B. Mikheev 已提交
1366 1367
l2:
	result = HeapTupleSatisfiesUpdate(&oldtup);
B
Bruce Momjian 已提交
1368

V
Vadim B. Mikheev 已提交
1369
	if (result == HeapTupleInvisible)
1370
	{
V
Vadim B. Mikheev 已提交
1371
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1372
		ReleaseBuffer(buffer);
V
Vadim B. Mikheev 已提交
1373
		elog(ERROR, "heap_replace: (am)invalid tid");
1374
	}
V
Vadim B. Mikheev 已提交
1375
	else if (result == HeapTupleBeingUpdated)
1376
	{
B
Bruce Momjian 已提交
1377
		TransactionId xwait = oldtup.t_data->t_xmax;
V
Vadim B. Mikheev 已提交
1378 1379 1380 1381 1382 1383 1384 1385

		/* sleep untill concurrent transaction ends */
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
		XactLockTableWait(xwait);

		LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
		if (TransactionIdDidAbort(xwait))
			goto l2;
1386 1387 1388 1389 1390 1391 1392
		/* 
		 * xwait is committed but if xwait had just marked
		 * the tuple for update then some other xaction could 
		 * update this tuple before we got to this point.
		 */
		if (oldtup.t_data->t_xmax != xwait)
			goto l2;
V
Vadim B. Mikheev 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
		if (!(oldtup.t_data->t_infomask & HEAP_XMAX_COMMITTED))
		{
			oldtup.t_data->t_infomask |= HEAP_XMAX_COMMITTED;
			SetBufferCommitInfoNeedsSave(buffer);
		}
		/* if tuple was marked for update but not updated... */
		if (oldtup.t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
			result = HeapTupleMayBeUpdated;
		else
			result = HeapTupleUpdated;
	}
	if (result != HeapTupleMayBeUpdated)
	{
		Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
		if (ctid != NULL)
			*ctid = oldtup.t_data->t_ctid;
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1410
		ReleaseBuffer(buffer);
V
Vadim B. Mikheev 已提交
1411
		return result;
1412 1413 1414
	}

	/* XXX order problems if not atomic assignment ??? */
1415 1416 1417 1418 1419
	newtup->t_data->t_oid = oldtup.t_data->t_oid;
	TransactionIdStore(GetCurrentTransactionId(), &(newtup->t_data->t_xmin));
	newtup->t_data->t_cmin = GetCurrentCommandId();
	StoreInvalidTransactionId(&(newtup->t_data->t_xmax));
	newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
1420
	newtup->t_data->t_infomask |= (HEAP_XMAX_INVALID | HEAP_UPDATED);
1421

V
Vadim B. Mikheev 已提交
1422 1423 1424
	/* logically delete old item */
	TransactionIdStore(GetCurrentTransactionId(), &(oldtup.t_data->t_xmax));
	oldtup.t_data->t_cmax = GetCurrentCommandId();
B
Bruce Momjian 已提交
1425 1426
	oldtup.t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED |
							 HEAP_XMAX_INVALID | HEAP_MARKED_FOR_UPDATE);
V
Vadim B. Mikheev 已提交
1427 1428

	/* insert new item */
1429
	if ((unsigned) MAXALIGN(newtup->t_len) <= PageGetFreeSpace((Page) dp))
V
Vadim B. Mikheev 已提交
1430
		RelationPutHeapTuple(relation, buffer, newtup);
1431 1432
	else
	{
B
Bruce Momjian 已提交
1433

V
Vadim B. Mikheev 已提交
1434
		/*
B
Bruce Momjian 已提交
1435 1436 1437 1438
		 * New item won't fit on same page as old item, have to look for a
		 * new place to put it. Note that we have to unlock current buffer
		 * context - not good but RelationPutHeapTupleAtEnd uses extend
		 * lock.
1439
		 */
V
Vadim B. Mikheev 已提交
1440 1441 1442
		LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
		RelationPutHeapTupleAtEnd(relation, newtup);
		LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1443 1444
	}

V
Vadim B. Mikheev 已提交
1445
	/*
B
Bruce Momjian 已提交
1446 1447
	 * New item in place, now record address of new tuple in t_ctid of old
	 * one.
1448
	 */
V
Vadim B. Mikheev 已提交
1449
	oldtup.t_data->t_ctid = newtup->t_self;
1450

V
Vadim B. Mikheev 已提交
1451 1452 1453
	LockBuffer(buffer, BUFFER_LOCK_UNLOCK);

	/* invalidate caches */
1454
	RelationInvalidateHeapTuple(relation, &oldtup);
1455 1456 1457

	WriteBuffer(buffer);

V
Vadim B. Mikheev 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466
	return HeapTupleMayBeUpdated;
}

/*
 *	heap_mark4update		- mark a tuple for update
 */
int
heap_mark4update(Relation relation, HeapTuple tuple, Buffer *buffer)
{
B
Bruce Momjian 已提交
1467 1468 1469 1470
	ItemPointer tid = &(tuple->t_self);
	ItemId		lp;
	PageHeader	dp;
	int			result;
V
Vadim B. Mikheev 已提交
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486

	/* increment access statistics */
	IncrHeapAccessStat(local_mark4update);
	IncrHeapAccessStat(global_mark4update);

	*buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));

	if (!BufferIsValid(*buffer))
		elog(ERROR, "heap_mark4update: failed ReadBuffer");

	LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);

	dp = (PageHeader) BufferGetPage(*buffer);
	lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(tid));
	tuple->t_data = (HeapTupleHeader) PageGetItem((Page) dp, lp);
	tuple->t_len = ItemIdGetLength(lp);
B
Bruce Momjian 已提交
1487

V
Vadim B. Mikheev 已提交
1488 1489
l3:
	result = HeapTupleSatisfiesUpdate(tuple);
B
Bruce Momjian 已提交
1490

V
Vadim B. Mikheev 已提交
1491 1492 1493 1494 1495 1496 1497 1498
	if (result == HeapTupleInvisible)
	{
		LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
		ReleaseBuffer(*buffer);
		elog(ERROR, "heap_mark4update: (am)invalid tid");
	}
	else if (result == HeapTupleBeingUpdated)
	{
B
Bruce Momjian 已提交
1499
		TransactionId xwait = tuple->t_data->t_xmax;
V
Vadim B. Mikheev 已提交
1500 1501 1502 1503 1504 1505 1506 1507

		/* sleep untill concurrent transaction ends */
		LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
		XactLockTableWait(xwait);

		LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
		if (TransactionIdDidAbort(xwait))
			goto l3;
1508 1509 1510 1511 1512 1513 1514
		/* 
		 * xwait is committed but if xwait had just marked
		 * the tuple for update then some other xaction could 
		 * update this tuple before we got to this point.
		 */
		if (tuple->t_data->t_xmax != xwait)
			goto l3;
V
Vadim B. Mikheev 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
		if (!(tuple->t_data->t_infomask & HEAP_XMAX_COMMITTED))
		{
			tuple->t_data->t_infomask |= HEAP_XMAX_COMMITTED;
			SetBufferCommitInfoNeedsSave(*buffer);
		}
		/* if tuple was marked for update but not updated... */
		if (tuple->t_data->t_infomask & HEAP_MARKED_FOR_UPDATE)
			result = HeapTupleMayBeUpdated;
		else
			result = HeapTupleUpdated;
	}
	if (result != HeapTupleMayBeUpdated)
	{
		Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated);
1529
		tuple->t_self = tuple->t_data->t_ctid;
V
Vadim B. Mikheev 已提交
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
		LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
		return result;
	}

	/* store transaction information of xact marking the tuple */
	TransactionIdStore(GetCurrentTransactionId(), &(tuple->t_data->t_xmax));
	tuple->t_data->t_cmax = GetCurrentCommandId();
	tuple->t_data->t_infomask &= ~(HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID);
	tuple->t_data->t_infomask |= HEAP_MARKED_FOR_UPDATE;

	LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);

	WriteNoReleaseBuffer(*buffer);
1543

V
Vadim B. Mikheev 已提交
1544
	return HeapTupleMayBeUpdated;
1545 1546 1547
}

/* ----------------
1548
 *		heap_markpos	- mark scan position
1549
 *
1550 1551 1552 1553 1554 1555
 *		Note:
 *				Should only one mark be maintained per scan at one time.
 *		Check if this can be done generally--say calls to get the
 *		next/previous tuple and NEVER pass struct scandesc to the
 *		user AM's.  Now, the mark is sent to the executor for safekeeping.
 *		Probably can store this info into a GENERAL scan structure.
1556
 *
1557 1558 1559
 *		May be best to change this call to store the marked position
 *		(up to 2?) in the scan structure itself.
 *		Fix to use the proper caching structure.
1560 1561 1562
 * ----------------
 */
void
1563
heap_markpos(HeapScanDesc scan)
1564
{
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574

	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_markpos);
	IncrHeapAccessStat(global_markpos);

	/* Note: no locking manipulations needed */

1575
	if (scan->rs_ptup.t_data == NULL &&
1576
		BufferIsUnknown(scan->rs_pbuf))
1577
	{							/* == NONTUP */
1578 1579 1580 1581 1582 1583 1584 1585
		scan->rs_ptup = scan->rs_ctup;
		heapgettup(scan->rs_rd,
				   &(scan->rs_ptup),
				   -1,
				   &scan->rs_pbuf,
				   scan->rs_snapshot,
				   scan->rs_nkeys,
				   scan->rs_key);
1586 1587

	}
1588
	else if (scan->rs_ntup.t_data == NULL &&
1589
			 BufferIsUnknown(scan->rs_nbuf))
1590
	{							/* == NONTUP */
1591 1592 1593 1594 1595 1596 1597 1598
		scan->rs_ntup = scan->rs_ctup;
		heapgettup(scan->rs_rd,
				   &(scan->rs_ntup),
				   1,
				   &scan->rs_nbuf,
				   scan->rs_snapshot,
				   scan->rs_nkeys,
				   scan->rs_key);
1599 1600 1601 1602 1603 1604
	}

	/* ----------------
	 * Should not unpin the buffer pages.  They may still be in use.
	 * ----------------
	 */
1605 1606
	if (scan->rs_ptup.t_data != NULL)
		scan->rs_mptid = scan->rs_ptup.t_self;
1607
	else
1608
		ItemPointerSetInvalid(&scan->rs_mptid);
1609 1610
	if (scan->rs_ctup.t_data != NULL)
		scan->rs_mctid = scan->rs_ctup.t_self;
1611
	else
1612
		ItemPointerSetInvalid(&scan->rs_mctid);
1613 1614
	if (scan->rs_ntup.t_data != NULL)
		scan->rs_mntid = scan->rs_ntup.t_self;
1615
	else
1616
		ItemPointerSetInvalid(&scan->rs_mntid);
1617 1618 1619
}

/* ----------------
1620
 *		heap_restrpos	- restore position to marked location
1621
 *
1622 1623 1624 1625 1626
 *		Note:  there are bad side effects here.  If we were past the end
 *		of a relation when heapmarkpos is called, then if the relation is
 *		extended via insert, then the next call to heaprestrpos will set
 *		cause the added tuples to be visible when the scan continues.
 *		Problems also arise if the TID's are rearranged!!!
1627
 *
1628 1629 1630
 *		Now pins buffer once for each valid tuple pointer (rs_ptup,
 *		rs_ctup, rs_ntup) referencing it.
 *		 - 01/13/94
1631 1632
 *
 * XXX	might be better to do direct access instead of
1633
 *		using the generality of heapgettup().
1634 1635 1636 1637 1638 1639 1640
 *
 * XXX It is very possible that when a scan is restored, that a tuple
 * XXX which previously qualified may fail for time range purposes, unless
 * XXX some form of locking exists (ie., portals currently can act funny.
 * ----------------
 */
void
1641
heap_restrpos(HeapScanDesc scan)
1642
{
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_restrpos);
	IncrHeapAccessStat(global_restrpos);

	/* XXX no amrestrpos checking that ammarkpos called */

	/* Note: no locking manipulations needed */

1654
	unpinscan(scan);
1655 1656

	/* force heapgettup to pin buffer for each loaded tuple */
1657 1658 1659
	scan->rs_pbuf = InvalidBuffer;
	scan->rs_cbuf = InvalidBuffer;
	scan->rs_nbuf = InvalidBuffer;
1660

1661
	if (!ItemPointerIsValid(&scan->rs_mptid))
1662
		scan->rs_ptup.t_data = NULL;
1663 1664
	else
	{
1665 1666 1667 1668 1669 1670 1671 1672 1673
		scan->rs_ptup.t_self = scan->rs_mptid;
		scan->rs_ptup.t_data = (HeapTupleHeader) 0x1;	/* for heapgettup */
		heapgettup(scan->rs_rd,
				   &(scan->rs_ptup),
				   0,
				   &(scan->rs_pbuf),
				   false,
				   0,
				   (ScanKey) NULL);
1674 1675
	}

1676
	if (!ItemPointerIsValid(&scan->rs_mctid))
1677
		scan->rs_ctup.t_data = NULL;
1678 1679
	else
	{
1680 1681 1682 1683 1684 1685 1686 1687 1688
		scan->rs_ctup.t_self = scan->rs_mctid;
		scan->rs_ctup.t_data = (HeapTupleHeader) 0x1;	/* for heapgettup */
		heapgettup(scan->rs_rd,
				   &(scan->rs_ctup),
				   0,
				   &(scan->rs_cbuf),
				   false,
				   0,
				   (ScanKey) NULL);
1689 1690
	}

1691
	if (!ItemPointerIsValid(&scan->rs_mntid))
1692
		scan->rs_ntup.t_data = NULL;
1693 1694
	else
	{
1695 1696 1697 1698 1699 1700 1701 1702 1703
		scan->rs_ntup.t_self = scan->rs_mntid;
		scan->rs_ntup.t_data = (HeapTupleHeader) 0x1;	/* for heapgettup */
		heapgettup(scan->rs_rd,
				   &(scan->rs_ntup),
				   0,
				   &scan->rs_nbuf,
				   false,
				   0,
				   (ScanKey) NULL);
1704
	}
1705
}