heapam.c 37.5 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.37 1998/10/12 00:53:30 momjian 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
 *
 *-------------------------------------------------------------------------
 */

M
Marc G. Fournier 已提交
76
#include <postgres.h>
77

M
Marc G. Fournier 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90
#include <storage/bufpage.h>
#include <access/heapam.h>
#include <miscadmin.h>
#include <utils/relcache.h>
#include <access/valid.h>
#include <access/hio.h>
#include <storage/lmgr.h>
#include <storage/smgr.h>
#include <catalog/catalog.h>
#include <access/transam.h>
#include <access/xact.h>
#include <utils/inval.h>
#include <utils/memutils.h>
91 92


M
-Wall'd  
Marc G. Fournier 已提交
93
#ifndef HAVE_MEMMOVE
94
#include <regex/utils.h>
M
-Wall'd  
Marc G. Fournier 已提交
95
#else
96
#include <string.h>
M
-Wall'd  
Marc G. Fournier 已提交
97 98
#endif

99 100
static void doinsert(Relation relation, HeapTuple tup);

101
/* ----------------------------------------------------------------
102
 *						 heap support routines
103 104 105 106
 * ----------------------------------------------------------------
 */

/* ----------------
107
 *		initscan - scan code common to heap_beginscan and heap_rescan
108 109 110
 * ----------------
 */
static void
111
initscan(HeapScanDesc scan,
112 113 114 115
		 Relation relation,
		 int atend,
		 unsigned nkeys,
		 ScanKey key)
116
{
117 118 119 120 121 122
	if (!RelationGetNumberOfBlocks(relation))
	{
		/* ----------------
		 *	relation is empty
		 * ----------------
		 */
123 124
		scan->rs_ntup = scan->rs_ctup = scan->rs_ptup = NULL;
		scan->rs_nbuf = scan->rs_cbuf = scan->rs_pbuf = InvalidBuffer;
125 126 127 128 129 130 131
	}
	else if (atend)
	{
		/* ----------------
		 *	reverse scan
		 * ----------------
		 */
132 133 134 135
		scan->rs_ntup = scan->rs_ctup = NULL;
		scan->rs_nbuf = scan->rs_cbuf = InvalidBuffer;
		scan->rs_ptup = NULL;
		scan->rs_pbuf = UnknownBuffer;
136 137 138 139 140 141 142
	}
	else
	{
		/* ----------------
		 *	forward scan
		 * ----------------
		 */
143 144 145 146
		scan->rs_ctup = scan->rs_ptup = NULL;
		scan->rs_cbuf = scan->rs_pbuf = InvalidBuffer;
		scan->rs_ntup = NULL;
		scan->rs_nbuf = UnknownBuffer;
147 148 149
	}							/* invalid too */

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

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

/* ----------------
164
 *		unpinscan - code common to heap_rescan and heap_endscan
165 166 167
 * ----------------
 */
static void
168
unpinscan(HeapScanDesc scan)
169
{
170 171
	if (BufferIsValid(scan->rs_pbuf))
		ReleaseBuffer(scan->rs_pbuf);
172 173 174 175 176 177 178

	/* ------------------------------------
	 *	Scan will pin buffer one for each non-NULL tuple pointer
	 *	(ptup, ctup, ntup), so they have to be unpinned multiple
	 *	times.
	 * ------------------------------------
	 */
179 180
	if (BufferIsValid(scan->rs_cbuf))
		ReleaseBuffer(scan->rs_cbuf);
181

182 183
	if (BufferIsValid(scan->rs_nbuf))
		ReleaseBuffer(scan->rs_nbuf);
184 185 186
}

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

/* ----------------
201
 *		heapgettup - fetch next heap tuple
202
 *
203 204
 *		routine used by heap_getnext() which does most of the
 *		real work in scanning tuples.
205 206 207 208 209
 *
 *		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.
210 211
 * ----------------
 */
212
static HeapTuple
213
heapgettup(Relation relation,
214 215
		   ItemPointer tid,
		   int dir,
216
		   Buffer *buf,
217
		   Snapshot snapshot,
218 219
		   int nkeys,
		   ScanKey key)
220
{
221 222 223 224 225 226 227 228
	ItemId		lpp;
	Page		dp;
	int			page;
	int			pages;
	int			lines;
	HeapTuple	rtup;
	OffsetNumber lineoff;
	int			linesleft;
229

230
	/* ----------------
231
	 *	increment access statistics
232 233
	 * ----------------
	 */
234 235 236
	IncrHeapAccessStat(local_heapgettup);
	IncrHeapAccessStat(global_heapgettup);

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

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

	if (!ItemPointerIsValid(tid))
		Assert(!PointerIsValid(tid));
265 266

	/* ----------------
267
	 *	return null immediately if relation is empty
268 269
	 * ----------------
	 */
270
	if (!(pages = relation->rd_nblocks))
271
		return NULL;
272 273 274 275 276 277 278 279 280 281 282 283 284 285

	/* ----------------
	 *	calculate next starting lineoff, given scan direction
	 * ----------------
	 */
	if (!dir)
	{
		/* ----------------
		 * ``no movement'' scan direction
		 * ----------------
		 */
		/* assume it is a valid TID XXX */
		if (ItemPointerIsValid(tid) == false)
		{
286
			*buf = InvalidBuffer;
287
			return NULL;
288
		}
289
		*buf = RelationGetBufferWithBuffer(relation,
290 291
										   ItemPointerGetBlockNumber(tid),
										   *buf);
292 293

#ifndef NO_BUFFERISVALID
294
		if (!BufferIsValid(*buf))
295
			elog(ERROR, "heapgettup: failed ReadBuffer");
296 297
#endif

298
		dp = (Page) BufferGetPage(*buf);
299 300 301 302
		lineoff = ItemPointerGetOffsetNumber(tid);
		lpp = PageGetItemId(dp, lineoff);

		rtup = (HeapTuple) PageGetItem((Page) dp, lpp);
303
		return rtup;
304

305
	}
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	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)
		{
324
			*buf = InvalidBuffer;
325
			return NULL;
326 327
		}

328
		*buf = RelationGetBufferWithBuffer(relation, page, *buf);
329
#ifndef NO_BUFFERISVALID
330
		if (!BufferIsValid(*buf))
331
			elog(ERROR, "heapgettup: failed ReadBuffer");
332
#endif
333

334
		dp = (Page) BufferGetPage(*buf);
335 336 337 338
		lines = PageGetMaxOffsetNumber(dp);
		if (tid == NULL)
		{
			lineoff = lines;	/* final offnum */
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
		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)
		{
368
			*buf = InvalidBuffer;
369
			return NULL;
370 371 372
		}
		/* page and lineoff now reference the physically next tid */

373
		*buf = RelationGetBufferWithBuffer(relation, page, *buf);
374
#ifndef NO_BUFFERISVALID
375
		if (!BufferIsValid(*buf))
376
			elog(ERROR, "heapgettup: failed ReadBuffer");
377 378
#endif

379
		dp = (Page) BufferGetPage(*buf);
380
		lines = PageGetMaxOffsetNumber(dp);
381
	}
382 383 384

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

385
	/* ----------------
386 387
	 *	calculate line pointer and number of remaining items
	 *	to check on this page.
388 389
	 * ----------------
	 */
390 391 392 393 394 395
	lpp = PageGetItemId(dp, lineoff);
	if (dir < 0)
		linesleft = lineoff - 1;
	else
		linesleft = lines - lineoff;

396
	/* ----------------
397 398
	 *	advance the scan until we find a qualifying tuple or
	 *	run out of stuff to scan
399 400
	 * ----------------
	 */
401 402 403 404 405 406 407 408
	for (;;)
	{
		while (linesleft >= 0)
		{
			/* ----------------
			 *	if current tuple qualifies, return it.
			 * ----------------
			 */
409
			HeapTupleSatisfies(lpp, relation, *buf, (PageHeader) dp,
410
							   snapshot, nkeys, key, rtup);
411
			if (rtup != NULL)
412
			{
413
				ItemPointer iptr = &(rtup->t_ctid);
414 415 416

				if (ItemPointerGetBlockNumber(iptr) != page)
				{
417

418 419 420 421 422 423
					/*
					 * set block id to the correct page number --- this is
					 * a hack to support the virtual fragment concept
					 */
					ItemPointerSetBlockNumber(iptr, page);
				}
424
				return rtup;
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
			}

			/* ----------------
			 *	otherwise move to the next item on the page
			 * ----------------
			 */
			--linesleft;
			if (dir < 0)
			{
				--lpp;			/* move back in this page's ItemId array */
			}
			else
			{
				++lpp;			/* move forward in this page's ItemId
								 * array */
			}
		}

		/* ----------------
		 *	if we get here, it means we've exhausted the items on
		 *	this page and it's time to move to the next..
		 * ----------------
		 */
		page = nextpage(page, dir);

		/* ----------------
		 *	return NULL if we've exhausted all the pages..
		 * ----------------
		 */
		if (page < 0 || page >= pages)
		{
456 457 458
			if (BufferIsValid(*buf))
				ReleaseBuffer(*buf);
			*buf = InvalidBuffer;
459
			return NULL;
460 461
		}

462
		*buf = ReleaseAndReadBuffer(*buf, relation, page);
463

464
#ifndef NO_BUFFERISVALID
465
		if (!BufferIsValid(*buf))
466
			elog(ERROR, "heapgettup: failed ReadBuffer");
467
#endif
468
		dp = (Page) BufferGetPage(*buf);
469 470 471 472 473 474
		lines = lineoff = PageGetMaxOffsetNumber((Page) dp);
		linesleft = lines - 1;
		if (dir < 0)
			lpp = PageGetItemId(dp, lineoff);
		else
			lpp = PageGetItemId(dp, FirstOffsetNumber);
475 476 477
	}
}

478
static void
479 480
doinsert(Relation relation, HeapTuple tup)
{
481 482
	RelationPutHeapTupleAtEnd(relation, tup);
	return;
483 484 485 486
}


/* ----------------------------------------------------------------
487
 *					 heap access method interface
488 489 490
 * ----------------------------------------------------------------
 */
/* ----------------
491
 *		heap_open - open a heap relation by relationId
492
 *
493 494
 *		presently the relcache routines do all the work we need
 *		to open/close heap relations.
495 496 497 498 499
 * ----------------
 */
Relation
heap_open(Oid relationId)
{
500
	Relation	r;
501 502 503 504 505 506 507 508 509 510 511

	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_open);
	IncrHeapAccessStat(global_open);

	r = (Relation) RelationIdGetRelation(relationId);

	if (RelationIsValid(r) && r->rd_rel->relkind == RELKIND_INDEX)
512
		elog(ERROR, "%s is an index relation", r->rd_rel->relname.data);
513

514
	return r;
515 516 517
}

/* ----------------
518
 *		heap_openr - open a heap relation by name
519
 *
520 521
 *		presently the relcache routines do all the work we need
 *		to open/close heap relations.
522 523 524 525 526
 * ----------------
 */
Relation
heap_openr(char *relationName)
{
527
	Relation	r;
528 529 530 531 532 533 534 535 536 537 538

	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_openr);
	IncrHeapAccessStat(global_openr);

	r = RelationNameGetRelation(relationName);

	if (RelationIsValid(r) && r->rd_rel->relkind == RELKIND_INDEX)
539
		elog(ERROR, "%s is an index relation", r->rd_rel->relname.data);
540

541
	return r;
542 543 544
}

/* ----------------
545
 *		heap_close - close a heap relation
546
 *
547 548
 *		presently the relcache routines do all the work we need
 *		to open/close heap relations.
549 550 551 552 553
 * ----------------
 */
void
heap_close(Relation relation)
{
554 555 556 557 558 559 560 561
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_close);
	IncrHeapAccessStat(global_close);

	RelationClose(relation);
562 563 564 565
}


/* ----------------
566
 *		heap_beginscan	- begin relation scan
567 568 569 570
 * ----------------
 */
HeapScanDesc
heap_beginscan(Relation relation,
571
			   int atend,
572
			   Snapshot snapshot,
573 574
			   unsigned nkeys,
			   ScanKey key)
575
{
576
	HeapScanDesc scan;
577 578 579 580 581 582 583 584 585 586 587

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

	/* ----------------
	 *	sanity checks
	 * ----------------
588
	 */
589
	if (RelationIsValid(relation) == false)
590
		elog(ERROR, "heap_beginscan: !RelationIsValid(relation)");
591 592 593 594 595 596 597 598 599

	/* ----------------
	 * set relation level read lock
	 * ----------------
	 */
	RelationSetLockForRead(relation);

	/* XXX someday assert SelfTimeQual if relkind == RELKIND_UNCATALOGED */
	if (relation->rd_rel->relkind == RELKIND_UNCATALOGED)
600
		snapshot = SnapshotSelf;
601 602 603 604 605 606 607 608 609 610 611

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

	/* ----------------
	 *	allocate and initialize scan descriptor
	 * ----------------
	 */
612
	scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
613

B
Bruce Momjian 已提交
614
	relation->rd_nblocks = smgrnblocks(DEFAULT_SMGR, relation);
615
	scan->rs_rd = relation;
616 617

	if (nkeys)
618

619
		/*
620 621
		 * we do this here instead of in initscan() because heap_rescan
		 * also calls initscan() and we don't want to allocate memory
622 623
		 * again
		 */
624
		scan->rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
625
	else
626
		scan->rs_key = NULL;
627

628
	initscan(scan, relation, atend, nkeys, key);
629

630 631 632
	scan->rs_atend = atend;
	scan->rs_snapshot = snapshot;
	scan->rs_nkeys = (short) nkeys;
633

634
	return scan;
635 636 637
}

/* ----------------
638
 *		heap_rescan		- restart a relation scan
639 640 641
 * ----------------
 */
void
642
heap_rescan(HeapScanDesc scan,
643 644
			bool scanFromEnd,
			ScanKey key)
645
{
646 647 648 649 650 651 652 653 654 655 656 657 658
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_rescan);
	IncrHeapAccessStat(global_rescan);

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

	/* ----------------
	 *	unpin scan buffers
	 * ----------------
	 */
659
	unpinscan(scan);
660 661 662 663 664

	/* ----------------
	 *	reinitialize scan descriptor
	 * ----------------
	 */
665 666
	initscan(scan, scan->rs_rd, scanFromEnd, scan->rs_nkeys, key);
	scan->rs_atend = (bool) scanFromEnd;
667 668 669
}

/* ----------------
670
 *		heap_endscan	- end relation scan
671
 *
672 673
 *		See how to integrate with index scans.
 *		Check handling if reldesc caching.
674 675 676
 * ----------------
 */
void
677
heap_endscan(HeapScanDesc scan)
678
{
679 680 681 682 683 684 685 686 687 688 689 690 691
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_endscan);
	IncrHeapAccessStat(global_endscan);

	/* Note: no locking manipulations needed */

	/* ----------------
	 *	unpin scan buffers
	 * ----------------
	 */
692
	unpinscan(scan);
693 694 695 696 697

	/* ----------------
	 *	decrement relation reference count and free scan descriptor storage
	 * ----------------
	 */
698
	RelationDecrementReferenceCount(scan->rs_rd);
699 700 701 702 703

	/* ----------------
	 * Non 2-phase read locks on catalog relations
	 * ----------------
	 */
704
	if (IsSystemRelationName(RelationGetRelationName(scan->rs_rd)->data))
705

706
		RelationUnsetLockForRead(scan->rs_rd);
707

708
	pfree(scan);				/* XXX */
709 710 711
}

/* ----------------
712
 *		heap_getnext	- retrieve next tuple in scan
713
 *
714
 *		Fix to work with index relations.
715 716
 *		We don't return the buffer anymore, but you can get it from the
 *		returned HeapTuple.
717 718 719 720 721
 * ----------------
 */

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

725
#define HEAPDEBUG_2 \
726 727
	 elog(DEBUG, "heap_getnext called with backw (no tracing yet)")

728
#define HEAPDEBUG_3 \
729 730
	 elog(DEBUG, "heap_getnext returns NULL at end")

731
#define HEAPDEBUG_4 \
732 733
	 elog(DEBUG, "heap_getnext valid buffer UNPIN'd")

734
#define HEAPDEBUG_5 \
735 736
	 elog(DEBUG, "heap_getnext next tuple was cached")

737
#define HEAPDEBUG_6 \
738 739
	 elog(DEBUG, "heap_getnext returning EOS")

740
#define HEAPDEBUG_7 \
741
	 elog(DEBUG, "heap_getnext returning tuple");
742 743 744 745 746 747 748 749
#else
#define HEAPDEBUG_1
#define HEAPDEBUG_2
#define HEAPDEBUG_3
#define HEAPDEBUG_4
#define HEAPDEBUG_5
#define HEAPDEBUG_6
#define HEAPDEBUG_7
750
#endif	 /* !defined(HEAPDEBUGALL) */
751 752


753
HeapTuple
754
heap_getnext(HeapScanDesc scandesc, int backw)
755
{
756
	HeapScanDesc scan = scandesc;
757

758
	/* ----------------
759
	 *	increment access statistics
760 761
	 * ----------------
	 */
762 763 764 765 766 767 768 769
	IncrHeapAccessStat(local_getnext);
	IncrHeapAccessStat(global_getnext);

	/* Note: no locking manipulations needed */

	/* ----------------
	 *	argument checks
	 * ----------------
770
	 */
771
	if (scan == NULL)
772
		elog(ERROR, "heap_getnext: NULL relscan");
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

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

	HEAPDEBUG_1;				/* heap_getnext( info ) */

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

789 790
		if (scan->rs_ptup == scan->rs_ctup &&
			BufferIsInvalid(scan->rs_pbuf))
791
		{
792 793
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
794
			return NULL;
795 796 797 798 799 800
		}

		/*
		 * Copy the "current" tuple/buffer to "next". Pin/unpin the
		 * buffers accordingly
		 */
801
		if (scan->rs_nbuf != scan->rs_cbuf)
802
		{
803 804 805 806
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
			if (BufferIsValid(scan->rs_cbuf))
				IncrBufferRefCount(scan->rs_cbuf);
807
		}
808 809
		scan->rs_ntup = scan->rs_ctup;
		scan->rs_nbuf = scan->rs_cbuf;
810

811
		if (scan->rs_ptup != NULL)
812
		{
813
			if (scan->rs_cbuf != scan->rs_pbuf)
814
			{
815 816 817 818
				if (BufferIsValid(scan->rs_cbuf))
					ReleaseBuffer(scan->rs_cbuf);
				if (BufferIsValid(scan->rs_pbuf))
					IncrBufferRefCount(scan->rs_pbuf);
819
			}
820 821
			scan->rs_ctup = scan->rs_ptup;
			scan->rs_cbuf = scan->rs_pbuf;
822 823 824
		}
		else
		{						/* NONTUP */
825
			ItemPointer iptr;
826

827 828
			iptr = (scan->rs_ctup != NULL) ?
				&(scan->rs_ctup->t_ctid) : (ItemPointer) NULL;
829 830

			/*
831
			 * Don't release scan->rs_cbuf at this point, because
832 833 834 835 836 837 838
			 * 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
			 */

839 840
			scan->rs_ctup = (HeapTuple)
				heapgettup(scan->rs_rd,
841 842
						   iptr,
						   -1,
843 844 845 846
						   &(scan->rs_cbuf),
						   scan->rs_snapshot,
						   scan->rs_nkeys,
						   scan->rs_key);
847 848
		}

849
		if (scan->rs_ctup == NULL && !BufferIsValid(scan->rs_cbuf))
850
		{
851 852 853 854 855 856 857 858
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
			scan->rs_ptup = NULL;
			scan->rs_pbuf = InvalidBuffer;
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
			scan->rs_ntup = NULL;
			scan->rs_nbuf = InvalidBuffer;
859
			return NULL;
860 861
		}

862 863 864 865
		if (BufferIsValid(scan->rs_pbuf))
			ReleaseBuffer(scan->rs_pbuf);
		scan->rs_ptup = NULL;
		scan->rs_pbuf = UnknownBuffer;
866 867 868 869 870 871 872 873

	}
	else
	{
		/* ----------------
		 *	handle forward scan
		 * ----------------
		 */
874 875
		if (scan->rs_ctup == scan->rs_ntup &&
			BufferIsInvalid(scan->rs_nbuf))
876
		{
877 878
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
879
			HEAPDEBUG_3;		/* heap_getnext returns NULL at end */
880
			return NULL;
881 882 883 884 885 886
		}

		/*
		 * Copy the "current" tuple/buffer to "previous". Pin/unpin the
		 * buffers accordingly
		 */
887
		if (scan->rs_pbuf != scan->rs_cbuf)
888
		{
889 890 891 892
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
			if (BufferIsValid(scan->rs_cbuf))
				IncrBufferRefCount(scan->rs_cbuf);
893
		}
894 895
		scan->rs_ptup = scan->rs_ctup;
		scan->rs_pbuf = scan->rs_cbuf;
896

897
		if (scan->rs_ntup != NULL)
898
		{
899
			if (scan->rs_cbuf != scan->rs_nbuf)
900
			{
901 902 903 904
				if (BufferIsValid(scan->rs_cbuf))
					ReleaseBuffer(scan->rs_cbuf);
				if (BufferIsValid(scan->rs_nbuf))
					IncrBufferRefCount(scan->rs_nbuf);
905
			}
906 907
			scan->rs_ctup = scan->rs_ntup;
			scan->rs_cbuf = scan->rs_nbuf;
908 909 910 911
			HEAPDEBUG_5;		/* heap_getnext next tuple was cached */
		}
		else
		{						/* NONTUP */
912
			ItemPointer iptr;
913

914 915
			iptr = (scan->rs_ctup != NULL) ?
				&scan->rs_ctup->t_ctid : (ItemPointer) NULL;
916 917

			/*
918
			 * Don't release scan->rs_cbuf at this point, because
919 920 921 922 923 924 925
			 * 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
			 */

926 927
			scan->rs_ctup = (HeapTuple)
				heapgettup(scan->rs_rd,
928 929
						   iptr,
						   1,
930 931 932 933
						   &scan->rs_cbuf,
						   scan->rs_snapshot,
						   scan->rs_nkeys,
						   scan->rs_key);
934 935
		}

936
		if (scan->rs_ctup == NULL && !BufferIsValid(scan->rs_cbuf))
937
		{
938 939 940 941 942 943 944 945
			if (BufferIsValid(scan->rs_nbuf))
				ReleaseBuffer(scan->rs_nbuf);
			scan->rs_ntup = NULL;
			scan->rs_nbuf = InvalidBuffer;
			if (BufferIsValid(scan->rs_pbuf))
				ReleaseBuffer(scan->rs_pbuf);
			scan->rs_ptup = NULL;
			scan->rs_pbuf = InvalidBuffer;
946
			HEAPDEBUG_6;		/* heap_getnext returning EOS */
947
			return NULL;
948 949
		}

950 951 952 953
		if (BufferIsValid(scan->rs_nbuf))
			ReleaseBuffer(scan->rs_nbuf);
		scan->rs_ntup = NULL;
		scan->rs_nbuf = UnknownBuffer;
954 955
	}

956
	/* ----------------
957 958
	 *	if we get here it means we have a new current scan tuple, so
	 *	point to the proper return buffer and return the tuple.
959 960
	 * ----------------
	 */
961 962 963

	HEAPDEBUG_7;				/* heap_getnext returning tuple */

964
	return scan->rs_ctup;
965 966 967
}

/* ----------------
968
 *		heap_fetch		- retrive tuple with tid
969
 *
970
 *		Currently ignores LP_IVALID during processing!
971 972 973 974 975 976 977
 *
 *		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
 *		value, and they are required to BuffferRelease() it when they
 *		are done.  If they want to make a copy of it before releasing it,
 *		they can call heap_copytyple().
978

979 980 981 982
 * ----------------
 */
HeapTuple
heap_fetch(Relation relation,
983
		   Snapshot snapshot,
984
		   ItemPointer tid,
985
		   Buffer *userbuf)
986
{
987 988 989 990 991
	ItemId		lp;
	Buffer		buffer;
	PageHeader	dp;
	HeapTuple	tuple;
	OffsetNumber offnum;
992

993 994
	AssertMacro(PointerIsValid(userbuf));		/* see comments above */

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_fetch);
	IncrHeapAccessStat(global_fetch);

	/*
	 * Note: This is collosally expensive - does two system calls per
	 * indexscan tuple fetch.  Not good, and since we should be doing page
	 * level locking by the scanner anyway, it is commented out.
	 */

	/* RelationSetLockForTupleRead(relation, tid); */

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

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

1018
#ifndef NO_BUFFERISVALID
1019 1020
	if (!BufferIsValid(buffer))
	{
1021
		elog(ERROR, "heap_fetch: %s relation: ReadBuffer(%lx) failed",
1022 1023
			 &relation->rd_rel->relname, (long) tid);
	}
1024
#endif
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

	/* ----------------
	 *	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));

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

1046
	HeapTupleSatisfies(lp, relation, buffer, dp,
1047
					   snapshot, 0, (ScanKey) NULL, tuple);
1048 1049

	if (tuple == NULL)
1050
	{
1051
		ReleaseBuffer(buffer);
1052
		return NULL;
1053
	}
1054 1055 1056 1057

	/* ----------------
	 *	all checks passed, now either return a copy of the tuple
	 *	or pin the buffer page and return a pointer, depending on
1058
	 *	whether caller gave us a valid buf.
1059 1060 1061
	 * ----------------
	 */

1062 1063
	*userbuf = buffer;			/* user is required to ReleaseBuffer()
								 * this */
1064

1065
	return tuple;
1066 1067 1068
}

/* ----------------
1069
 *		heap_insert		- insert tuple
1070
 *
1071 1072
 *		The assignment of t_min (and thus the others) should be
 *		removed eventually.
1073
 *
1074 1075 1076 1077
 *		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.
1078
 *
1079
 *		Fix to work with indexes.
1080 1081 1082 1083 1084
 * ----------------
 */
Oid
heap_insert(Relation relation, HeapTuple tup)
{
1085 1086 1087 1088 1089 1090
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_insert);
	IncrHeapAccessStat(global_insert);
1091 1092

	/* ----------------
1093 1094
	 *	set relation level write lock. If this is a "local" relation (not
	 *	visible to others), we don't need to set a write lock.
1095 1096
	 * ----------------
	 */
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
	if (!relation->rd_islocal)
		RelationSetLockForWrite(relation);

	/* ----------------
	 *	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).
	 * ----------------
	 */
	if (!OidIsValid(tup->t_oid))
	{
		tup->t_oid = newoid();
		LastOidProcessed = tup->t_oid;
	}
	else
		CheckMaxObjectId(tup->t_oid);

	TransactionIdStore(GetCurrentTransactionId(), &(tup->t_xmin));
	tup->t_cmin = GetCurrentCommandId();
	StoreInvalidTransactionId(&(tup->t_xmax));
V
Vadim B. Mikheev 已提交
1121 1122
	tup->t_infomask &= ~(HEAP_XACT_MASK);
	tup->t_infomask |= HEAP_XMAX_INVALID;
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

	doinsert(relation, tup);

	if (IsSystemRelationName(RelationGetRelationName(relation)->data))
	{
		RelationUnsetLockForWrite(relation);

		/* ----------------
		 *		invalidate caches (only works for system relations)
		 * ----------------
		 */
		RelationInvalidateHeapTuple(relation, tup);
	}

1137
	return tup->t_oid;
1138 1139 1140
}

/* ----------------
1141
 *		heap_delete		- delete a tuple
1142
 *
1143
 *		Must decide how to handle errors.
1144 1145
 * ----------------
 */
1146
int
1147 1148
heap_delete(Relation relation, ItemPointer tid)
{
1149 1150 1151
	ItemId		lp;
	HeapTuple	tp;
	PageHeader	dp;
1152
	Buffer		buf;
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_delete);
	IncrHeapAccessStat(global_delete);

	/* ----------------
	 *	sanity check
	 * ----------------
	 */
	Assert(ItemPointerIsValid(tid));

	/* ----------------
	 *	set relation level write lock
	 * ----------------
	 */
	RelationSetLockForWrite(relation);

1173
	buf = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1174

1175
#ifndef NO_BUFFERISVALID
1176
	if (!BufferIsValid(buf))
1177
	{							/* XXX L_SH better ??? */
1178
		elog(ERROR, "heap_delete: failed ReadBuffer");
1179
	}
1180
#endif	 /* NO_BUFFERISVALID */
1181

1182
	dp = (PageHeader) BufferGetPage(buf);
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
	lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(tid));

	/*
	 * Just like test against non-functional updates we try to catch
	 * non-functional delete attempts.			- vadim 05/05/97
	 */
	tp = (HeapTuple) PageGetItem((Page) dp, lp);
	Assert(HeapTupleIsValid(tp));
	if (TupleUpdatedByCurXactAndCmd(tp))
	{
1193

1194
		/*
1195 1196 1197
		 * Vadim says this is no longer needed 1998/6/15 elog(NOTICE,
		 * "Non-functional delete, tuple already deleted");
		 */
1198 1199
		if (IsSystemRelationName(RelationGetRelationName(relation)->data))
			RelationUnsetLockForWrite(relation);
1200
		ReleaseBuffer(buf);
1201
		return 1;
1202 1203 1204 1205 1206
	}
	/* ----------------
	 *	check that we're deleteing a valid item
	 * ----------------
	 */
1207
	HeapTupleSatisfies(lp, relation, buf, dp,
1208
					   false, 0, (ScanKey) NULL, tp);
1209
	if (!tp)
1210 1211 1212
	{

		/* XXX call something else */
1213
		ReleaseBuffer(buf);
1214

1215
		elog(ERROR, "heap_delete: (am)invalid tid");
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	}

	/* ----------------
	 *	get the tuple and lock tell the buffer manager we want
	 *	exclusive access to the page
	 * ----------------
	 */

	/* ----------------
	 *	store transaction information of xact deleting the tuple
	 * ----------------
	 */
	TransactionIdStore(GetCurrentTransactionId(), &(tp->t_xmax));
	tp->t_cmax = GetCurrentCommandId();
V
Vadim B. Mikheev 已提交
1230
	tp->t_infomask &= ~(HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID);
1231 1232 1233 1234 1235 1236 1237

	/* ----------------
	 *	invalidate caches
	 * ----------------
	 */
	RelationInvalidateHeapTuple(relation, tp);

1238
	WriteBuffer(buf);
1239 1240 1241
	if (IsSystemRelationName(RelationGetRelationName(relation)->data))
		RelationUnsetLockForWrite(relation);

1242
	return 0;
1243 1244 1245
}

/* ----------------
1246 1247 1248
 *		heap_replace	- replace a tuple
 *
 *		Must decide how to handle errors.
1249
 *
1250
 *		Fix arguments, work with indexes.
1251
 *
1252 1253 1254 1255
 *		12/30/93 - modified the return value to be 1 when
 *				   a non-functional update is detected. This
 *				   prevents the calling routine from updating
 *				   indices unnecessarily. -kw
1256 1257 1258 1259
 *
 * ----------------
 */
int
B
Bruce Momjian 已提交
1260
heap_replace(Relation relation, ItemPointer otid, HeapTuple replace_tuple)
1261
{
1262
	ItemId		lp;
B
Bruce Momjian 已提交
1263
	HeapTuple	old_tuple;
1264 1265
	Page		dp;
	Buffer		buffer;
1266
	HeapTuple	tuple;
1267

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_replace);
	IncrHeapAccessStat(global_replace);

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	Assert(ItemPointerIsValid(otid));

	/* ----------------
	 *	set relation level write lock
	 * ----------------
	 */
	if (!relation->rd_islocal)
		RelationSetLockForWrite(relation);

	buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(otid));
1289
#ifndef NO_BUFFERISVALID
1290 1291 1292
	if (!BufferIsValid(buffer))
	{
		/* XXX L_SH better ??? */
1293
		elog(ERROR, "amreplace: failed ReadBuffer");
1294
	}
1295
#endif	 /* NO_BUFFERISVALID */
1296 1297 1298 1299

	dp = (Page) BufferGetPage(buffer);
	lp = PageGetItemId(dp, ItemPointerGetOffsetNumber(otid));

1300
	/* ----------------
1301
	 *	logically delete old item
1302 1303
	 * ----------------
	 */
1304

B
Bruce Momjian 已提交
1305 1306
	old_tuple = (HeapTuple) PageGetItem(dp, lp);
	Assert(HeapTupleIsValid(old_tuple));
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318

	/* -----------------
	 *	the following test should be able to catch all non-functional
	 *	update attempts and shut out all ghost tuples.
	 *	XXX In the future, Spyros may need to update the rule lock on a tuple
	 *	more than once within the same command and same transaction.
	 *	He will have to introduce a new flag to override the following check.
	 *	-- Wei
	 *
	 * -----------------
	 */

B
Bruce Momjian 已提交
1319
	if (TupleUpdatedByCurXactAndCmd(old_tuple))
1320 1321 1322 1323 1324
	{
		elog(NOTICE, "Non-functional update, only first update is performed");
		if (IsSystemRelationName(RelationGetRelationName(relation)->data))
			RelationUnsetLockForWrite(relation);
		ReleaseBuffer(buffer);
1325
		return 1;
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
	}

	/* ----------------
	 *	check that we're replacing a valid item -
	 *
	 *	NOTE that this check must follow the non-functional update test
	 *		 above as it can happen that we try to 'replace' the same tuple
	 *		 twice in a single transaction.  The second time around the
	 *		 tuple will fail the NowTimeQual.  We don't want to abort the
	 *		 xact, we only want to flag the 'non-functional' NOTICE. -mer
	 * ----------------
	 */
1338
	HeapTupleSatisfies(lp,
1339 1340 1341 1342 1343 1344 1345
					   relation,
					   buffer,
					   (PageHeader) dp,
					   false,
					   0,
					   (ScanKey) NULL,
					   tuple);
1346
	if (!tuple)
1347 1348
	{
		ReleaseBuffer(buffer);
1349
		elog(ERROR, "heap_replace: (am)invalid otid");
1350 1351 1352
	}

	/* XXX order problems if not atomic assignment ??? */
B
Bruce Momjian 已提交
1353 1354 1355 1356 1357 1358
	replace_tuple->t_oid = old_tuple->t_oid;
	TransactionIdStore(GetCurrentTransactionId(), &(replace_tuple->t_xmin));
	replace_tuple->t_cmin = GetCurrentCommandId();
	StoreInvalidTransactionId(&(replace_tuple->t_xmax));
	replace_tuple->t_infomask &= ~(HEAP_XACT_MASK);
	replace_tuple->t_infomask |= HEAP_XMAX_INVALID;
1359 1360 1361 1362 1363

	/* ----------------
	 *	insert new item
	 * ----------------
	 */
B
Bruce Momjian 已提交
1364 1365
	if ((unsigned) DOUBLEALIGN(replace_tuple->t_len) <= PageGetFreeSpace((Page) dp))
		RelationPutHeapTuple(relation, BufferGetBlockNumber(buffer), replace_tuple);
1366 1367 1368 1369 1370 1371 1372
	else
	{
		/* ----------------
		 *	new item won't fit on same page as old item, have to look
		 *	for a new place to put it.
		 * ----------------
		 */
B
Bruce Momjian 已提交
1373
		doinsert(relation, replace_tuple);
1374 1375 1376 1377 1378 1379
	}

	/* ----------------
	 *	new item in place, now record transaction information
	 * ----------------
	 */
B
Bruce Momjian 已提交
1380 1381 1382
	TransactionIdStore(GetCurrentTransactionId(), &(old_tuple->t_xmax));
	old_tuple->t_cmax = GetCurrentCommandId();
	old_tuple->t_infomask &= ~(HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID);
1383 1384 1385 1386 1387

	/* ----------------
	 *	invalidate caches
	 * ----------------
	 */
B
Bruce Momjian 已提交
1388
	RelationInvalidateHeapTuple(relation, old_tuple);
1389 1390 1391 1392 1393 1394

	WriteBuffer(buffer);

	if (IsSystemRelationName(RelationGetRelationName(relation)->data))
		RelationUnsetLockForWrite(relation);

1395
	return 0;
1396 1397 1398
}

/* ----------------
1399
 *		heap_markpos	- mark scan position
1400
 *
1401 1402 1403 1404 1405 1406
 *		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.
1407
 *
1408 1409 1410
 *		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.
1411 1412 1413
 * ----------------
 */
void
1414
heap_markpos(HeapScanDesc scan)
1415
{
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

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

	/* Note: no locking manipulations needed */

1426 1427
	if (scan->rs_ptup == NULL &&
		BufferIsUnknown(scan->rs_pbuf))
1428
	{							/* == NONTUP */
1429 1430 1431 1432
		scan->rs_ptup = (HeapTuple)
			heapgettup(scan->rs_rd,
					   (scan->rs_ctup == NULL) ?
					   (ItemPointer) NULL : &scan->rs_ctup->t_ctid,
1433
					   -1,
1434 1435 1436 1437
					   &scan->rs_pbuf,
					   scan->rs_snapshot,
					   scan->rs_nkeys,
					   scan->rs_key);
1438 1439

	}
1440 1441
	else if (scan->rs_ntup == NULL &&
			 BufferIsUnknown(scan->rs_nbuf))
1442
	{							/* == NONTUP */
1443 1444 1445 1446
		scan->rs_ntup = (HeapTuple)
			heapgettup(scan->rs_rd,
					   (scan->rs_ctup == NULL) ?
					   (ItemPointer) NULL : &scan->rs_ctup->t_ctid,
1447
					   1,
1448 1449 1450 1451
					   &scan->rs_nbuf,
					   scan->rs_snapshot,
					   scan->rs_nkeys,
					   scan->rs_key);
1452 1453 1454 1455 1456 1457
	}

	/* ----------------
	 * Should not unpin the buffer pages.  They may still be in use.
	 * ----------------
	 */
1458 1459
	if (scan->rs_ptup != NULL)
		scan->rs_mptid = scan->rs_ptup->t_ctid;
1460
	else
1461 1462 1463
		ItemPointerSetInvalid(&scan->rs_mptid);
	if (scan->rs_ctup != NULL)
		scan->rs_mctid = scan->rs_ctup->t_ctid;
1464
	else
1465 1466 1467
		ItemPointerSetInvalid(&scan->rs_mctid);
	if (scan->rs_ntup != NULL)
		scan->rs_mntid = scan->rs_ntup->t_ctid;
1468
	else
1469
		ItemPointerSetInvalid(&scan->rs_mntid);
1470 1471 1472
}

/* ----------------
1473
 *		heap_restrpos	- restore position to marked location
1474
 *
1475 1476 1477 1478 1479
 *		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!!!
1480
 *
1481 1482 1483
 *		Now pins buffer once for each valid tuple pointer (rs_ptup,
 *		rs_ctup, rs_ntup) referencing it.
 *		 - 01/13/94
1484 1485
 *
 * XXX	might be better to do direct access instead of
1486
 *		using the generality of heapgettup().
1487 1488 1489 1490 1491 1492 1493
 *
 * 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
1494
heap_restrpos(HeapScanDesc scan)
1495
{
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
	/* ----------------
	 *	increment access statistics
	 * ----------------
	 */
	IncrHeapAccessStat(local_restrpos);
	IncrHeapAccessStat(global_restrpos);

	/* XXX no amrestrpos checking that ammarkpos called */

	/* Note: no locking manipulations needed */

1507
	unpinscan(scan);
1508 1509

	/* force heapgettup to pin buffer for each loaded tuple */
1510 1511 1512
	scan->rs_pbuf = InvalidBuffer;
	scan->rs_cbuf = InvalidBuffer;
	scan->rs_nbuf = InvalidBuffer;
1513

1514 1515
	if (!ItemPointerIsValid(&scan->rs_mptid))
		scan->rs_ptup = NULL;
1516 1517
	else
	{
1518 1519 1520
		scan->rs_ptup = (HeapTuple)
			heapgettup(scan->rs_rd,
					   &scan->rs_mptid,
1521
					   0,
1522
					   &scan->rs_pbuf,
1523
					   false,
1524 1525 1526 1527
					   0,
					   (ScanKey) NULL);
	}

1528 1529
	if (!ItemPointerIsValid(&scan->rs_mctid))
		scan->rs_ctup = NULL;
1530 1531
	else
	{
1532 1533 1534
		scan->rs_ctup = (HeapTuple)
			heapgettup(scan->rs_rd,
					   &scan->rs_mctid,
1535
					   0,
1536
					   &scan->rs_cbuf,
1537
					   false,
1538 1539 1540 1541
					   0,
					   (ScanKey) NULL);
	}

1542 1543
	if (!ItemPointerIsValid(&scan->rs_mntid))
		scan->rs_ntup = NULL;
1544 1545
	else
	{
1546 1547 1548
		scan->rs_ntup = (HeapTuple)
			heapgettup(scan->rs_rd,
					   &scan->rs_mntid,
1549
					   0,
1550
					   &scan->rs_nbuf,
1551
					   false,
1552 1553 1554
					   0,
					   (ScanKey) NULL);
	}
1555
}