nodeLimit.c 7.66 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * nodeLimit.c
 *	  Routines to handle limiting of query results where appropriate
 *
6
 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/executor/nodeLimit.c,v 1.6 2001/03/23 04:49:53 momjian Exp $
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
 *
 *-------------------------------------------------------------------------
 */
/*
 * INTERFACE ROUTINES
 *		ExecLimit		- extract a limited range of tuples
 *		ExecInitLimit	- initialize node and subnodes..
 *		ExecEndLimit	- shutdown node and subnodes
 */

#include "postgres.h"

#include "executor/executor.h"
#include "executor/nodeLimit.h"

static void recompute_limits(Limit *node);


/* ----------------------------------------------------------------
 *		ExecLimit
 *
 *		This is a very simple node which just performs LIMIT/OFFSET
 *		filtering on the stream of tuples returned by a subplan.
 * ----------------------------------------------------------------
 */
TupleTableSlot *				/* return: a tuple or NULL */
ExecLimit(Limit *node)
{
	LimitState *limitstate;
	ScanDirection direction;
	TupleTableSlot *resultTupleSlot;
	TupleTableSlot *slot;
	Plan	   *outerPlan;
	long		netlimit;

47 48
	/*
	 * get information from the node
49 50 51 52 53 54
	 */
	limitstate = node->limitstate;
	direction = node->plan.state->es_direction;
	outerPlan = outerPlan((Plan *) node);
	resultTupleSlot = limitstate->cstate.cs_ResultTupleSlot;

55 56 57 58
	/*
	 * If first call for this scan, compute limit/offset. (We can't do
	 * this any earlier, because parameters from upper nodes may not be
	 * set until now.)
59
	 */
60
	if (!limitstate->parmsSet)
61 62 63
		recompute_limits(node);
	netlimit = limitstate->offset + limitstate->count;

64 65
	/*
	 * now loop, returning only desired tuples.
66 67 68
	 */
	for (;;)
	{
69 70 71

		/*
		 * If we have reached the subplan EOF or the limit, just quit.
72 73
		 *
		 * NOTE: when scanning forwards, we must fetch one tuple beyond the
74 75 76
		 * COUNT limit before we can return NULL, else the subplan won't
		 * be properly positioned to start going backwards.  Hence test
		 * here is for position > netlimit not position >= netlimit.
77 78
		 *
		 * Similarly, when scanning backwards, we must re-fetch the last
79 80 81
		 * tuple in the offset region before we can return NULL.
		 * Otherwise we won't be correctly aligned to start going forward
		 * again.  So, although you might think we can quit when position
82 83
		 * equals offset + 1, we have to fetch a subplan tuple first, and
		 * then exit when position = offset.
84 85 86 87 88
		 */
		if (ScanDirectionIsForward(direction))
		{
			if (limitstate->atEnd)
				return NULL;
89
			if (!limitstate->noCount && limitstate->position > netlimit)
90 91 92 93 94 95 96
				return NULL;
		}
		else
		{
			if (limitstate->position <= limitstate->offset)
				return NULL;
		}
97 98 99

		/*
		 * fetch a tuple from the outer subplan
100 101 102 103
		 */
		slot = ExecProcNode(outerPlan, (Plan *) node);
		if (TupIsNull(slot))
		{
104

105 106 107 108 109 110
			/*
			 * We are at start or end of the subplan.  Update local state
			 * appropriately, but always return NULL.
			 */
			if (ScanDirectionIsForward(direction))
			{
111
				Assert(!limitstate->atEnd);
112 113 114 115 116 117 118 119 120 121 122
				/* must bump position to stay in sync for backwards fetch */
				limitstate->position++;
				limitstate->atEnd = true;
			}
			else
			{
				limitstate->position = 0;
				limitstate->atEnd = false;
			}
			return NULL;
		}
123

124 125 126 127 128 129 130 131 132 133 134 135
		/*
		 * We got the next subplan tuple successfully, so adjust state.
		 */
		if (ScanDirectionIsForward(direction))
			limitstate->position++;
		else
		{
			limitstate->position--;
			Assert(limitstate->position > 0);
		}
		limitstate->atEnd = false;

136 137 138
		/*
		 * Now, is this a tuple we want?  If not, loop around to fetch
		 * another tuple from the subplan.
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
		 */
		if (limitstate->position > limitstate->offset &&
			(limitstate->noCount || limitstate->position <= netlimit))
			break;
	}

	ExecStoreTuple(slot->val,
				   resultTupleSlot,
				   InvalidBuffer,
				   false);		/* tuple does not belong to slot */

	return resultTupleSlot;
}

/*
 * Evaluate the limit/offset expressions --- done at start of each scan.
 *
 * This is also a handy place to reset the current-position state info.
 */
static void
recompute_limits(Limit *node)
{
	LimitState *limitstate = node->limitstate;
	ExprContext *econtext = limitstate->cstate.cs_ExprContext;
	bool		isNull;

	if (node->limitOffset)
	{
		limitstate->offset = DatumGetInt32(ExecEvalExpr(node->limitOffset,
														econtext,
														&isNull,
														NULL));
		/* Interpret NULL offset as no offset */
		if (isNull)
			limitstate->offset = 0;
		else if (limitstate->offset < 0)
			limitstate->offset = 0;
	}
	else
	{
		/* No OFFSET supplied */
		limitstate->offset = 0;
	}

	if (node->limitCount)
	{
		limitstate->count = DatumGetInt32(ExecEvalExpr(node->limitCount,
186 187 188
													   econtext,
													   &isNull,
													   NULL));
189
		/* Interpret NULL count as no count (LIMIT ALL) */
190 191
		if (isNull)
			limitstate->noCount = true;
192 193
		else if (limitstate->count < 0)
			limitstate->count = 0;
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
	}
	else
	{
		/* No COUNT supplied */
		limitstate->count = 0;
		limitstate->noCount = true;
	}

	/* Reset position data to start-of-scan */
	limitstate->position = 0;
	limitstate->atEnd = false;

	/* Set flag that params are computed */
	limitstate->parmsSet = true;
}

/* ----------------------------------------------------------------
 *		ExecInitLimit
 *
 *		This initializes the limit node state structures and
 *		the node's subplan.
 * ----------------------------------------------------------------
 */
bool							/* return: initialization status */
ExecInitLimit(Limit *node, EState *estate, Plan *parent)
{
	LimitState *limitstate;
	Plan	   *outerPlan;

223 224
	/*
	 * assign execution state to node
225 226 227
	 */
	node->plan.state = estate;

228 229
	/*
	 * create new LimitState for node
230 231 232 233 234
	 */
	limitstate = makeNode(LimitState);
	node->limitstate = limitstate;
	limitstate->parmsSet = false;

235 236
	/*
	 * Miscellaneous initialization
237
	 *
238 239
	 * Limit nodes never call ExecQual or ExecProject, but they need an
	 * exprcontext anyway to evaluate the limit/offset parameters in.
240 241 242 243
	 */
	ExecAssignExprContext(estate, &limitstate->cstate);

#define LIMIT_NSLOTS 1
244 245

	/*
246 247 248 249
	 * Tuple table initialization
	 */
	ExecInitResultTupleSlot(estate, &limitstate->cstate);

250 251
	/*
	 * then initialize outer plan
252 253 254 255
	 */
	outerPlan = outerPlan((Plan *) node);
	ExecInitNode(outerPlan, estate, (Plan *) node);

256 257 258
	/*
	 * limit nodes do no projections, so initialize projection info for
	 * this node appropriately
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
	 */
	ExecAssignResultTypeFromOuterPlan((Plan *) node, &limitstate->cstate);
	limitstate->cstate.cs_ProjInfo = NULL;

	return TRUE;
}

int
ExecCountSlotsLimit(Limit *node)
{
	return ExecCountSlotsNode(outerPlan(node)) +
	ExecCountSlotsNode(innerPlan(node)) +
	LIMIT_NSLOTS;
}

/* ----------------------------------------------------------------
 *		ExecEndLimit
 *
 *		This shuts down the subplan and frees resources allocated
 *		to this node.
 * ----------------------------------------------------------------
 */
void
ExecEndLimit(Limit *node)
{
	LimitState *limitstate = node->limitstate;

	ExecFreeExprContext(&limitstate->cstate);

	ExecEndNode(outerPlan((Plan *) node), (Plan *) node);

	/* clean up tuple table */
	ExecClearTuple(limitstate->cstate.cs_ResultTupleSlot);
}


void
ExecReScanLimit(Limit *node, ExprContext *exprCtxt, Plan *parent)
{
	LimitState *limitstate = node->limitstate;

	ExecClearTuple(limitstate->cstate.cs_ResultTupleSlot);

	/* force recalculation of limit expressions on first call */
	limitstate->parmsSet = false;

	/*
	 * if chgParam of subnode is not null then plan will be re-scanned by
	 * first ExecProcNode.
	 */
	if (((Plan *) node)->lefttree->chgParam == NULL)
		ExecReScan(((Plan *) node)->lefttree, exprCtxt, (Plan *) node);
}