nodeHashjoin.c 21.0 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * nodeHashjoin.c--
4
 *	  Routines to handle hash join nodes
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/executor/nodeHashjoin.c,v 1.7 1997/09/08 02:22:43 momjian Exp $
11 12 13
 *
 *-------------------------------------------------------------------------
 */
14
#include <sys/types.h>
15
#include <string.h>
16
#include <sys/file.h>
17 18 19 20
#include <sys/stat.h>
#include <fcntl.h>


21

B
Bruce Momjian 已提交
22
#include "postgres.h"
23 24
#include "storage/bufmgr.h"		/* for BLCKSZ */
#include "storage/fd.h"			/* for SEEK_ */
25
#include "executor/executor.h"
26
#include "executor/execdebug.h"
27 28 29 30 31 32 33 34 35
#include "executor/nodeHash.h"
#include "executor/nodeHashjoin.h"

#include "optimizer/clauses.h"	/* for get_leftop */


#include "utils/palloc.h"

static TupleTableSlot *
36
			ExecHashJoinOuterGetTuple(Plan * node, Plan * parent, HashJoinState * hjstate);
37 38

static TupleTableSlot *
39 40
ExecHashJoinGetSavedTuple(HashJoinState * hjstate, char *buffer,
	 File file, TupleTableSlot * tupleSlot, int *block, char **position);
41

42 43 44
static int
ExecHashJoinGetBatch(int bucketno, HashJoinTable hashtable,
					 int nbatch);
45

46
static int	ExecHashJoinNewBatch(HashJoinState * hjstate);
47 48 49



50
/* ----------------------------------------------------------------
51
 *		ExecHashJoin
52
 *
53 54 55 56
 *		This function implements the Hybrid Hashjoin algorithm.
 *		recursive partitioning remains to be added.
 *		Note: the relation we build hash table on is the inner
 *			  the other one is outer.
57 58
 * ----------------------------------------------------------------
 */
59 60
TupleTableSlot *				/* return: a tuple or NULL */
ExecHashJoin(HashJoin * node)
61
{
62 63 64 65 66 67 68 69
	HashJoinState *hjstate;
	EState	   *estate;
	Plan	   *outerNode;
	Hash	   *hashNode;
	List	   *hjclauses;
	Expr	   *clause;
	List	   *qual;
	ScanDirection dir;
70
	TupleTableSlot *inntuple;
71 72
	Var		   *outerVar;
	ExprContext *econtext;
73

74 75 76 77
	HashJoinTable hashtable;
	int			bucketno;
	HashBucket	bucket;
	HeapTuple	curtuple;
78

79
	bool		qualResult;
80 81 82

	TupleTableSlot *outerTupleSlot;
	TupleTableSlot *innerTupleSlot;
83 84 85 86 87 88 89 90 91 92 93 94
	int			nbatch;
	int			curbatch;
	File	   *outerbatches;
	RelativeAddr *outerbatchNames;
	RelativeAddr *outerbatchPos;
	Var		   *innerhashkey;
	int			batch;
	int			batchno;
	char	   *buffer;
	int			i;
	bool		hashPhaseDone;
	char	   *pos;
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

	/* ----------------
	 *	get information from HashJoin node
	 * ----------------
	 */
	hjstate = node->hashjoinstate;
	hjclauses = node->hashclauses;
	clause = lfirst(hjclauses);
	estate = node->join.state;
	qual = node->join.qual;
	hashNode = (Hash *) innerPlan(node);
	outerNode = outerPlan(node);
	hashPhaseDone = node->hashdone;

	dir = estate->es_direction;

111
	/* -----------------
112
	 * get information from HashJoin state
113 114
	 * -----------------
	 */
115 116 117
	hashtable = hjstate->hj_HashTable;
	bucket = hjstate->hj_CurBucket;
	curtuple = hjstate->hj_CurTuple;
118

119 120 121
	/* --------------------
	 * initialize expression context
	 * --------------------
122
	 */
123 124 125 126 127
	econtext = hjstate->jstate.cs_ExprContext;

	if (hjstate->jstate.cs_TupFromTlist)
	{
		TupleTableSlot *result;
128
		bool		isDone;
129 130 131 132

		result = ExecProject(hjstate->jstate.cs_ProjInfo, &isDone);
		if (!isDone)
			return result;
133 134
	}
	/* ----------------
135
	 *	if this is the first call, build the hash table for inner relation
136 137
	 * ----------------
	 */
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
	if (!hashPhaseDone)
	{							/* if the hash phase not completed */
		hashtable = node->hashjointable;
		if (hashtable == NULL)
		{						/* if the hash table has not been created */
			/* ----------------
			 * create the hash table
			 * ----------------
			 */
			hashtable = ExecHashTableCreate(hashNode);
			hjstate->hj_HashTable = hashtable;
			innerhashkey = hashNode->hashkey;
			hjstate->hj_InnerHashKey = innerhashkey;

			/* ----------------
			 * execute the Hash node, to build the hash table
			 * ----------------
			 */
			hashNode->hashtable = hashtable;
			innerTupleSlot = ExecProcNode((Plan *) hashNode, (Plan *) node);
		}
		bucket = NULL;
		curtuple = NULL;
		curbatch = 0;
		node->hashdone = true;
163
	}
164 165 166 167 168 169 170 171
	nbatch = hashtable->nbatch;
	outerbatches = hjstate->hj_OuterBatches;
	if (nbatch > 0 && outerbatches == NULL)
	{							/* if needs hash partition */
		/* -----------------
		 *	allocate space for file descriptors of outer batch files
		 *	then open the batch files in the current process
		 * -----------------
172
		 */
173 174 175 176 177 178 179 180 181 182 183
		innerhashkey = hashNode->hashkey;
		hjstate->hj_InnerHashKey = innerhashkey;
		outerbatchNames = (RelativeAddr *)
			ABSADDR(hashtable->outerbatchNames);
		outerbatches = (File *)
			palloc(nbatch * sizeof(File));
		for (i = 0; i < nbatch; i++)
		{
			outerbatches[i] = FileNameOpenFile(
											 ABSADDR(outerbatchNames[i]),
											   O_CREAT | O_RDWR, 0600);
184
		}
185 186 187 188 189 190 191 192 193
		hjstate->hj_OuterBatches = outerbatches;

		/* ------------------
		 *	get the inner batch file descriptors from the
		 *	hash node
		 * ------------------
		 */
		hjstate->hj_InnerBatches =
			hashNode->hashstate->hashBatches;
194
	}
195 196 197 198
	outerbatchPos = (RelativeAddr *) ABSADDR(hashtable->outerbatchPos);
	curbatch = hashtable->curbatch;
	outerbatchNames = (RelativeAddr *) ABSADDR(hashtable->outerbatchNames);

199
	/* ----------------
200
	 *	Now get an outer tuple and probe into the hash table for matches
201 202
	 * ----------------
	 */
203 204 205 206 207 208 209 210
	outerTupleSlot = hjstate->jstate.cs_OuterTupleSlot;
	outerVar = get_leftop(clause);

	bucketno = -1;				/* if bucketno remains -1, means use old
								 * outer tuple */
	if (TupIsNull(outerTupleSlot))
	{

211
		/*
212
		 * if the current outer tuple is nil, get a new one
213
		 */
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
		outerTupleSlot = (TupleTableSlot *)
			ExecHashJoinOuterGetTuple(outerNode, (Plan *) node, hjstate);

		while (curbatch <= nbatch && TupIsNull(outerTupleSlot))
		{

			/*
			 * if the current batch runs out, switch to new batch
			 */
			curbatch = ExecHashJoinNewBatch(hjstate);
			if (curbatch > nbatch)
			{

				/*
				 * when the last batch runs out, clean up
				 */
				ExecHashTableDestroy(hashtable);
				hjstate->hj_HashTable = NULL;
				return NULL;
			}
			else
				outerTupleSlot = (TupleTableSlot *)
					ExecHashJoinOuterGetTuple(outerNode, (Plan *) node, hjstate);
		}

		/*
		 * now we get an outer tuple, find the corresponding bucket for
		 * this tuple from the hash table
		 */
		econtext->ecxt_outertuple = outerTupleSlot;

#ifdef HJDEBUG
		printf("Probing ");
#endif
		bucketno = ExecHashGetBucket(hashtable, econtext, outerVar);
		bucket = (HashBucket) (ABSADDR(hashtable->top)
							   + bucketno * hashtable->bucketsize);
251
	}
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

	for (;;)
	{
		/* ----------------
		 *		Now we've got an outer tuple and the corresponding hash bucket,
		 *	but this tuple may not belong to the current batch.
		 * ----------------
		 */
		if (curbatch == 0 && bucketno != -1)	/* if this is the first
												 * pass */
			batch = ExecHashJoinGetBatch(bucketno, hashtable, nbatch);
		else
			batch = 0;
		if (batch > 0)
		{

			/*
			 * if the current outer tuple does not belong to the current
			 * batch, save to the tmp file for the corresponding batch.
			 */
			buffer = ABSADDR(hashtable->batch) + (batch - 1) * BLCKSZ;
			batchno = batch - 1;
			pos = ExecHashJoinSaveTuple(outerTupleSlot->val,
										buffer,
										outerbatches[batchno],
										ABSADDR(outerbatchPos[batchno]));

			outerbatchPos[batchno] = RELADDR(pos);
		}
		else if (bucket != NULL)
		{
			do
			{

				/*
				 * scan the hash bucket for matches
				 */
				curtuple = ExecScanHashBucket(hjstate,
											  bucket,
											  curtuple,
											  hjclauses,
											  econtext);

				if (curtuple != NULL)
				{

					/*
					 * we've got a match, but still need to test qpqual
					 */
					inntuple = ExecStoreTuple(curtuple,
											  hjstate->hj_HashTupleSlot,
											  InvalidBuffer,
											  false);	/* don't pfree this
														 * tuple */

					econtext->ecxt_innertuple = inntuple;

					/* ----------------
					 * test to see if we pass the qualification
					 * ----------------
					 */
					qualResult = ExecQual((List *) qual, econtext);

					/* ----------------
					 * if we pass the qual, then save state for next call and
					 * have ExecProject form the projection, store it
					 * in the tuple table, and return the slot.
					 * ----------------
					 */
					if (qualResult)
					{
						ProjectionInfo *projInfo;
						TupleTableSlot *result;
325
						bool		isDone;
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

						hjstate->hj_CurBucket = bucket;
						hjstate->hj_CurTuple = curtuple;
						hashtable->curbatch = curbatch;
						hjstate->jstate.cs_OuterTupleSlot = outerTupleSlot;

						projInfo = hjstate->jstate.cs_ProjInfo;
						result = ExecProject(projInfo, &isDone);
						hjstate->jstate.cs_TupFromTlist = !isDone;
						return result;
					}
				}
			}
			while (curtuple != NULL);
		}

		/* ----------------
		 *	 Now the current outer tuple has run out of matches,
		 *	 so we free it and get a new outer tuple.
		 * ----------------
		 */
		outerTupleSlot = (TupleTableSlot *)
			ExecHashJoinOuterGetTuple(outerNode, (Plan *) node, hjstate);

		while (curbatch <= nbatch && TupIsNull(outerTupleSlot))
		{

			/*
			 * if the current batch runs out, switch to new batch
			 */
			curbatch = ExecHashJoinNewBatch(hjstate);
			if (curbatch > nbatch)
			{

				/*
				 * when the last batch runs out, clean up
				 */
				ExecHashTableDestroy(hashtable);
				hjstate->hj_HashTable = NULL;
				return NULL;
			}
			else
				outerTupleSlot = (TupleTableSlot *)
					ExecHashJoinOuterGetTuple(outerNode, (Plan *) node, hjstate);
		}

		/* ----------------
		 *	 Now get the corresponding hash bucket for the new
		 *	 outer tuple.
		 * ----------------
		 */
		econtext->ecxt_outertuple = outerTupleSlot;
378
#ifdef HJDEBUG
379
		printf("Probing ");
380
#endif
381 382 383 384 385
		bucketno = ExecHashGetBucket(hashtable, econtext, outerVar);
		bucket = (HashBucket) (ABSADDR(hashtable->top)
							   + bucketno * hashtable->bucketsize);
		curtuple = NULL;
	}
386 387 388
}

/* ----------------------------------------------------------------
389
 *		ExecInitHashJoin
390
 *
391
 *		Init routine for HashJoin node.
392 393
 * ----------------------------------------------------------------
 */
394 395
bool							/* return: initialization status */
ExecInitHashJoin(HashJoin * node, EState * estate, Plan * parent)
396
{
397 398 399
	HashJoinState *hjstate;
	Plan	   *outerNode;
	Hash	   *hashNode;
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

	/* ----------------
	 *	assign the node's execution state
	 * ----------------
	 */
	node->join.state = estate;

	/* ----------------
	 * create state structure
	 * ----------------
	 */
	hjstate = makeNode(HashJoinState);

	node->hashjoinstate = hjstate;

	/* ----------------
	 *	Miscellanious initialization
	 *
	 *		 +	assign node's base_id
	 *		 +	assign debugging hooks and
	 *		 +	create expression context for node
	 * ----------------
	 */
	ExecAssignNodeBaseInfo(estate, &hjstate->jstate, parent);
	ExecAssignExprContext(estate, &hjstate->jstate);

426
#define HASHJOIN_NSLOTS 2
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
	/* ----------------
	 *	tuple table initialization
	 * ----------------
	 */
	ExecInitResultTupleSlot(estate, &hjstate->jstate);
	ExecInitOuterTupleSlot(estate, hjstate);

	/* ----------------
	 * initializes child nodes
	 * ----------------
	 */
	outerNode = outerPlan((Plan *) node);
	hashNode = (Hash *) innerPlan((Plan *) node);

	ExecInitNode(outerNode, estate, (Plan *) node);
	ExecInitNode((Plan *) hashNode, estate, (Plan *) node);

	/* ----------------
	 *	now for some voodoo.  our temporary tuple slot
	 *	is actually the result tuple slot of the Hash node
	 *	(which is our inner plan).	we do this because Hash
	 *	nodes don't return tuples via ExecProcNode() -- instead
	 *	the hash join node uses ExecScanHashBucket() to get
	 *	at the contents of the hash table.	-cim 6/9/91
	 * ----------------
	 */
	{
454
		HashState  *hashstate = hashNode->hashstate;
455 456 457 458 459 460 461 462
		TupleTableSlot *slot =
		hashstate->cstate.cs_ResultTupleSlot;

		hjstate->hj_HashTupleSlot = slot;
	}
	hjstate->hj_OuterTupleSlot->ttc_tupleDescriptor =
		ExecGetTupType(outerNode);

463
/*
464 465
	hjstate->hj_OuterTupleSlot->ttc_execTupDescriptor =
							  ExecGetExecTupDesc(outerNode);
466
*/
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

	/* ----------------
	 *	initialize tuple type and projection info
	 * ----------------
	 */
	ExecAssignResultTypeFromTL((Plan *) node, &hjstate->jstate);
	ExecAssignProjectionInfo((Plan *) node, &hjstate->jstate);

	/* ----------------
	 *	XXX comment me
	 * ----------------
	 */

	node->hashdone = false;

	hjstate->hj_HashTable = (HashJoinTable) NULL;
	hjstate->hj_HashTableShmId = (IpcMemoryId) 0;
	hjstate->hj_CurBucket = (HashBucket) NULL;
	hjstate->hj_CurTuple = (HeapTuple) NULL;
	hjstate->hj_CurOTuple = (OverflowTuple) NULL;
	hjstate->hj_InnerHashKey = (Var *) NULL;
	hjstate->hj_OuterBatches = (File *) NULL;
	hjstate->hj_InnerBatches = (File *) NULL;
	hjstate->hj_OuterReadPos = (char *) NULL;
	hjstate->hj_OuterReadBlk = (int) 0;

	hjstate->jstate.cs_OuterTupleSlot = (TupleTableSlot *) NULL;
	hjstate->jstate.cs_TupFromTlist = (bool) false;

	return TRUE;
497 498 499
}

int
500
ExecCountSlotsHashJoin(HashJoin * node)
501
{
502
	return ExecCountSlotsNode(outerPlan(node)) +
503
	ExecCountSlotsNode(innerPlan(node)) +
504
	HASHJOIN_NSLOTS;
505 506 507
}

/* ----------------------------------------------------------------
508
 *		ExecEndHashJoin
509
 *
510
 *		clean up routine for HashJoin node
511 512 513
 * ----------------------------------------------------------------
 */
void
514
ExecEndHashJoin(HashJoin * node)
515
{
516
	HashJoinState *hjstate;
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

	/* ----------------
	 *	get info from the HashJoin state
	 * ----------------
	 */
	hjstate = node->hashjoinstate;

	/* ----------------
	 * free hash table in case we end plan before all tuples are retrieved
	 * ---------------
	 */
	if (hjstate->hj_HashTable)
	{
		ExecHashTableDestroy(hjstate->hj_HashTable);
		hjstate->hj_HashTable = NULL;
	}

	/* ----------------
	 *	Free the projection info and the scan attribute info
	 *
	 *	Note: we don't ExecFreeResultType(hjstate)
	 *		  because the rule manager depends on the tupType
	 *		  returned by ExecMain().  So for now, this
	 *		  is freed at end-transaction time.  -cim 6/2/91
	 * ----------------
	 */
	ExecFreeProjectionInfo(&hjstate->jstate);

	/* ----------------
	 * clean up subtrees
	 * ----------------
	 */
	ExecEndNode(outerPlan((Plan *) node), (Plan *) node);
	ExecEndNode(innerPlan((Plan *) node), (Plan *) node);

	/* ----------------
	 *	clean out the tuple table
	 * ----------------
	 */
	ExecClearTuple(hjstate->jstate.cs_ResultTupleSlot);
	ExecClearTuple(hjstate->hj_OuterTupleSlot);
	ExecClearTuple(hjstate->hj_HashTupleSlot);

560 561 562
}

/* ----------------------------------------------------------------
563
 *		ExecHashJoinOuterGetTuple
564
 *
565 566 567
 *		get the next outer tuple for hashjoin: either by
 *		executing a plan node as in the first pass, or from
 *		the tmp files for the hashjoin batches.
568 569 570 571
 * ----------------------------------------------------------------
 */

static TupleTableSlot *
572
ExecHashJoinOuterGetTuple(Plan * node, Plan * parent, HashJoinState * hjstate)
573
{
574
	TupleTableSlot *slot;
575 576 577 578 579 580 581
	HashJoinTable hashtable;
	int			curbatch;
	File	   *outerbatches;
	char	   *outerreadPos;
	int			batchno;
	char	   *outerreadBuf;
	int			outerreadBlk;
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

	hashtable = hjstate->hj_HashTable;
	curbatch = hashtable->curbatch;

	if (curbatch == 0)
	{							/* if it is the first pass */
		slot = ExecProcNode(node, parent);
		return slot;
	}

	/*
	 * otherwise, read from the tmp files
	 */
	outerbatches = hjstate->hj_OuterBatches;
	outerreadPos = hjstate->hj_OuterReadPos;
	outerreadBlk = hjstate->hj_OuterReadBlk;
	outerreadBuf = ABSADDR(hashtable->readbuf);
	batchno = curbatch - 1;

	slot = ExecHashJoinGetSavedTuple(hjstate,
									 outerreadBuf,
									 outerbatches[batchno],
									 hjstate->hj_OuterTupleSlot,
									 &outerreadBlk,
									 &outerreadPos);

	hjstate->hj_OuterReadPos = outerreadPos;
	hjstate->hj_OuterReadBlk = outerreadBlk;

611 612 613 614
	return slot;
}

/* ----------------------------------------------------------------
615
 *		ExecHashJoinGetSavedTuple
616
 *
617
 *		read the next tuple from a tmp file using a certain buffer
618 619 620 621
 * ----------------------------------------------------------------
 */

static TupleTableSlot *
622 623 624 625 626 627
ExecHashJoinGetSavedTuple(HashJoinState * hjstate,
						  char *buffer,
						  File file,
						  TupleTableSlot * tupleSlot,
						  int *block,	/* return parameter */
						  char **position)		/* return parameter */
628
{
629 630 631 632 633
	char	   *bufstart;
	char	   *bufend;
	int			cc;
	HeapTuple	heapTuple;
	HashJoinTable hashtable;
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

	hashtable = hjstate->hj_HashTable;
	bufend = buffer + *(long *) buffer;
	bufstart = (char *) (buffer + sizeof(long));
	if ((*position == NULL) || (*position >= bufend))
	{
		if (*position == NULL)
			(*block) = 0;
		else
			(*block)++;
		FileSeek(file, *block * BLCKSZ, SEEK_SET);
		cc = FileRead(file, buffer, BLCKSZ);
		NDirectFileRead++;
		if (cc < 0)
			perror("FileRead");
		if (cc == 0)			/* end of file */
			return NULL;
		else
			(*position) = bufstart;
	}
	heapTuple = (HeapTuple) (*position);
	(*position) = (char *) LONGALIGN(*position + heapTuple->t_len);

	return ExecStoreTuple(heapTuple, tupleSlot, InvalidBuffer, false);
658 659 660
}

/* ----------------------------------------------------------------
661
 *		ExecHashJoinNewBatch
662
 *
663
 *		switch to a new hashjoin batch
664 665
 * ----------------------------------------------------------------
 */
666
static int
667
ExecHashJoinNewBatch(HashJoinState * hjstate)
668
{
669 670 671 672 673 674 675 676 677
	File	   *innerBatches;
	File	   *outerBatches;
	int		   *innerBatchSizes;
	Var		   *innerhashkey;
	HashJoinTable hashtable;
	int			nbatch;
	char	   *readPos;
	int			readBlk;
	char	   *readBuf;
678
	TupleTableSlot *slot;
679 680 681 682
	ExprContext *econtext;
	int			i;
	int			cc;
	int			newbatch;
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

	hashtable = hjstate->hj_HashTable;
	outerBatches = hjstate->hj_OuterBatches;
	innerBatches = hjstate->hj_InnerBatches;
	nbatch = hashtable->nbatch;
	newbatch = hashtable->curbatch + 1;

	/* ------------------
	 *	this is the last process, so it will do the cleanup and
	 *	batch-switching.
	 * ------------------
	 */
	if (newbatch == 1)
	{

		/*
		 * if it is end of the first pass, flush all the last pages for
		 * the batches.
		 */
		outerBatches = hjstate->hj_OuterBatches;
		for (i = 0; i < nbatch; i++)
		{
			cc = FileSeek(outerBatches[i], 0L, SEEK_END);
			if (cc < 0)
				perror("FileSeek");
			cc = FileWrite(outerBatches[i],
						 ABSADDR(hashtable->batch) + i * BLCKSZ, BLCKSZ);
			NDirectFileWrite++;
			if (cc < 0)
				perror("FileWrite");
		}
714
	}
715 716 717 718 719 720 721 722 723
	if (newbatch > 1)
	{

		/*
		 * remove the previous outer batch
		 */
		FileUnlink(outerBatches[newbatch - 2]);
	}

724
	/*
725 726 727 728 729 730
	 * rebuild the hash table for the new inner batch
	 */
	innerBatchSizes = (int *) ABSADDR(hashtable->innerbatchSizes);
	/* --------------
	 *	skip over empty inner batches
	 * --------------
731
	 */
732 733 734 735 736
	while (newbatch <= nbatch && innerBatchSizes[newbatch - 1] == 0)
	{
		FileUnlink(outerBatches[newbatch - 1]);
		FileUnlink(innerBatches[newbatch - 1]);
		newbatch++;
737
	}
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	if (newbatch > nbatch)
	{
		hashtable->pcount = hashtable->nprocess;

		return newbatch;
	}
	ExecHashTableReset(hashtable, innerBatchSizes[newbatch - 1]);


	econtext = hjstate->jstate.cs_ExprContext;
	innerhashkey = hjstate->hj_InnerHashKey;
	readPos = NULL;
	readBlk = 0;
	readBuf = ABSADDR(hashtable->readbuf);

	while ((slot = ExecHashJoinGetSavedTuple(hjstate,
											 readBuf,
											 innerBatches[newbatch - 1],
											 hjstate->hj_HashTupleSlot,
											 &readBlk,
											 &readPos))
		   && !TupIsNull(slot))
	{
		econtext->ecxt_innertuple = slot;
		ExecHashTableInsert(hashtable, econtext, innerhashkey, NULL);
		/* possible bug - glass */
	}


	/* -----------------
	 *	only the last process comes to this branch
	 *	now all the processes have finished the build phase
	 * ----------------
	 */

	/*
	 * after we build the hash table, the inner batch is no longer needed
	 */
	FileUnlink(innerBatches[newbatch - 1]);
	hjstate->hj_OuterReadPos = NULL;
778 779
	hashtable->pcount = hashtable->nprocess;

780
	hashtable->curbatch = newbatch;
781 782 783 784
	return newbatch;
}

/* ----------------------------------------------------------------
785
 *		ExecHashJoinGetBatch
786
 *
787 788 789 790
 *		determine the batch number for a bucketno
 *		+----------------+-------+-------+ ... +-------+
 *		0			  nbuckets						 totalbuckets
 * batch		 0			 1		 2	   ...
791 792
 * ----------------------------------------------------------------
 */
793
static int
794 795
ExecHashJoinGetBatch(int bucketno, HashJoinTable hashtable, int nbatch)
{
796
	int			b;
797 798 799 800 801 802 803 804

	if (bucketno < hashtable->nbuckets || nbatch == 0)
		return 0;

	b = (float) (bucketno - hashtable->nbuckets) /
		(float) (hashtable->totalbuckets - hashtable->nbuckets) *
		nbatch;
	return b + 1;
805 806 807
}

/* ----------------------------------------------------------------
808
 *		ExecHashJoinSaveTuple
809
 *
810 811 812
 *		save a tuple to a tmp file using a buffer.
 *		the first few bytes in a page is an offset to the end
 *		of the page.
813 814 815
 * ----------------------------------------------------------------
 */

816
char	   *
817
ExecHashJoinSaveTuple(HeapTuple heapTuple,
818 819 820
					  char *buffer,
					  File file,
					  char *position)
821
{
822 823 824 825
	long	   *pageend;
	char	   *pagestart;
	char	   *pagebound;
	int			cc;
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849

	pageend = (long *) buffer;
	pagestart = (char *) (buffer + sizeof(long));
	pagebound = buffer + BLCKSZ;
	if (position == NULL)
		position = pagestart;

	if (position + heapTuple->t_len >= pagebound)
	{
		cc = FileSeek(file, 0L, SEEK_END);
		if (cc < 0)
			perror("FileSeek");
		cc = FileWrite(file, buffer, BLCKSZ);
		NDirectFileWrite++;
		if (cc < 0)
			perror("FileWrite");
		position = pagestart;
		*pageend = 0;
	}
	memmove(position, heapTuple, heapTuple->t_len);
	position = (char *) LONGALIGN(position + heapTuple->t_len);
	*pageend = position - buffer;

	return position;
850
}