fastpath.c 9.9 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * fastpath.c--
4
 *	  routines to handle function requests from the frontend
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/tcop/fastpath.c,v 1.21 1998/09/01 04:32:11 momjian Exp $
11 12
 *
 * NOTES
13
 *	  This cruft is the server side of PQfn.
14
 *
15
 *	  - jolly 07/11/95:
16
 *
17 18 19
 *	  no longer rely on return sizes provided by the frontend.	Always
 *	  use the true lengths for the catalogs.  Assume that the frontend
 *	  has allocated enough space to handle the result value returned.
20
 *
21 22 23 24
 *	  trust that the user knows what he is doing with the args.  If the
 *	  sys catalog says it is a varlena, assume that the user is only sending
 *	  down VARDATA and that the argsize is the VARSIZE.  If the arg is
 *	  fixed len, assume that the argsize given by the user is correct.
25
 *
26 27 28
 *	  if the function returns by value, then only send 4 bytes value
 *	  back to the frontend.  If the return returns by reference,
 *	  send down only the data portion and set the return size appropriately.
29
 *
30
 *	 OLD COMMENTS FOLLOW
31
 *
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
 *	  The VAR_LENGTH_{ARGS,RESULT} stuff is limited to MAX_STRING_LENGTH
 *	  (see src/backend/tmp/fastpath.h) for no obvious reason.  Since its
 *	  primary use (for us) is for Inversion path names, it should probably
 *	  be increased to 256 (MAXPATHLEN for Inversion, hidden in pg_type
 *	  as well as utils/adt/filename.c).
 *
 *	  Quoth PMA on 08/15/93:
 *
 *	  This code has been almost completely rewritten with an eye to
 *	  keeping it as compatible as possible with the previous (broken)
 *	  implementation.
 *
 *	  The previous implementation would assume (1) that any value of
 *	  length <= 4 bytes was passed-by-value, and that any other value
 *	  was a struct varlena (by-reference).	There was NO way to pass a
47
 *	  fixed-length by-reference argument (like name) or a struct
48 49 50 51 52 53 54 55 56
 *	  varlena of size <= 4 bytes.
 *
 *	  The new implementation checks the catalogs to determine whether
 *	  a value is by-value (type "0" is null-delimited character string,
 *	  as it is for, e.g., the parser).	The only other item obtained
 *	  from the catalogs is whether or not the value should be placed in
 *	  a struct varlena or not.	Otherwise, the size given by the
 *	  frontend is assumed to be correct (probably a bad decision, but
 *	  we do strange things in the name of compatibility).
57 58 59
 *
 *-------------------------------------------------------------------------
 */
B
Bruce Momjian 已提交
60 61
#include <string.h>

62 63 64 65 66 67
#include "postgres.h"

#include "tcop/tcopdebug.h"

#include "utils/palloc.h"
#include "fmgr.h"
68
#include "utils/builtins.h"		/* for oideq */
69 70 71
#include "tcop/fastpath.h"
#include "libpq/libpq.h"

72
#include "access/xact.h"		/* for TransactionId/CommandId protos */
73 74 75 76 77 78 79

#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"


/* ----------------
80
 *		SendFunctionResult
81 82 83
 * ----------------
 */
static void
84 85 86 87 88
SendFunctionResult(Oid fid,		/* function id */
				   char *retval,/* actual return value */
				   bool retbyval,
				   int retlen	/* the length according to the catalogs */
)
89
{
90 91 92 93 94 95 96 97 98 99 100 101 102 103
	pq_putnchar("V", 1);

	if (retlen != 0)
	{
		pq_putnchar("G", 1);
		if (retbyval)
		{						/* by-value */
			pq_putint(retlen, 4);
			pq_putint((int) (Datum) retval, retlen);
		}
		else
		{						/* by-reference ... */
			if (retlen < 0)
			{					/* ... varlena */
104
				pq_putint(VARSIZE(retval) - VARHDRSZ, VARHDRSZ);
105 106 107 108 109 110 111 112
				pq_putnchar(VARDATA(retval), VARSIZE(retval) - VARHDRSZ);
			}
			else
			{					/* ... fixed */
				pq_putint(retlen, 4);
				pq_putnchar(retval, retlen);
			}
		}
113 114
	}

115
	pq_putnchar("0", 1);
116 117 118 119
}

/*
 * This structure saves enough state so that one can avoid having to
120
 * do catalog lookups over and over again.	(Each RPC can require up
121 122 123
 * to MAXFMGRARGS+2 lookups, which is quite tedious.)
 *
 * The previous incarnation of this code just assumed that any argument
124
 * of size <= 4 was by value; this is not correct.	There is no cheap
125 126 127
 * way to determine function argument length etc.; one must simply pay
 * the price of catalog lookups.
 */
128 129
struct fp_info
{
130 131 132 133 134 135 136 137
	Oid			funcid;
	int			nargs;
	bool		argbyval[MAXFMGRARGS];
	int32		arglen[MAXFMGRARGS];	/* signed (for varlena) */
	bool		retbyval;
	int32		retlen;			/* signed (for varlena) */
	TransactionId xid;
	CommandId	cid;
138 139 140
};

/*
141
 * We implement one-back caching here.	If we need to do more, we can.
142 143 144
 * Most routines in tight loops (like PQfswrite -> F_LOWRITE) will do
 * the same thing repeatedly.
 */
145
static struct fp_info last_fp = {InvalidOid};
146 147 148 149 150

/*
 * valid_fp_info
 *
 * RETURNS:
151 152
 *		1 if the state in 'fip' is valid
 *		0 otherwise
153 154 155
 *
 * "valid" means:
 * The saved state was either uninitialized, for another function,
156 157
 * or from a previous command.	(Commands can do updates, which
 * may invalidate catalog entries for subsequent commands.	This
158 159 160 161
 * is overly pessimistic but since there is no smarter invalidation
 * scheme...).
 */
static int
162
valid_fp_info(Oid func_id, struct fp_info * fip)
163
{
164 165 166 167 168 169 170
	Assert(OidIsValid(func_id));
	Assert(fip != (struct fp_info *) NULL);

	return (OidIsValid(fip->funcid) &&
			oideq(func_id, fip->funcid) &&
			TransactionIdIsCurrentTransactionId(fip->xid) &&
			CommandIdIsCurrentCommandId(fip->cid));
171 172 173 174 175 176 177 178 179
}

/*
 * update_fp_info
 *
 * Performs catalog lookups to load a struct fp_info 'fip' for the
 * function 'func_id'.
 *
 * RETURNS:
180 181
 *		The correct information in 'fip'.  Sets 'fip->funcid' to
 *		InvalidOid if an exception occurs.
182 183
 */
static void
184
update_fp_info(Oid func_id, struct fp_info * fip)
185
{
186 187 188 189
	Oid		   *argtypes;		/* an oid8 */
	Oid			rettype;
	HeapTuple	func_htp,
				type_htp;
190
	Form_pg_type tp;
191 192
	Form_pg_proc pp;
	int			i;
193 194 195 196 197 198 199 200

	Assert(OidIsValid(func_id));
	Assert(fip != (struct fp_info *) NULL);

	/*
	 * Since the validity of this structure is determined by whether the
	 * funcid is OK, we clear the funcid here.	It must not be set to the
	 * correct value until we are about to return with a good struct
201
	 * fp_info, since we can be interrupted (i.e., with an elog(ERROR,
202 203
	 * ...)) at any time.
	 */
B
Bruce Momjian 已提交
204
	MemSet((char *) fip, 0, (int) sizeof(struct fp_info));
205 206
	fip->funcid = InvalidOid;

207 208
	func_htp = SearchSysCacheTuple(PROOID,
								   ObjectIdGetDatum(func_id),
209 210 211
								   0, 0, 0);
	if (!HeapTupleIsValid(func_htp))
	{
212
		elog(ERROR, "update_fp_info: cache lookup for function %d failed",
213
			 func_id);
214
	}
215 216 217 218 219 220 221 222 223 224 225 226 227 228
	pp = (Form_pg_proc) GETSTRUCT(func_htp);
	fip->nargs = pp->pronargs;
	rettype = pp->prorettype;
	argtypes = pp->proargtypes;

	for (i = 0; i < fip->nargs; ++i)
	{
		if (OidIsValid(argtypes[i]))
		{
			type_htp = SearchSysCacheTuple(TYPOID,
										   ObjectIdGetDatum(argtypes[i]),
										   0, 0, 0);
			if (!HeapTupleIsValid(type_htp))
			{
229
				elog(ERROR, "update_fp_info: bad argument type %d for %d",
230 231
					 argtypes[i], func_id);
			}
232
			tp = (Form_pg_type) GETSTRUCT(type_htp);
233 234 235 236 237 238 239
			fip->argbyval[i] = tp->typbyval;
			fip->arglen[i] = tp->typlen;
		}						/* else it had better be VAR_LENGTH_ARG */
	}

	if (OidIsValid(rettype))
	{
240 241
		type_htp = SearchSysCacheTuple(TYPOID,
									   ObjectIdGetDatum(rettype),
242 243 244
									   0, 0, 0);
		if (!HeapTupleIsValid(type_htp))
		{
245
			elog(ERROR, "update_fp_info: bad return type %d for %d",
246 247
				 rettype, func_id);
		}
248
		tp = (Form_pg_type) GETSTRUCT(type_htp);
249 250 251 252 253 254 255 256 257 258 259
		fip->retbyval = tp->typbyval;
		fip->retlen = tp->typlen;
	}							/* else it had better by VAR_LENGTH_RESULT */

	fip->xid = GetCurrentTransactionId();
	fip->cid = GetCurrentCommandId();

	/*
	 * This must be last!
	 */
	fip->funcid = func_id;
260
}
261

262 263 264 265 266 267 268 269

/*
 * HandleFunctionRequest
 *
 * Server side of PQfn (fastpath function calls from the frontend).
 * This corresponds to the libpq protocol symbol "F".
 *
 * RETURNS:
270
 *		nothing of significance.
271
 *		All errors result in elog(ERROR,...).
272 273 274 275
 */
int
HandleFunctionRequest()
{
276 277 278 279 280 281 282 283
	Oid			fid;
	int			argsize;
	int			nargs;
	char	   *arg[8];
	char	   *retval;
	int			i;
	uint32		palloced;
	char	   *p;
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	struct fp_info *fip;

	fid = (Oid) pq_getint(4);	/* function oid */
	nargs = pq_getint(4);		/* # of arguments */

	/*
	 * This is where the one-back caching is done. If you want to save
	 * more state, make this a loop around an array.
	 */
	fip = &last_fp;
	if (!valid_fp_info(fid, fip))
		update_fp_info(fid, fip);

	if (fip->nargs != nargs)
	{
299
		elog(ERROR, "HandleFunctionRequest: actual arguments (%d) != registered arguments (%d)",
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
			 nargs, fip->nargs);
	}

	/*
	 * Copy arguments into arg vector.	If we palloc() an argument, we
	 * need to remember, so that we pfree() it after the call.
	 */
	palloced = 0x0;
	for (i = 0; i < 8; ++i)
	{
		if (i >= nargs)
			arg[i] = (char *) NULL;
		else
		{
			argsize = pq_getint(4);

			Assert(argsize > 0);
			if (fip->argbyval[i])
			{					/* by-value */
				Assert(argsize <= 4);
				arg[i] = (char *) pq_getint(argsize);
321
			}
322 323 324 325
			else
			{					/* by-reference ... */
				if (fip->arglen[i] < 0)
				{				/* ... varlena */
326 327 328
					if (!(p = palloc(argsize + VARHDRSZ + 1)))	/* Added +1 to solve
																 * memory leak - Peter
																 * 98 Jan 6 */
329
						elog(ERROR, "HandleFunctionRequest: palloc failed");
330 331 332 333 334 335
					VARSIZE(p) = argsize + VARHDRSZ;
					pq_getnchar(VARDATA(p), 0, argsize);
				}
				else
				{				/* ... fixed */
					/* XXX cross our fingers and trust "argsize" */
336
					if (!(p = palloc(argsize + 1)))
337
						elog(ERROR, "HandleFunctionRequest: palloc failed");
338 339 340 341 342 343
					pq_getnchar(p, 0, argsize);
				}
				palloced |= (1 << i);
				arg[i] = p;
			}
		}
344 345 346
	}

#ifndef NO_FASTPATH
347 348 349
	retval = fmgr(fid,
				  arg[0], arg[1], arg[2], arg[3],
				  arg[4], arg[5], arg[6], arg[7]);
350 351

#else
352
	retval = NULL;
353
#endif	 /* NO_FASTPATH */
354 355 356 357 358 359 360 361 362 363 364 365 366

	/* free palloc'ed arguments */
	for (i = 0; i < nargs; ++i)
	{
		if (palloced & (1 << i))
			pfree(arg[i]);
	}

	/*
	 * If this is an ordinary query (not a retrieve portal p ...), then we
	 * return the data to the user.  If the return value was palloc'ed,
	 * then it must also be freed.
	 */
367
#ifndef NO_FASTPATH
368
	SendFunctionResult(fid, retval, fip->retbyval, fip->retlen);
369
#else
370
	SendFunctionResult(fid, retval, fip->retbyval, 0);
371
#endif	 /* NO_FASTPATH */
372 373 374 375

	if (!fip->retbyval)
		pfree(retval);

376 377


378
	return 0;
379
}