]> granicus.if.org Git - postgresql/blob - src/backend/tcop/fastpath.c
From: Phil Thompson <phil@river-bank.demon.co.uk>
[postgresql] / src / backend / tcop / fastpath.c
1 /*-------------------------------------------------------------------------
2  *
3  * fastpath.c--
4  *        routines to handle function requests from the frontend
5  *
6  * Copyright (c) 1994, Regents of the University of California
7  *
8  *
9  * IDENTIFICATION
10  *        $Header: /cvsroot/pgsql/src/backend/tcop/fastpath.c,v 1.12 1998/01/26 01:41:28 scrappy Exp $
11  *
12  * NOTES
13  *        This cruft is the server side of PQfn.
14  *
15  *        - jolly 07/11/95:
16  *
17  *        no longer rely on return sizes provided by the frontend.      Always
18  *        use the true lengths for the catalogs.  Assume that the frontend
19  *        has allocated enough space to handle the result value returned.
20  *
21  *        trust that the user knows what he is doing with the args.  If the
22  *        sys catalog says it is a varlena, assume that the user is only sending
23  *        down VARDATA and that the argsize is the VARSIZE.  If the arg is
24  *        fixed len, assume that the argsize given by the user is correct.
25  *
26  *        if the function returns by value, then only send 4 bytes value
27  *        back to the frontend.  If the return returns by reference,
28  *        send down only the data portion and set the return size appropriately.
29  *
30  *       OLD COMMENTS FOLLOW
31  *
32  *        The VAR_LENGTH_{ARGS,RESULT} stuff is limited to MAX_STRING_LENGTH
33  *        (see src/backend/tmp/fastpath.h) for no obvious reason.  Since its
34  *        primary use (for us) is for Inversion path names, it should probably
35  *        be increased to 256 (MAXPATHLEN for Inversion, hidden in pg_type
36  *        as well as utils/adt/filename.c).
37  *
38  *        Quoth PMA on 08/15/93:
39  *
40  *        This code has been almost completely rewritten with an eye to
41  *        keeping it as compatible as possible with the previous (broken)
42  *        implementation.
43  *
44  *        The previous implementation would assume (1) that any value of
45  *        length <= 4 bytes was passed-by-value, and that any other value
46  *        was a struct varlena (by-reference).  There was NO way to pass a
47  *        fixed-length by-reference argument (like char16) or a struct
48  *        varlena of size <= 4 bytes.
49  *
50  *        The new implementation checks the catalogs to determine whether
51  *        a value is by-value (type "0" is null-delimited character string,
52  *        as it is for, e.g., the parser).      The only other item obtained
53  *        from the catalogs is whether or not the value should be placed in
54  *        a struct varlena or not.      Otherwise, the size given by the
55  *        frontend is assumed to be correct (probably a bad decision, but
56  *        we do strange things in the name of compatibility).
57  *
58  *-------------------------------------------------------------------------
59  */
60 #include <string.h>
61
62 #include "postgres.h"
63
64 #include "tcop/tcopdebug.h"
65
66 #include "utils/palloc.h"
67 #include "fmgr.h"
68 #include "utils/builtins.h"             /* for oideq */
69 #include "tcop/fastpath.h"
70 #include "libpq/libpq.h"
71
72 #include "access/xact.h"                /* for TransactionId/CommandId protos */
73
74 #include "utils/syscache.h"
75 #include "catalog/pg_proc.h"
76 #include "catalog/pg_type.h"
77
78
79 /* ----------------
80  *              SendFunctionResult
81  * ----------------
82  */
83 static void
84 SendFunctionResult(Oid fid,             /* function id */
85                                    char *retval,/* actual return value */
86                                    bool retbyval,
87                                    int retlen   /* the length according to the catalogs */
88 )
89 {
90         pq_putnchar("V", 1);
91
92         if (retlen != 0)
93         {
94                 pq_putnchar("G", 1);
95                 if (retbyval)
96                 {                                               /* by-value */
97                         pq_putint(retlen, 4);
98                         pq_putint((int) (Datum) retval, retlen);
99                 }
100                 else
101                 {                                               /* by-reference ... */
102                         if (retlen < 0)
103                         {                                       /* ... varlena */
104                                 pq_putint(VARSIZE(retval) - VARHDRSZ, VARHDRSZ);
105                                 pq_putnchar(VARDATA(retval), VARSIZE(retval) - VARHDRSZ);
106                         }
107                         else
108                         {                                       /* ... fixed */
109                                 pq_putint(retlen, 4);
110                                 pq_putnchar(retval, retlen);
111                         }
112                 }
113         }
114
115         pq_putnchar("0", 1);
116         pq_flush();
117 }
118
119 /*
120  * This structure saves enough state so that one can avoid having to
121  * do catalog lookups over and over again.      (Each RPC can require up
122  * to MAXFMGRARGS+2 lookups, which is quite tedious.)
123  *
124  * The previous incarnation of this code just assumed that any argument
125  * of size <= 4 was by value; this is not correct.      There is no cheap
126  * way to determine function argument length etc.; one must simply pay
127  * the price of catalog lookups.
128  */
129 struct fp_info
130 {
131         Oid                     funcid;
132         int                     nargs;
133         bool            argbyval[MAXFMGRARGS];
134         int32           arglen[MAXFMGRARGS];    /* signed (for varlena) */
135         bool            retbyval;
136         int32           retlen;                 /* signed (for varlena) */
137         TransactionId xid;
138         CommandId       cid;
139 };
140
141 /*
142  * We implement one-back caching here.  If we need to do more, we can.
143  * Most routines in tight loops (like PQfswrite -> F_LOWRITE) will do
144  * the same thing repeatedly.
145  */
146 static struct fp_info last_fp = {InvalidOid};
147
148 /*
149  * valid_fp_info
150  *
151  * RETURNS:
152  *              1 if the state in 'fip' is valid
153  *              0 otherwise
154  *
155  * "valid" means:
156  * The saved state was either uninitialized, for another function,
157  * or from a previous command.  (Commands can do updates, which
158  * may invalidate catalog entries for subsequent commands.      This
159  * is overly pessimistic but since there is no smarter invalidation
160  * scheme...).
161  */
162 static int
163 valid_fp_info(Oid func_id, struct fp_info * fip)
164 {
165         Assert(OidIsValid(func_id));
166         Assert(fip != (struct fp_info *) NULL);
167
168         return (OidIsValid(fip->funcid) &&
169                         oideq(func_id, fip->funcid) &&
170                         TransactionIdIsCurrentTransactionId(fip->xid) &&
171                         CommandIdIsCurrentCommandId(fip->cid));
172 }
173
174 /*
175  * update_fp_info
176  *
177  * Performs catalog lookups to load a struct fp_info 'fip' for the
178  * function 'func_id'.
179  *
180  * RETURNS:
181  *              The correct information in 'fip'.  Sets 'fip->funcid' to
182  *              InvalidOid if an exception occurs.
183  */
184 static void
185 update_fp_info(Oid func_id, struct fp_info * fip)
186 {
187         Oid                *argtypes;           /* an oid8 */
188         Oid                     rettype;
189         HeapTuple       func_htp,
190                                 type_htp;
191         TypeTupleForm tp;
192         Form_pg_proc pp;
193         int                     i;
194
195         Assert(OidIsValid(func_id));
196         Assert(fip != (struct fp_info *) NULL);
197
198         /*
199          * Since the validity of this structure is determined by whether the
200          * funcid is OK, we clear the funcid here.      It must not be set to the
201          * correct value until we are about to return with a good struct
202          * fp_info, since we can be interrupted (i.e., with an elog(ERROR,
203          * ...)) at any time.
204          */
205         MemSet((char *) fip, 0, (int) sizeof(struct fp_info));
206         fip->funcid = InvalidOid;
207
208         func_htp = SearchSysCacheTuple(PROOID, ObjectIdGetDatum(func_id),
209                                                                    0, 0, 0);
210         if (!HeapTupleIsValid(func_htp))
211         {
212                 elog(ERROR, "update_fp_info: cache lookup for function %d failed",
213                          func_id);
214         }
215         pp = (Form_pg_proc) GETSTRUCT(func_htp);
216         fip->nargs = pp->pronargs;
217         rettype = pp->prorettype;
218         argtypes = pp->proargtypes;
219
220         for (i = 0; i < fip->nargs; ++i)
221         {
222                 if (OidIsValid(argtypes[i]))
223                 {
224                         type_htp = SearchSysCacheTuple(TYPOID,
225                                                                                    ObjectIdGetDatum(argtypes[i]),
226                                                                                    0, 0, 0);
227                         if (!HeapTupleIsValid(type_htp))
228                         {
229                                 elog(ERROR, "update_fp_info: bad argument type %d for %d",
230                                          argtypes[i], func_id);
231                         }
232                         tp = (TypeTupleForm) GETSTRUCT(type_htp);
233                         fip->argbyval[i] = tp->typbyval;
234                         fip->arglen[i] = tp->typlen;
235                 }                                               /* else it had better be VAR_LENGTH_ARG */
236         }
237
238         if (OidIsValid(rettype))
239         {
240                 type_htp = SearchSysCacheTuple(TYPOID, ObjectIdGetDatum(rettype),
241                                                                            0, 0, 0);
242                 if (!HeapTupleIsValid(type_htp))
243                 {
244                         elog(ERROR, "update_fp_info: bad return type %d for %d",
245                                  rettype, func_id);
246                 }
247                 tp = (TypeTupleForm) GETSTRUCT(type_htp);
248                 fip->retbyval = tp->typbyval;
249                 fip->retlen = tp->typlen;
250         }                                                       /* else it had better by VAR_LENGTH_RESULT */
251
252         fip->xid = GetCurrentTransactionId();
253         fip->cid = GetCurrentCommandId();
254
255         /*
256          * This must be last!
257          */
258         fip->funcid = func_id;
259 }
260
261
262 /*
263  * HandleFunctionRequest
264  *
265  * Server side of PQfn (fastpath function calls from the frontend).
266  * This corresponds to the libpq protocol symbol "F".
267  *
268  * RETURNS:
269  *              nothing of significance.
270  *              All errors result in elog(ERROR,...).
271  */
272 int
273 HandleFunctionRequest()
274 {
275         Oid                     fid;
276         int                     argsize;
277         int                     nargs;
278         char       *arg[8];
279         char       *retval;
280         int                     i;
281         uint32          palloced;
282         char       *p;
283         struct fp_info *fip;
284
285         fid = (Oid) pq_getint(4);       /* function oid */
286         nargs = pq_getint(4);           /* # of arguments */
287
288         /*
289          * This is where the one-back caching is done. If you want to save
290          * more state, make this a loop around an array.
291          */
292         fip = &last_fp;
293         if (!valid_fp_info(fid, fip))
294         {
295                 update_fp_info(fid, fip);
296         }
297
298         if (fip->nargs != nargs)
299         {
300                 elog(ERROR, "HandleFunctionRequest: actual arguments (%d) != registered arguments (%d)",
301                          nargs, fip->nargs);
302         }
303
304         /*
305          * Copy arguments into arg vector.      If we palloc() an argument, we
306          * need to remember, so that we pfree() it after the call.
307          */
308         palloced = 0x0;
309         for (i = 0; i < 8; ++i)
310         {
311                 if (i >= nargs)
312                 {
313                         arg[i] = (char *) NULL;
314                 }
315                 else
316                 {
317                         argsize = pq_getint(4);
318
319                         Assert(argsize > 0);
320                         if (fip->argbyval[i])
321                         {                                       /* by-value */
322                                 Assert(argsize <= 4);
323                                 arg[i] = (char *) pq_getint(argsize);
324                         }
325                         else
326                         {                                       /* by-reference ... */
327                                 if (fip->arglen[i] < 0)
328                                 {                               /* ... varlena */
329                                         if (!(p = palloc(argsize + VARHDRSZ + 1))) /* Added +1 to solve memory leak - Peter 98 Jan 6 */
330                                         {
331                                                 elog(ERROR, "HandleFunctionRequest: palloc failed");
332                                         }
333                                         VARSIZE(p) = argsize + VARHDRSZ;
334                                         pq_getnchar(VARDATA(p), 0, argsize);
335                                 }
336                                 else
337                                 {                               /* ... fixed */
338                                         /* XXX cross our fingers and trust "argsize" */
339                                         if (!(p = palloc(argsize + 1)))
340                                         {
341                                                 elog(ERROR, "HandleFunctionRequest: palloc failed");
342                                         }
343                                         pq_getnchar(p, 0, argsize);
344                                 }
345                                 palloced |= (1 << i);
346                                 arg[i] = p;
347                         }
348                 }
349         }
350
351 #ifndef NO_FASTPATH
352         retval = fmgr(fid,
353                                   arg[0], arg[1], arg[2], arg[3],
354                                   arg[4], arg[5], arg[6], arg[7]);
355
356 #else
357         retval = NULL;
358 #endif                                                  /* NO_FASTPATH */
359
360         /* free palloc'ed arguments */
361         for (i = 0; i < nargs; ++i)
362         {
363                 if (palloced & (1 << i))
364                         pfree(arg[i]);
365         }
366
367         /*
368          * If this is an ordinary query (not a retrieve portal p ...), then we
369          * return the data to the user.  If the return value was palloc'ed,
370          * then it must also be freed.
371          */
372 #ifndef NO_FASTPATH
373         SendFunctionResult(fid, retval, fip->retbyval, fip->retlen);
374 #else
375         SendFunctionResult(fid, retval, fip->retbyval, 0);
376 #endif                                                  /* NO_FASTPATH */
377
378         if (!fip->retbyval)
379                 pfree(retval);
380
381
382
383         return (0);
384 }