tuplestore.c 27.0 KB
Newer Older
1 2 3 4 5 6 7 8
/*-------------------------------------------------------------------------
 *
 * tuplestore.c
 *	  Generalized routines for temporary tuple storage.
 *
 * This module handles temporary storage of tuples for purposes such
 * as Materialize nodes, hashjoin batch files, etc.  It is essentially
 * a dumbed-down version of tuplesort.c; it does no sorting of tuples
9 10
 * but can only store and regurgitate a sequence of tuples.  However,
 * because no sort is required, it is allowed to start reading the sequence
B
Bruce Momjian 已提交
11
 * before it has all been written.	This is particularly useful for cursors,
12 13
 * because it allows random access within the already-scanned portion of
 * a query without having to process the underlying scan to completion.
14 15 16 17
 * A temporary file is used to handle the data if it exceeds the
 * space limit specified by the caller.
 *
 * The (approximate) amount of memory allowed to the tuplestore is specified
B
Bruce Momjian 已提交
18
 * in kilobytes by the caller.	We absorb tuples and simply store them in an
19
 * in-memory array as long as we haven't exceeded maxKBytes.  If we do exceed
20
 * maxKBytes, we dump all the tuples into a temp file and then read from that
21
 * when needed.
22
 *
23
 * When the caller requests backward-scan capability, we write the temp file
24
 * in a format that allows either forward or backward scan.  Otherwise, only
25 26 27 28
 * forward scan is allowed.  Rewind and markpos/restorepos are normally allowed
 * but can be turned off via tuplestore_set_eflags; turning off both backward
 * scan and rewind enables truncation of the tuplestore at the mark point
 * (if any) for minimal memory usage.
29 30 31
 *
 * Because we allow reading before writing is complete, there are two
 * interesting positions in the temp file: the current read position and
B
Bruce Momjian 已提交
32
 * the current write position.	At any given instant, the temp file's seek
33 34
 * position corresponds to one of these, and the other one is remembered in
 * the Tuplestore's state.
35 36
 *
 *
37
 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
38 39 40
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * IDENTIFICATION
41
 *	  $PostgreSQL: pgsql/src/backend/utils/sort/tuplestore.c,v 1.32 2007/06/03 17:08:26 tgl Exp $
42 43 44 45 46 47 48
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include "access/heapam.h"
49
#include "commands/tablespace.h"
50
#include "executor/executor.h"
51
#include "storage/buffile.h"
52
#include "utils/memutils.h"
53 54
#include "utils/tuplestore.h"

55

56
/*
B
Bruce Momjian 已提交
57
 * Possible states of a Tuplestore object.	These denote the states that
58 59 60 61
 * persist between calls of Tuplestore routines.
 */
typedef enum
{
62 63 64
	TSS_INMEM,					/* Tuples still fit in memory */
	TSS_WRITEFILE,				/* Writing to temp file */
	TSS_READFILE				/* Reading from temp file */
65 66 67 68 69 70 71 72
} TupStoreStatus;

/*
 * Private state of a Tuplestore operation.
 */
struct Tuplestorestate
{
	TupStoreStatus status;		/* enumerated value as shown above */
73
	int			eflags;			/* capability flags */
74
	bool		interXact;		/* keep open through transactions? */
75 76 77 78
	long		availMem;		/* remaining memory available, in bytes */
	BufFile    *myfile;			/* underlying file, or NULL if none */

	/*
B
Bruce Momjian 已提交
79 80 81
	 * These function pointers decouple the routines that must know what kind
	 * of tuple we are handling from the routines that don't need to know it.
	 * They are set up by the tuplestore_begin_xxx routines.
82
	 *
B
Bruce Momjian 已提交
83 84 85
	 * (Although tuplestore.c currently only supports heap tuples, I've copied
	 * this part of tuplesort.c so that extension to other kinds of objects
	 * will be easy if it's ever needed.)
86
	 *
B
Bruce Momjian 已提交
87
	 * Function to copy a supplied input tuple into palloc'd space. (NB: we
B
Bruce Momjian 已提交
88 89 90
	 * assume that a single pfree() is enough to release the tuple later, so
	 * the representation must be "flat" in one palloc chunk.) state->availMem
	 * must be decreased by the amount of space used.
91 92 93 94
	 */
	void	   *(*copytup) (Tuplestorestate *state, void *tup);

	/*
B
Bruce Momjian 已提交
95 96 97 98 99
	 * Function to write a stored tuple onto tape.	The representation of the
	 * tuple on tape need not be the same as it is in memory; requirements on
	 * the tape representation are given below.  After writing the tuple,
	 * pfree() it, and increase state->availMem by the amount of memory space
	 * thereby released.
100 101 102 103
	 */
	void		(*writetup) (Tuplestorestate *state, void *tup);

	/*
B
Bruce Momjian 已提交
104 105 106 107
	 * Function to read a stored tuple from tape back into memory. 'len' is
	 * the already-read length of the stored tuple.  Create and return a
	 * palloc'd copy, and decrease state->availMem by the amount of memory
	 * space consumed.
108 109 110 111
	 */
	void	   *(*readtup) (Tuplestorestate *state, unsigned int len);

	/*
B
Bruce Momjian 已提交
112 113
	 * This array holds pointers to tuples in memory if we are in state INMEM.
	 * In states WRITEFILE and READFILE it's not used.
114 115 116 117 118 119
	 */
	void	  **memtuples;		/* array of pointers to palloc'd tuples */
	int			memtupcount;	/* number of tuples currently present */
	int			memtupsize;		/* allocated length of memtuples array */

	/*
120 121
	 * These variables are used to keep track of the current position.
	 *
122 123 124 125 126 127
	 * In state WRITEFILE, the current file seek position is the write point,
	 * and the read position is remembered in readpos_xxx; in state READFILE,
	 * the current file seek position is the read point, and the write
	 * position is remembered in writepos_xxx.	(The write position is the
	 * same as EOF, but since BufFileSeek doesn't currently implement
	 * SEEK_END, we have to remember it explicitly.)
128
	 *
129 130 131 132
	 * Special case: if we are in WRITEFILE state and eof_reached is true,
	 * then the read position is implicitly equal to the write position (and
	 * hence to the file seek position); this way we need not update the
	 * readpos_xxx variables on each write.
133
	 */
134 135 136 137 138
	bool		eof_reached;	/* read reached EOF (always valid) */
	int			current;		/* next array index (valid if INMEM) */
	int			readpos_file;	/* file# (valid if WRITEFILE and not eof) */
	long		readpos_offset; /* offset (valid if WRITEFILE and not eof) */
	int			writepos_file;	/* file# (valid if READFILE) */
B
Bruce Momjian 已提交
139
	long		writepos_offset;	/* offset (valid if READFILE) */
140 141

	/* markpos_xxx holds marked position for mark and restore */
B
Bruce Momjian 已提交
142
	int			markpos_current;	/* saved "current" */
143 144
	int			markpos_file;	/* saved "readpos_file" */
	long		markpos_offset; /* saved "readpos_offset" */
145 146 147
};

#define COPYTUP(state,tup)	((*(state)->copytup) (state, tup))
B
Bruce Momjian 已提交
148
#define WRITETUP(state,tup) ((*(state)->writetup) (state, tup))
149 150 151 152 153 154 155 156 157 158
#define READTUP(state,len)	((*(state)->readtup) (state, len))
#define LACKMEM(state)		((state)->availMem < 0)
#define USEMEM(state,amt)	((state)->availMem -= (amt))
#define FREEMEM(state,amt)	((state)->availMem += (amt))

/*--------------------
 *
 * NOTES about on-tape representation of tuples:
 *
 * We require the first "unsigned int" of a stored tuple to be the total size
159 160
 * on-tape of the tuple, including itself (so it is never zero).
 * The remainder of the stored tuple
161 162 163
 * may or may not match the in-memory representation of the tuple ---
 * any conversion needed is the job of the writetup and readtup routines.
 *
164 165
 * If state->eflags & EXEC_FLAG_BACKWARD, then the stored representation of
 * the tuple must be followed by another "unsigned int" that is a copy of the
166 167
 * length --- so the total tape space used is actually sizeof(unsigned int)
 * more than the stored length value.  This allows read-backwards.	When
168
 * EXEC_FLAG_BACKWARD is not set, the write/read routines may omit the extra
169 170 171 172 173 174 175 176
 * length word.
 *
 * writetup is expected to write both length words as well as the tuple
 * data.  When readtup is called, the tape is positioned just after the
 * front length word; readtup must read the tuple data and advance past
 * the back length word (if present).
 *
 * The write/read routines can make use of the tuple description data
B
Bruce Momjian 已提交
177
 * stored in the Tuplestorestate record, if needed. They are also expected
178 179
 * to adjust state->availMem by the amount of memory space (not tape space!)
 * released or consumed.  There is no error return from either writetup
180
 * or readtup; they should ereport() on failure.
181 182 183 184
 *
 *
 * NOTES about memory consumption calculations:
 *
185 186 187
 * We count space allocated for tuples against the maxKBytes limit,
 * plus the space used by the variable-size array memtuples.
 * Fixed-size space (primarily the BufFile I/O buffer) is not counted.
188
 *
189 190 191 192 193
 * Note that we count actual space used (as shown by GetMemoryChunkSpace)
 * rather than the originally-requested size.  This is important since
 * palloc can add substantial overhead.  It's not a complete answer since
 * we won't count any wasted space in palloc allocation blocks, but it's
 * a lot better than what we were doing before 7.3.
194 195 196 197 198
 *
 *--------------------
 */


199
static Tuplestorestate *tuplestore_begin_common(int eflags,
B
Bruce Momjian 已提交
200 201
						bool interXact,
						int maxKBytes);
202
static void tuplestore_puttuple_common(Tuplestorestate *state, void *tuple);
203
static void dumptuples(Tuplestorestate *state);
204
static void tuplestore_trim(Tuplestorestate *state, int ntuples);
205 206 207 208 209 210 211 212 213 214 215 216
static unsigned int getlen(Tuplestorestate *state, bool eofOK);
static void *copytup_heap(Tuplestorestate *state, void *tup);
static void writetup_heap(Tuplestorestate *state, void *tup);
static void *readtup_heap(Tuplestorestate *state, unsigned int len);


/*
 *		tuplestore_begin_xxx
 *
 * Initialize for a tuple store operation.
 */
static Tuplestorestate *
217
tuplestore_begin_common(int eflags, bool interXact, int maxKBytes)
218 219 220
{
	Tuplestorestate *state;

221
	state = (Tuplestorestate *) palloc0(sizeof(Tuplestorestate));
222

223
	state->status = TSS_INMEM;
224
	state->eflags = eflags;
225
	state->interXact = interXact;
226 227 228 229
	state->availMem = maxKBytes * 1024L;
	state->myfile = NULL;

	state->memtupcount = 0;
B
Bruce Momjian 已提交
230
	state->memtupsize = 1024;	/* initial guess */
231 232
	state->memtuples = (void **) palloc(state->memtupsize * sizeof(void *));

233 234
	USEMEM(state, GetMemoryChunkSpace(state->memtuples));

235 236 237
	state->eof_reached = false;
	state->current = 0;

238 239 240
	return state;
}

241 242 243 244 245 246 247 248 249 250
/*
 * tuplestore_begin_heap
 *
 * Create a new tuplestore; other types of tuple stores (other than
 * "heap" tuple stores, for heap tuples) are possible, but not presently
 * implemented.
 *
 * randomAccess: if true, both forward and backward accesses to the
 * tuple store are allowed.
 *
251
 * interXact: if true, the files used for on-disk storage persist beyond the
B
Bruce Momjian 已提交
252
 * end of the current transaction.	NOTE: It's the caller's responsibility to
253 254 255
 * create such a tuplestore in a memory context that will also survive
 * transaction boundaries, and to ensure the tuplestore is closed when it's
 * no longer wanted.
256 257
 *
 * maxKBytes: how much data to store in memory (any data beyond this
258
 * amount is paged to disk).  When in doubt, use work_mem.
259
 */
260
Tuplestorestate *
261
tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
262
{
263 264 265 266 267 268 269 270 271 272 273 274
	Tuplestorestate *state;
	int		eflags;

	/*
	 * This interpretation of the meaning of randomAccess is compatible
	 * with the pre-8.3 behavior of tuplestores.
	 */
	eflags = randomAccess ?
		(EXEC_FLAG_BACKWARD | EXEC_FLAG_REWIND | EXEC_FLAG_MARK) :
		(EXEC_FLAG_REWIND | EXEC_FLAG_MARK);

	state = tuplestore_begin_common(eflags, interXact, maxKBytes);
275 276 277 278 279 280 281 282

	state->copytup = copytup_heap;
	state->writetup = writetup_heap;
	state->readtup = readtup_heap;

	return state;
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
/*
 * tuplestore_set_eflags
 *
 * Set capability flags at a finer grain than is allowed by
 * tuplestore_begin_xxx.  This must be called before inserting any data
 * into the tuplestore.
 *
 * eflags is a bitmask following the meanings used for executor node
 * startup flags (see executor.h).  tuplestore pays attention to these bits:
 *		EXEC_FLAG_REWIND		need rewind to start
 *		EXEC_FLAG_BACKWARD		need backward fetch
 *		EXEC_FLAG_MARK			need mark/restore
 * If tuplestore_set_eflags is not called, REWIND and MARK are allowed,
 * and BACKWARD is set per "randomAccess" in the tuplestore_begin_xxx call.
 */
void
tuplestore_set_eflags(Tuplestorestate *state, int eflags)
{
	Assert(state->status == TSS_INMEM);
	Assert(state->memtupcount == 0);

	state->eflags = eflags;
}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
/*
 * tuplestore_end
 *
 *	Release resources and clean up.
 */
void
tuplestore_end(Tuplestorestate *state)
{
	int			i;

	if (state->myfile)
		BufFileClose(state->myfile);
	if (state->memtuples)
	{
		for (i = 0; i < state->memtupcount; i++)
			pfree(state->memtuples[i]);
		pfree(state->memtuples);
	}
}

/*
328 329 330 331 332 333 334 335 336 337 338 339
 * tuplestore_ateof
 *
 * Returns the current eof_reached state.
 */
bool
tuplestore_ateof(Tuplestorestate *state)
{
	return state->eof_reached;
}

/*
 * Accept one tuple and append it to the tuplestore.
340 341
 *
 * Note that the input tuple is always copied; the caller need not save it.
342 343 344 345
 *
 * If the read status is currently "AT EOF" then it remains so (the read
 * pointer advances along with the write pointer); otherwise the read
 * pointer is unchanged.  This is for the convenience of nodeMaterial.c.
346 347 348
 *
 * tuplestore_puttupleslot() is a convenience routine to collect data from
 * a TupleTableSlot without an extra copy operation.
349 350
 */
void
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
tuplestore_puttupleslot(Tuplestorestate *state,
						TupleTableSlot *slot)
{
	MinimalTuple tuple;

	/*
	 * Form a MinimalTuple in working memory
	 */
	tuple = ExecCopySlotMinimalTuple(slot);
	USEMEM(state, GetMemoryChunkSpace(tuple));

	tuplestore_puttuple_common(state, (void *) tuple);
}

/*
 * "Standard" case to copy from a HeapTuple.  This is actually now somewhat
 * deprecated, but not worth getting rid of in view of the number of callers.
 * (Consider adding something that takes a tupdesc+values/nulls arrays so
 * that we can use heap_form_minimal_tuple() and avoid a copy step.)
 */
void
tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
373 374
{
	/*
B
Bruce Momjian 已提交
375
	 * Copy the tuple.	(Must do this even in WRITEFILE case.)
376 377 378
	 */
	tuple = COPYTUP(state, tuple);

379 380 381 382 383 384
	tuplestore_puttuple_common(state, (void *) tuple);
}

static void
tuplestore_puttuple_common(Tuplestorestate *state, void *tuple)
{
385 386
	switch (state->status)
	{
387
		case TSS_INMEM:
B
Bruce Momjian 已提交
388

389 390 391 392 393 394 395
			/*
			 * Grow the array as needed.  Note that we try to grow the array
			 * when there is still one free slot remaining --- if we fail,
			 * there'll still be room to store the incoming tuple, and then
			 * we'll switch to tape-based operation.
			 */
			if (state->memtupcount >= state->memtupsize - 1)
396
			{
397 398 399 400 401 402 403 404 405 406 407 408 409 410
				/*
				 * See grow_memtuples() in tuplesort.c for the rationale
				 * behind these two tests.
				 */
				if (state->availMem > (long) (state->memtupsize * sizeof(void *)) &&
					(Size) (state->memtupsize * 2) < MaxAllocSize / sizeof(void *))
				{
					FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
					state->memtupsize *= 2;
					state->memtuples = (void **)
						repalloc(state->memtuples,
								 state->memtupsize * sizeof(void *));
					USEMEM(state, GetMemoryChunkSpace(state->memtuples));
				}
411
			}
412 413

			/* Stash the tuple in the in-memory array */
414 415
			state->memtuples[state->memtupcount++] = tuple;

416 417 418 419
			/* If eof_reached, keep read position in sync */
			if (state->eof_reached)
				state->current = state->memtupcount;

420
			/*
421
			 * Done if we still fit in available memory and have array slots.
422
			 */
423
			if (state->memtupcount < state->memtupsize && !LACKMEM(state))
424 425 426 427
				return;

			/*
			 * Nope; time to switch to tape-based operation.
428 429 430 431
			 *
			 * If the temp table is slated to outlive the current transaction,
			 * force it into my database's default tablespace, so that it will
			 * not pose a threat to possible tablespace drop attempts.
432
			 */
433 434 435
			state->myfile = BufFileCreateTemp(state->interXact,
											  state->interXact ? InvalidOid :
											  GetTempTablespace());
436 437 438 439 440 441
			state->status = TSS_WRITEFILE;
			dumptuples(state);
			break;
		case TSS_WRITEFILE:
			WRITETUP(state, tuple);
			break;
442
		case TSS_READFILE:
B
Bruce Momjian 已提交
443

444
			/*
445
			 * Switch from reading to writing.
446
			 */
447 448 449 450 451 452
			if (!state->eof_reached)
				BufFileTell(state->myfile,
							&state->readpos_file, &state->readpos_offset);
			if (BufFileSeek(state->myfile,
							state->writepos_file, state->writepos_offset,
							SEEK_SET) != 0)
453
				elog(ERROR, "seek to EOF failed");
454 455
			state->status = TSS_WRITEFILE;
			WRITETUP(state, tuple);
456 457
			break;
		default:
458
			elog(ERROR, "invalid tuplestore state");
459 460 461 462 463 464 465 466
			break;
	}
}

/*
 * Fetch the next tuple in either forward or back direction.
 * Returns NULL if no more tuples.	If should_free is set, the
 * caller must pfree the returned tuple when done with it.
467 468 469
 *
 * Backward scan is only allowed if randomAccess was set true or
 * EXEC_FLAG_BACKWARD was specified to tuplestore_set_eflags().
470
 */
471
static void *
472
tuplestore_gettuple(Tuplestorestate *state, bool forward,
B
Bruce Momjian 已提交
473
					bool *should_free)
474 475 476 477
{
	unsigned int tuplen;
	void	   *tup;

478
	Assert(forward || (state->eflags & EXEC_FLAG_BACKWARD));
479

480 481
	switch (state->status)
	{
482
		case TSS_INMEM:
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
			*should_free = false;
			if (forward)
			{
				if (state->current < state->memtupcount)
					return state->memtuples[state->current++];
				state->eof_reached = true;
				return NULL;
			}
			else
			{
				if (state->current <= 0)
					return NULL;

				/*
				 * if all tuples are fetched already then we return last
				 * tuple, else - tuple before last returned.
				 */
				if (state->eof_reached)
					state->eof_reached = false;
				else
				{
					state->current--;	/* last returned tuple */
					if (state->current <= 0)
						return NULL;
				}
				return state->memtuples[state->current - 1];
			}
			break;

512 513 514 515
		case TSS_WRITEFILE:
			/* Skip state change if we'll just return NULL */
			if (state->eof_reached && forward)
				return NULL;
B
Bruce Momjian 已提交
516

517 518 519 520 521 522 523
			/*
			 * Switch from writing to reading.
			 */
			BufFileTell(state->myfile,
						&state->writepos_file, &state->writepos_offset);
			if (!state->eof_reached)
				if (BufFileSeek(state->myfile,
B
Bruce Momjian 已提交
524
								state->readpos_file, state->readpos_offset,
525
								SEEK_SET) != 0)
526
					elog(ERROR, "seek failed");
527 528 529
			state->status = TSS_READFILE;
			/* FALL THRU into READFILE case */

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
		case TSS_READFILE:
			*should_free = true;
			if (forward)
			{
				if ((tuplen = getlen(state, true)) != 0)
				{
					tup = READTUP(state, tuplen);
					return tup;
				}
				else
				{
					state->eof_reached = true;
					return NULL;
				}
			}

			/*
			 * Backward.
			 *
549 550
			 * if all tuples are fetched already then we return last tuple,
			 * else - tuple before last returned.
551
			 *
552 553
			 * Back up to fetch previously-returned tuple's ending length
			 * word. If seek fails, assume we are at start of file.
554
			 */
555 556 557 558 559
			if (BufFileSeek(state->myfile, 0, -(long) sizeof(unsigned int),
							SEEK_CUR) != 0)
				return NULL;
			tuplen = getlen(state, false);

560 561 562
			if (state->eof_reached)
			{
				state->eof_reached = false;
563
				/* We will return the tuple returned before returning NULL */
564 565 566 567 568 569 570
			}
			else
			{
				/*
				 * Back up to get ending length word of tuple before it.
				 */
				if (BufFileSeek(state->myfile, 0,
B
Bruce Momjian 已提交
571
								-(long) (tuplen + 2 * sizeof(unsigned int)),
572 573 574
								SEEK_CUR) != 0)
				{
					/*
B
Bruce Momjian 已提交
575 576 577 578
					 * If that fails, presumably the prev tuple is the first
					 * in the file.  Back up so that it becomes next to read
					 * in forward direction (not obviously right, but that is
					 * what in-memory case does).
579 580
					 */
					if (BufFileSeek(state->myfile, 0,
B
Bruce Momjian 已提交
581
									-(long) (tuplen + sizeof(unsigned int)),
582
									SEEK_CUR) != 0)
583
						elog(ERROR, "bogus tuple length in backward scan");
584 585
					return NULL;
				}
586
				tuplen = getlen(state, false);
587 588 589
			}

			/*
B
Bruce Momjian 已提交
590 591 592
			 * Now we have the length of the prior tuple, back up and read it.
			 * Note: READTUP expects we are positioned after the initial
			 * length word of the tuple, so back up to that point.
593 594
			 */
			if (BufFileSeek(state->myfile, 0,
B
Bruce Momjian 已提交
595
							-(long) tuplen,
596
							SEEK_CUR) != 0)
597
				elog(ERROR, "bogus tuple length in backward scan");
598 599 600 601
			tup = READTUP(state, tuplen);
			return tup;

		default:
602
			elog(ERROR, "invalid tuplestore state");
603 604 605 606
			return NULL;		/* keep compiler quiet */
	}
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
/*
 * tuplestore_gettupleslot - exported function to fetch a MinimalTuple
 *
 * If successful, put tuple in slot and return TRUE; else, clear the slot
 * and return FALSE.
 */
bool
tuplestore_gettupleslot(Tuplestorestate *state, bool forward,
						TupleTableSlot *slot)
{
	MinimalTuple tuple;
	bool		should_free;

	tuple = (MinimalTuple) tuplestore_gettuple(state, forward, &should_free);

	if (tuple)
	{
		ExecStoreMinimalTuple(tuple, slot, should_free);
		return true;
	}
	else
	{
		ExecClearTuple(slot);
		return false;
	}
}

/*
 * tuplestore_advance - exported function to adjust position without fetching
 *
 * We could optimize this case to avoid palloc/pfree overhead, but for the
 * moment it doesn't seem worthwhile.
 */
bool
tuplestore_advance(Tuplestorestate *state, bool forward)
{
	void	   *tuple;
	bool		should_free;

	tuple = tuplestore_gettuple(state, forward, &should_free);

	if (tuple)
	{
		if (should_free)
			pfree(tuple);
		return true;
	}
	else
	{
		return false;
	}
}

660 661
/*
 * dumptuples - remove tuples from memory and write to tape
662 663 664 665
 *
 * As a side effect, we must set readpos and markpos to the value
 * corresponding to "current"; otherwise, a dump would lose the current read
 * position.
666 667 668 669 670 671
 */
static void
dumptuples(Tuplestorestate *state)
{
	int			i;

B
Bruce Momjian 已提交
672
	for (i = 0;; i++)
673 674 675 676 677 678 679 680 681
	{
		if (i == state->current)
			BufFileTell(state->myfile,
						&state->readpos_file, &state->readpos_offset);
		if (i == state->markpos_current)
			BufFileTell(state->myfile,
						&state->markpos_file, &state->markpos_offset);
		if (i >= state->memtupcount)
			break;
682
		WRITETUP(state, state->memtuples[i]);
683
	}
684 685 686 687 688 689 690 691 692
	state->memtupcount = 0;
}

/*
 * tuplestore_rescan		- rewind and replay the scan
 */
void
tuplestore_rescan(Tuplestorestate *state)
{
693 694
	Assert(state->eflags & EXEC_FLAG_REWIND);

695 696
	switch (state->status)
	{
697 698
		case TSS_INMEM:
			state->eof_reached = false;
699
			state->current = 0;
700 701
			break;
		case TSS_WRITEFILE:
702
			state->eof_reached = false;
703 704
			state->readpos_file = 0;
			state->readpos_offset = 0L;
705 706
			break;
		case TSS_READFILE:
707
			state->eof_reached = false;
708
			if (BufFileSeek(state->myfile, 0, 0L, SEEK_SET) != 0)
709
				elog(ERROR, "seek to start failed");
710 711
			break;
		default:
712
			elog(ERROR, "invalid tuplestore state");
713 714 715 716 717 718 719 720 721 722
			break;
	}
}

/*
 * tuplestore_markpos	- saves current position in the tuple sequence
 */
void
tuplestore_markpos(Tuplestorestate *state)
{
723 724
	Assert(state->eflags & EXEC_FLAG_MARK);

725 726
	switch (state->status)
	{
727 728
		case TSS_INMEM:
			state->markpos_current = state->current;
729 730 731 732 733 734 735 736 737 738 739 740 741 742
			/*
			 * We can truncate the tuplestore if neither backward scan nor
			 * rewind capability are required by the caller.  There will
			 * never be a need to back up past the mark point.
			 *
			 * Note: you might think we could remove all the tuples before
			 * "current", since that one is the next to be returned.  However,
			 * since tuplestore_gettuple returns a direct pointer to our
			 * internal copy of the tuple, it's likely that the caller has
			 * still got the tuple just before "current" referenced in a slot.
			 * Don't free it yet.
			 */
			if (!(state->eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_REWIND)))
				tuplestore_trim(state, 1);
743 744 745 746 747 748 749 750 751 752 753 754 755 756
			break;
		case TSS_WRITEFILE:
			if (state->eof_reached)
			{
				/* Need to record the implicit read position */
				BufFileTell(state->myfile,
							&state->markpos_file,
							&state->markpos_offset);
			}
			else
			{
				state->markpos_file = state->readpos_file;
				state->markpos_offset = state->readpos_offset;
			}
757 758 759 760 761 762 763
			break;
		case TSS_READFILE:
			BufFileTell(state->myfile,
						&state->markpos_file,
						&state->markpos_offset);
			break;
		default:
764
			elog(ERROR, "invalid tuplestore state");
765 766 767 768 769 770 771 772 773 774 775
			break;
	}
}

/*
 * tuplestore_restorepos - restores current position in tuple sequence to
 *						  last saved position
 */
void
tuplestore_restorepos(Tuplestorestate *state)
{
776 777
	Assert(state->eflags & EXEC_FLAG_MARK);

778 779
	switch (state->status)
	{
780 781 782 783 784 785 786 787
		case TSS_INMEM:
			state->eof_reached = false;
			state->current = state->markpos_current;
			break;
		case TSS_WRITEFILE:
			state->eof_reached = false;
			state->readpos_file = state->markpos_file;
			state->readpos_offset = state->markpos_offset;
788 789
			break;
		case TSS_READFILE:
790
			state->eof_reached = false;
791 792 793 794 795 796 797
			if (BufFileSeek(state->myfile,
							state->markpos_file,
							state->markpos_offset,
							SEEK_SET) != 0)
				elog(ERROR, "tuplestore_restorepos failed");
			break;
		default:
798
			elog(ERROR, "invalid tuplestore state");
799 800 801 802
			break;
	}
}

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
/*
 * tuplestore_trim	- remove all but ntuples tuples before current
 */
static void
tuplestore_trim(Tuplestorestate *state, int ntuples)
{
	int			nremove;
	int			i;

	/*
	 * We don't bother trimming temp files since it usually would mean more
	 * work than just letting them sit in kernel buffers until they age out.
	 */
	if (state->status != TSS_INMEM)
		return;

	nremove = state->current - ntuples;
	if (nremove <= 0)
		return;					/* nothing to do */
	Assert(nremove <= state->memtupcount);

	/* Release no-longer-needed tuples */
	for (i = 0; i < nremove; i++)
	{
		FREEMEM(state, GetMemoryChunkSpace(state->memtuples[i]));
		pfree(state->memtuples[i]);
	}

	/*
	 * Slide the array down and readjust pointers.  This may look pretty
	 * stupid, but we expect that there will usually not be very many
	 * tuple-pointers to move, so this isn't that expensive; and it keeps
	 * a lot of other logic simple.
	 *
	 * In fact, in the current usage for merge joins, it's demonstrable that
	 * there will always be exactly one non-removed tuple; so optimize that
	 * case.
	 */
	if (nremove + 1 == state->memtupcount)
		state->memtuples[0] = state->memtuples[nremove];
	else
		memmove(state->memtuples, state->memtuples + nremove,
				(state->memtupcount - nremove) * sizeof(void *));

	state->memtupcount -= nremove;
	state->current -= nremove;
	state->markpos_current -= nremove;
}

852 853 854 855 856 857 858 859 860

/*
 * Tape interface routines
 */

static unsigned int
getlen(Tuplestorestate *state, bool eofOK)
{
	unsigned int len;
861
	size_t		nbytes;
862

863 864 865 866
	nbytes = BufFileRead(state->myfile, (void *) &len, sizeof(len));
	if (nbytes == sizeof(len))
		return len;
	if (nbytes != 0)
867
		elog(ERROR, "unexpected end of tape");
868
	if (!eofOK)
869
		elog(ERROR, "unexpected end of data");
870
	return 0;
871 872 873 874 875
}


/*
 * Routines specialized for HeapTuple case
876 877 878 879 880 881
 *
 * The stored form is actually a MinimalTuple, but for largely historical
 * reasons we allow COPYTUP to work from a HeapTuple.
 *
 * Since MinimalTuple already has length in its first word, we don't need
 * to write that separately.
882 883 884 885 886
 */

static void *
copytup_heap(Tuplestorestate *state, void *tup)
{
887
	MinimalTuple tuple;
888

889
	tuple = minimal_tuple_from_heap_tuple((HeapTuple) tup);
890 891
	USEMEM(state, GetMemoryChunkSpace(tuple));
	return (void *) tuple;
892 893 894 895 896
}

static void
writetup_heap(Tuplestorestate *state, void *tup)
{
897 898
	MinimalTuple tuple = (MinimalTuple) tup;
	unsigned int tuplen = tuple->t_len;
899

900
	if (BufFileWrite(state->myfile, (void *) tuple, tuplen) != (size_t) tuplen)
901
		elog(ERROR, "write failed");
902
	if (state->eflags & EXEC_FLAG_BACKWARD)	/* need trailing length word? */
903 904
		if (BufFileWrite(state->myfile, (void *) &tuplen,
						 sizeof(tuplen)) != sizeof(tuplen))
905
			elog(ERROR, "write failed");
906

907
	FREEMEM(state, GetMemoryChunkSpace(tuple));
908
	heap_free_minimal_tuple(tuple);
909 910 911 912 913
}

static void *
readtup_heap(Tuplestorestate *state, unsigned int len)
{
914 915
	MinimalTuple tuple = (MinimalTuple) palloc(len);
	unsigned int tuplen;
916

917
	USEMEM(state, GetMemoryChunkSpace(tuple));
918
	/* read in the tuple proper */
919 920 921
	tuple->t_len = len;
	if (BufFileRead(state->myfile, (void *) ((char *) tuple + sizeof(int)),
					len - sizeof(int)) != (size_t) (len - sizeof(int)))
922
		elog(ERROR, "unexpected end of data");
923
	if (state->eflags & EXEC_FLAG_BACKWARD)	/* need trailing length word? */
924 925
		if (BufFileRead(state->myfile, (void *) &tuplen,
						sizeof(tuplen)) != sizeof(tuplen))
926
			elog(ERROR, "unexpected end of data");
927 928
	return (void *) tuple;
}