]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_comp.c
Move some declarations in the raw-parser header files to create a clearer
[postgresql] / src / pl / plpgsql / src / pl_comp.c
1 /*-------------------------------------------------------------------------
2  *
3  * pl_comp.c            - Compiler part of the PL/pgSQL
4  *                        procedural language
5  *
6  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_comp.c,v 1.137 2009/07/12 17:12:34 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "plpgsql.h"
17
18 #include <ctype.h>
19
20 #include "pl_gram.h"
21
22 #include "catalog/namespace.h"
23 #include "catalog/pg_attrdef.h"
24 #include "catalog/pg_attribute.h"
25 #include "catalog/pg_class.h"
26 #include "catalog/pg_proc.h"
27 #include "catalog/pg_proc_fn.h"
28 #include "catalog/pg_type.h"
29 #include "funcapi.h"
30 #include "nodes/makefuncs.h"
31 #include "parser/parse_type.h"
32 #include "tcop/tcopprot.h"
33 #include "utils/array.h"
34 #include "utils/builtins.h"
35 #include "utils/lsyscache.h"
36 #include "utils/memutils.h"
37 #include "utils/syscache.h"
38
39
40 /* ----------
41  * Our own local and global variables
42  * ----------
43  */
44 static int      datums_alloc;
45 int                     plpgsql_nDatums;
46 PLpgSQL_datum **plpgsql_Datums;
47 static int      datums_last = 0;
48
49 int                     plpgsql_error_lineno;
50 char       *plpgsql_error_funcname;
51 bool            plpgsql_DumpExecTree = false;
52 bool            plpgsql_check_syntax = false;
53
54 PLpgSQL_function *plpgsql_curr_compile;
55
56 /* A context appropriate for short-term allocs during compilation */
57 MemoryContext compile_tmp_cxt;
58
59 /* ----------
60  * Hash table for compiled functions
61  * ----------
62  */
63 static HTAB *plpgsql_HashTable = NULL;
64
65 typedef struct plpgsql_hashent
66 {
67         PLpgSQL_func_hashkey key;
68         PLpgSQL_function *function;
69 } plpgsql_HashEnt;
70
71 #define FUNCS_PER_USER          128 /* initial table size */
72
73 /* ----------
74  * Lookup table for EXCEPTION condition names
75  * ----------
76  */
77 typedef struct
78 {
79         const char *label;
80         int                     sqlerrstate;
81 } ExceptionLabelMap;
82
83 static const ExceptionLabelMap exception_label_map[] = {
84 #include "plerrcodes.h"
85         {NULL, 0}
86 };
87
88
89 /* ----------
90  * static prototypes
91  * ----------
92  */
93 static PLpgSQL_function *do_compile(FunctionCallInfo fcinfo,
94                    HeapTuple procTup,
95                    PLpgSQL_function *function,
96                    PLpgSQL_func_hashkey *hashkey,
97                    bool forValidator);
98 static PLpgSQL_row *build_row_from_class(Oid classOid);
99 static PLpgSQL_row *build_row_from_vars(PLpgSQL_variable **vars, int numvars);
100 static PLpgSQL_type *build_datatype(HeapTuple typeTup, int32 typmod);
101 static void compute_function_hashkey(FunctionCallInfo fcinfo,
102                                                  Form_pg_proc procStruct,
103                                                  PLpgSQL_func_hashkey *hashkey,
104                                                  bool forValidator);
105 static void plpgsql_resolve_polymorphic_argtypes(int numargs,
106                                                                          Oid *argtypes, char *argmodes,
107                                                                          Node *call_expr, bool forValidator,
108                                                                          const char *proname);
109 static PLpgSQL_function *plpgsql_HashTableLookup(PLpgSQL_func_hashkey *func_key);
110 static void plpgsql_HashTableInsert(PLpgSQL_function *function,
111                                                 PLpgSQL_func_hashkey *func_key);
112 static void plpgsql_HashTableDelete(PLpgSQL_function *function);
113 static void delete_function(PLpgSQL_function *func);
114
115 /* ----------
116  * plpgsql_compile              Make an execution tree for a PL/pgSQL function.
117  *
118  * If forValidator is true, we're only compiling for validation purposes,
119  * and so some checks are skipped.
120  *
121  * Note: it's important for this to fall through quickly if the function
122  * has already been compiled.
123  * ----------
124  */
125 PLpgSQL_function *
126 plpgsql_compile(FunctionCallInfo fcinfo, bool forValidator)
127 {
128         Oid                     funcOid = fcinfo->flinfo->fn_oid;
129         HeapTuple       procTup;
130         Form_pg_proc procStruct;
131         PLpgSQL_function *function;
132         PLpgSQL_func_hashkey hashkey;
133         bool            function_valid = false;
134         bool            hashkey_valid = false;
135
136         /*
137          * Lookup the pg_proc tuple by Oid; we'll need it in any case
138          */
139         procTup = SearchSysCache(PROCOID,
140                                                          ObjectIdGetDatum(funcOid),
141                                                          0, 0, 0);
142         if (!HeapTupleIsValid(procTup))
143                 elog(ERROR, "cache lookup failed for function %u", funcOid);
144         procStruct = (Form_pg_proc) GETSTRUCT(procTup);
145
146         /*
147          * See if there's already a cache entry for the current FmgrInfo. If not,
148          * try to find one in the hash table.
149          */
150         function = (PLpgSQL_function *) fcinfo->flinfo->fn_extra;
151
152 recheck:
153         if (!function)
154         {
155                 /* Compute hashkey using function signature and actual arg types */
156                 compute_function_hashkey(fcinfo, procStruct, &hashkey, forValidator);
157                 hashkey_valid = true;
158
159                 /* And do the lookup */
160                 function = plpgsql_HashTableLookup(&hashkey);
161         }
162
163         if (function)
164         {
165                 /* We have a compiled function, but is it still valid? */
166                 if (function->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
167                         ItemPointerEquals(&function->fn_tid, &procTup->t_self))
168                         function_valid = true;
169                 else
170                 {
171                         /*
172                          * Nope, so remove it from hashtable and try to drop associated
173                          * storage (if not done already).
174                          */
175                         delete_function(function);
176
177                         /*
178                          * If the function isn't in active use then we can overwrite the
179                          * func struct with new data, allowing any other existing fn_extra
180                          * pointers to make use of the new definition on their next use.
181                          * If it is in use then just leave it alone and make a new one.
182                          * (The active invocations will run to completion using the
183                          * previous definition, and then the cache entry will just be
184                          * leaked; doesn't seem worth adding code to clean it up, given
185                          * what a corner case this is.)
186                          *
187                          * If we found the function struct via fn_extra then it's possible
188                          * a replacement has already been made, so go back and recheck the
189                          * hashtable.
190                          */
191                         if (function->use_count != 0)
192                         {
193                                 function = NULL;
194                                 if (!hashkey_valid)
195                                         goto recheck;
196                         }
197                 }
198         }
199
200         /*
201          * If the function wasn't found or was out-of-date, we have to compile it
202          */
203         if (!function_valid)
204         {
205                 /*
206                  * Calculate hashkey if we didn't already; we'll need it to store the
207                  * completed function.
208                  */
209                 if (!hashkey_valid)
210                         compute_function_hashkey(fcinfo, procStruct, &hashkey,
211                                                                          forValidator);
212
213                 /*
214                  * Do the hard part.
215                  */
216                 function = do_compile(fcinfo, procTup, function,
217                                                           &hashkey, forValidator);
218         }
219
220         ReleaseSysCache(procTup);
221
222         /*
223          * Save pointer in FmgrInfo to avoid search on subsequent calls
224          */
225         fcinfo->flinfo->fn_extra = (void *) function;
226
227         /*
228          * Finally return the compiled function
229          */
230         return function;
231 }
232
233 /*
234  * This is the slow part of plpgsql_compile().
235  *
236  * The passed-in "function" pointer is either NULL or an already-allocated
237  * function struct to overwrite.
238  *
239  * While compiling a function, the CurrentMemoryContext is the
240  * per-function memory context of the function we are compiling. That
241  * means a palloc() will allocate storage with the same lifetime as
242  * the function itself.
243  *
244  * Because palloc()'d storage will not be immediately freed, temporary
245  * allocations should either be performed in a short-lived memory
246  * context or explicitly pfree'd. Since not all backend functions are
247  * careful about pfree'ing their allocations, it is also wise to
248  * switch into a short-term context before calling into the
249  * backend. An appropriate context for performing short-term
250  * allocations is the compile_tmp_cxt.
251  *
252  * NB: this code is not re-entrant.  We assume that nothing we do here could
253  * result in the invocation of another plpgsql function.
254  */
255 static PLpgSQL_function *
256 do_compile(FunctionCallInfo fcinfo,
257                    HeapTuple procTup,
258                    PLpgSQL_function *function,
259                    PLpgSQL_func_hashkey *hashkey,
260                    bool forValidator)
261 {
262         Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
263         bool            is_trigger = CALLED_AS_TRIGGER(fcinfo);
264         Datum           prosrcdatum;
265         bool            isnull;
266         char       *proc_source;
267         HeapTuple       typeTup;
268         Form_pg_type typeStruct;
269         PLpgSQL_variable *var;
270         PLpgSQL_rec *rec;
271         int                     i;
272         ErrorContextCallback plerrcontext;
273         int                     parse_rc;
274         Oid                     rettypeid;
275         int                     numargs;
276         int                     num_in_args = 0;
277         int                     num_out_args = 0;
278         Oid                *argtypes;
279         char      **argnames;
280         char       *argmodes;
281         int                *in_arg_varnos = NULL;
282         PLpgSQL_variable **out_arg_variables;
283         MemoryContext func_cxt;
284
285         /*
286          * Setup the scanner input and error info.      We assume that this function
287          * cannot be invoked recursively, so there's no need to save and restore
288          * the static variables used here.
289          */
290         prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
291                                                                   Anum_pg_proc_prosrc, &isnull);
292         if (isnull)
293                 elog(ERROR, "null prosrc");
294         proc_source = TextDatumGetCString(prosrcdatum);
295         plpgsql_scanner_init(proc_source);
296
297         plpgsql_error_funcname = pstrdup(NameStr(procStruct->proname));
298         plpgsql_error_lineno = 0;
299
300         /*
301          * Setup error traceback support for ereport()
302          */
303         plerrcontext.callback = plpgsql_compile_error_callback;
304         plerrcontext.arg = forValidator ? proc_source : NULL;
305         plerrcontext.previous = error_context_stack;
306         error_context_stack = &plerrcontext;
307
308         /*
309          * Initialize the compiler, particularly the namespace stack.  The
310          * outermost namespace contains function parameters and other special
311          * variables (such as FOUND), and is named after the function itself.
312          */
313         plpgsql_ns_init();
314         plpgsql_ns_push(NameStr(procStruct->proname));
315         plpgsql_DumpExecTree = false;
316
317         datums_alloc = 128;
318         plpgsql_nDatums = 0;
319         /* This is short-lived, so needn't allocate in function's cxt */
320         plpgsql_Datums = palloc(sizeof(PLpgSQL_datum *) * datums_alloc);
321         datums_last = 0;
322
323         /*
324          * Do extra syntax checks when validating the function definition. We skip
325          * this when actually compiling functions for execution, for performance
326          * reasons.
327          */
328         plpgsql_check_syntax = forValidator;
329
330         /*
331          * Create the new function struct, if not done already.  The function
332          * structs are never thrown away, so keep them in TopMemoryContext.
333          */
334         if (function == NULL)
335         {
336                 function = (PLpgSQL_function *)
337                         MemoryContextAllocZero(TopMemoryContext, sizeof(PLpgSQL_function));
338         }
339         else
340         {
341                 /* re-using a previously existing struct, so clear it out */
342                 memset(function, 0, sizeof(PLpgSQL_function));
343         }
344         plpgsql_curr_compile = function;
345
346         /*
347          * All the rest of the compile-time storage (e.g. parse tree) is kept in
348          * its own memory context, so it can be reclaimed easily.
349          */
350         func_cxt = AllocSetContextCreate(TopMemoryContext,
351                                                                          "PL/PgSQL function context",
352                                                                          ALLOCSET_DEFAULT_MINSIZE,
353                                                                          ALLOCSET_DEFAULT_INITSIZE,
354                                                                          ALLOCSET_DEFAULT_MAXSIZE);
355         compile_tmp_cxt = MemoryContextSwitchTo(func_cxt);
356
357         function->fn_name = pstrdup(NameStr(procStruct->proname));
358         function->fn_oid = fcinfo->flinfo->fn_oid;
359         function->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
360         function->fn_tid = procTup->t_self;
361         function->fn_is_trigger = is_trigger;
362         function->fn_cxt = func_cxt;
363         function->out_param_varno = -1;         /* set up for no OUT param */
364
365         switch (is_trigger)
366         {
367                 case false:
368
369                         /*
370                          * Fetch info about the procedure's parameters. Allocations aren't
371                          * needed permanently, so make them in tmp cxt.
372                          *
373                          * We also need to resolve any polymorphic input or output
374                          * argument types.      In validation mode we won't be able to, so we
375                          * arbitrarily assume we are dealing with integers.
376                          */
377                         MemoryContextSwitchTo(compile_tmp_cxt);
378
379                         numargs = get_func_arg_info(procTup,
380                                                                                 &argtypes, &argnames, &argmodes);
381
382                         plpgsql_resolve_polymorphic_argtypes(numargs, argtypes, argmodes,
383                                                                                                  fcinfo->flinfo->fn_expr,
384                                                                                                  forValidator,
385                                                                                                  plpgsql_error_funcname);
386
387                         in_arg_varnos = (int *) palloc(numargs * sizeof(int));
388                         out_arg_variables = (PLpgSQL_variable **) palloc(numargs * sizeof(PLpgSQL_variable *));
389
390                         MemoryContextSwitchTo(func_cxt);
391
392                         /*
393                          * Create the variables for the procedure's parameters.
394                          */
395                         for (i = 0; i < numargs; i++)
396                         {
397                                 char            buf[32];
398                                 Oid                     argtypeid = argtypes[i];
399                                 char            argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
400                                 PLpgSQL_type *argdtype;
401                                 PLpgSQL_variable *argvariable;
402                                 int                     argitemtype;
403
404                                 /* Create $n name for variable */
405                                 snprintf(buf, sizeof(buf), "$%d", i + 1);
406
407                                 /* Create datatype info */
408                                 argdtype = plpgsql_build_datatype(argtypeid, -1);
409
410                                 /* Disallow pseudotype argument */
411                                 /* (note we already replaced polymorphic types) */
412                                 /* (build_variable would do this, but wrong message) */
413                                 if (argdtype->ttype != PLPGSQL_TTYPE_SCALAR &&
414                                         argdtype->ttype != PLPGSQL_TTYPE_ROW)
415                                         ereport(ERROR,
416                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
417                                                    errmsg("PL/pgSQL functions cannot accept type %s",
418                                                                   format_type_be(argtypeid))));
419
420                                 /* Build variable and add to datum list */
421                                 argvariable = plpgsql_build_variable(buf, 0,
422                                                                                                          argdtype, false);
423
424                                 if (argvariable->dtype == PLPGSQL_DTYPE_VAR)
425                                 {
426                                         argitemtype = PLPGSQL_NSTYPE_VAR;
427                                         /* input argument vars are forced to be CONSTANT */
428                                         if (argmode == PROARGMODE_IN ||
429                                                 argmode == PROARGMODE_VARIADIC)
430                                                 ((PLpgSQL_var *) argvariable)->isconst = true;
431                                 }
432                                 else
433                                 {
434                                         Assert(argvariable->dtype == PLPGSQL_DTYPE_ROW);
435                                         argitemtype = PLPGSQL_NSTYPE_ROW;
436                                 }
437
438                                 /* Remember arguments in appropriate arrays */
439                                 if (argmode == PROARGMODE_IN ||
440                                         argmode == PROARGMODE_INOUT ||
441                                         argmode == PROARGMODE_VARIADIC)
442                                         in_arg_varnos[num_in_args++] = argvariable->dno;
443                                 if (argmode == PROARGMODE_OUT ||
444                                         argmode == PROARGMODE_INOUT ||
445                                         argmode == PROARGMODE_TABLE)
446                                         out_arg_variables[num_out_args++] = argvariable;
447
448                                 /* Add to namespace under the $n name */
449                                 plpgsql_ns_additem(argitemtype, argvariable->dno, buf);
450
451                                 /* If there's a name for the argument, make an alias */
452                                 if (argnames && argnames[i][0] != '\0')
453                                         plpgsql_ns_additem(argitemtype, argvariable->dno,
454                                                                            argnames[i]);
455                         }
456
457                         /*
458                          * If there's just one OUT parameter, out_param_varno points
459                          * directly to it.      If there's more than one, build a row that
460                          * holds all of them.
461                          */
462                         if (num_out_args == 1)
463                                 function->out_param_varno = out_arg_variables[0]->dno;
464                         else if (num_out_args > 1)
465                         {
466                                 PLpgSQL_row *row = build_row_from_vars(out_arg_variables,
467                                                                                                            num_out_args);
468
469                                 plpgsql_adddatum((PLpgSQL_datum *) row);
470                                 function->out_param_varno = row->dno;
471                         }
472
473                         /*
474                          * Check for a polymorphic returntype. If found, use the actual
475                          * returntype type from the caller's FuncExpr node, if we have
476                          * one.  (In validation mode we arbitrarily assume we are dealing
477                          * with integers.)
478                          *
479                          * Note: errcode is FEATURE_NOT_SUPPORTED because it should always
480                          * work; if it doesn't we're in some context that fails to make
481                          * the info available.
482                          */
483                         rettypeid = procStruct->prorettype;
484                         if (IsPolymorphicType(rettypeid))
485                         {
486                                 if (forValidator)
487                                 {
488                                         if (rettypeid == ANYARRAYOID)
489                                                 rettypeid = INT4ARRAYOID;
490                                         else    /* ANYELEMENT or ANYNONARRAY */
491                                                 rettypeid = INT4OID;
492                                         /* XXX what could we use for ANYENUM? */
493                                 }
494                                 else
495                                 {
496                                         rettypeid = get_fn_expr_rettype(fcinfo->flinfo);
497                                         if (!OidIsValid(rettypeid))
498                                                 ereport(ERROR,
499                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
500                                                          errmsg("could not determine actual return type "
501                                                                         "for polymorphic function \"%s\"",
502                                                                         plpgsql_error_funcname)));
503                                 }
504                         }
505
506                         /*
507                          * Normal function has a defined returntype
508                          */
509                         function->fn_rettype = rettypeid;
510                         function->fn_retset = procStruct->proretset;
511
512                         /*
513                          * Lookup the function's return type
514                          */
515                         typeTup = SearchSysCache(TYPEOID,
516                                                                          ObjectIdGetDatum(rettypeid),
517                                                                          0, 0, 0);
518                         if (!HeapTupleIsValid(typeTup))
519                                 elog(ERROR, "cache lookup failed for type %u", rettypeid);
520                         typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
521
522                         /* Disallow pseudotype result, except VOID or RECORD */
523                         /* (note we already replaced polymorphic types) */
524                         if (typeStruct->typtype == TYPTYPE_PSEUDO)
525                         {
526                                 if (rettypeid == VOIDOID ||
527                                         rettypeid == RECORDOID)
528                                          /* okay */ ;
529                                 else if (rettypeid == TRIGGEROID)
530                                         ereport(ERROR,
531                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
532                                                          errmsg("trigger functions can only be called as triggers")));
533                                 else
534                                         ereport(ERROR,
535                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
536                                                    errmsg("PL/pgSQL functions cannot return type %s",
537                                                                   format_type_be(rettypeid))));
538                         }
539
540                         if (typeStruct->typrelid != InvalidOid ||
541                                 rettypeid == RECORDOID)
542                                 function->fn_retistuple = true;
543                         else
544                         {
545                                 function->fn_retbyval = typeStruct->typbyval;
546                                 function->fn_rettyplen = typeStruct->typlen;
547                                 function->fn_rettypioparam = getTypeIOParam(typeTup);
548                                 fmgr_info(typeStruct->typinput, &(function->fn_retinput));
549
550                                 /*
551                                  * install $0 reference, but only for polymorphic return
552                                  * types, and not when the return is specified through an
553                                  * output parameter.
554                                  */
555                                 if (IsPolymorphicType(procStruct->prorettype) &&
556                                         num_out_args == 0)
557                                 {
558                                         (void) plpgsql_build_variable("$0", 0,
559                                                                                                   build_datatype(typeTup, -1),
560                                                                                                   true);
561                                 }
562                         }
563                         ReleaseSysCache(typeTup);
564                         break;
565
566                 case true:
567                         /* Trigger procedure's return type is unknown yet */
568                         function->fn_rettype = InvalidOid;
569                         function->fn_retbyval = false;
570                         function->fn_retistuple = true;
571                         function->fn_retset = false;
572
573                         /* shouldn't be any declared arguments */
574                         if (procStruct->pronargs != 0)
575                                 ereport(ERROR,
576                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
577                                   errmsg("trigger functions cannot have declared arguments"),
578                                                  errhint("The arguments of the trigger can be accessed through TG_NARGS and TG_ARGV instead.")));
579
580                         /* Add the record for referencing NEW */
581                         rec = plpgsql_build_record("new", 0, true);
582                         function->new_varno = rec->dno;
583
584                         /* Add the record for referencing OLD */
585                         rec = plpgsql_build_record("old", 0, true);
586                         function->old_varno = rec->dno;
587
588                         /* Add the variable tg_name */
589                         var = plpgsql_build_variable("tg_name", 0,
590                                                                                  plpgsql_build_datatype(NAMEOID, -1),
591                                                                                  true);
592                         function->tg_name_varno = var->dno;
593
594                         /* Add the variable tg_when */
595                         var = plpgsql_build_variable("tg_when", 0,
596                                                                                  plpgsql_build_datatype(TEXTOID, -1),
597                                                                                  true);
598                         function->tg_when_varno = var->dno;
599
600                         /* Add the variable tg_level */
601                         var = plpgsql_build_variable("tg_level", 0,
602                                                                                  plpgsql_build_datatype(TEXTOID, -1),
603                                                                                  true);
604                         function->tg_level_varno = var->dno;
605
606                         /* Add the variable tg_op */
607                         var = plpgsql_build_variable("tg_op", 0,
608                                                                                  plpgsql_build_datatype(TEXTOID, -1),
609                                                                                  true);
610                         function->tg_op_varno = var->dno;
611
612                         /* Add the variable tg_relid */
613                         var = plpgsql_build_variable("tg_relid", 0,
614                                                                                  plpgsql_build_datatype(OIDOID, -1),
615                                                                                  true);
616                         function->tg_relid_varno = var->dno;
617
618                         /* Add the variable tg_relname */
619                         var = plpgsql_build_variable("tg_relname", 0,
620                                                                                  plpgsql_build_datatype(NAMEOID, -1),
621                                                                                  true);
622                         function->tg_relname_varno = var->dno;
623
624                         /* tg_table_name is now preferred to tg_relname */
625                         var = plpgsql_build_variable("tg_table_name", 0,
626                                                                                  plpgsql_build_datatype(NAMEOID, -1),
627                                                                                  true);
628                         function->tg_table_name_varno = var->dno;
629
630
631                         /* add variable tg_table_schema */
632                         var = plpgsql_build_variable("tg_table_schema", 0,
633                                                                                  plpgsql_build_datatype(NAMEOID, -1),
634                                                                                  true);
635                         function->tg_table_schema_varno = var->dno;
636
637
638                         /* Add the variable tg_nargs */
639                         var = plpgsql_build_variable("tg_nargs", 0,
640                                                                                  plpgsql_build_datatype(INT4OID, -1),
641                                                                                  true);
642                         function->tg_nargs_varno = var->dno;
643
644                         break;
645
646                 default:
647                         elog(ERROR, "unrecognized function typecode: %d", (int) is_trigger);
648                         break;
649         }
650
651         /* Remember if function is STABLE/IMMUTABLE */
652         function->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
653
654         /*
655          * Create the magic FOUND variable.
656          */
657         var = plpgsql_build_variable("found", 0,
658                                                                  plpgsql_build_datatype(BOOLOID, -1),
659                                                                  true);
660         function->found_varno = var->dno;
661
662         /*
663          * Now parse the function's text
664          */
665         parse_rc = plpgsql_yyparse();
666         if (parse_rc != 0)
667                 elog(ERROR, "plpgsql parser returned %d", parse_rc);
668         function->action = plpgsql_yylval.program;
669
670         plpgsql_scanner_finish();
671         pfree(proc_source);
672
673         /*
674          * If it has OUT parameters or returns VOID or returns a set, we allow
675          * control to fall off the end without an explicit RETURN statement. The
676          * easiest way to implement this is to add a RETURN statement to the end
677          * of the statement list during parsing.  However, if the outer block has
678          * an EXCEPTION clause, we need to make a new outer block, since the added
679          * RETURN shouldn't act like it is inside the EXCEPTION clause.
680          */
681         if (num_out_args > 0 || function->fn_rettype == VOIDOID ||
682                 function->fn_retset)
683         {
684                 if (function->action->exceptions != NULL)
685                 {
686                         PLpgSQL_stmt_block *new;
687
688                         new = palloc0(sizeof(PLpgSQL_stmt_block));
689                         new->cmd_type = PLPGSQL_STMT_BLOCK;
690                         new->body = list_make1(function->action);
691
692                         function->action = new;
693                 }
694                 if (function->action->body == NIL ||
695                         ((PLpgSQL_stmt *) llast(function->action->body))->cmd_type != PLPGSQL_STMT_RETURN)
696                 {
697                         PLpgSQL_stmt_return *new;
698
699                         new = palloc0(sizeof(PLpgSQL_stmt_return));
700                         new->cmd_type = PLPGSQL_STMT_RETURN;
701                         new->expr = NULL;
702                         new->retvarno = function->out_param_varno;
703
704                         function->action->body = lappend(function->action->body, new);
705                 }
706         }
707
708         /*
709          * Complete the function's info
710          */
711         function->fn_nargs = procStruct->pronargs;
712         for (i = 0; i < function->fn_nargs; i++)
713                 function->fn_argvarnos[i] = in_arg_varnos[i];
714         function->ndatums = plpgsql_nDatums;
715         function->datums = palloc(sizeof(PLpgSQL_datum *) * plpgsql_nDatums);
716         for (i = 0; i < plpgsql_nDatums; i++)
717                 function->datums[i] = plpgsql_Datums[i];
718
719         /* Debug dump for completed functions */
720         if (plpgsql_DumpExecTree)
721                 plpgsql_dumptree(function);
722
723         /*
724          * add it to the hash table
725          */
726         plpgsql_HashTableInsert(function, hashkey);
727
728         /*
729          * Pop the error context stack
730          */
731         error_context_stack = plerrcontext.previous;
732         plpgsql_error_funcname = NULL;
733         plpgsql_error_lineno = 0;
734
735         plpgsql_check_syntax = false;
736
737         MemoryContextSwitchTo(compile_tmp_cxt);
738         compile_tmp_cxt = NULL;
739         return function;
740 }
741
742
743 /*
744  * error context callback to let us supply a call-stack traceback. If
745  * we are validating, the function source is passed as an
746  * argument. This function is public only for the sake of an assertion
747  * in gram.y
748  */
749 void
750 plpgsql_compile_error_callback(void *arg)
751 {
752         if (arg)
753         {
754                 /*
755                  * Try to convert syntax error position to reference text of original
756                  * CREATE FUNCTION command.
757                  */
758                 if (function_parse_error_transpose((const char *) arg))
759                         return;
760
761                 /*
762                  * Done if a syntax error position was reported; otherwise we have to
763                  * fall back to a "near line N" report.
764                  */
765         }
766
767         if (plpgsql_error_funcname)
768                 errcontext("compilation of PL/pgSQL function \"%s\" near line %d",
769                                    plpgsql_error_funcname, plpgsql_error_lineno);
770 }
771
772
773 /* ----------
774  * plpgsql_parse_word           The scanner calls this to postparse
775  *                              any single word not found by a
776  *                              keyword rule.
777  * ----------
778  */
779 int
780 plpgsql_parse_word(const char *word)
781 {
782         PLpgSQL_nsitem *nse;
783         char       *cp[1];
784
785         /* Do case conversion and word separation */
786         plpgsql_convert_ident(word, cp, 1);
787
788         /*
789          * Recognize tg_argv when compiling triggers (XXX this sucks, it should be
790          * a regular variable in the namestack)
791          */
792         if (plpgsql_curr_compile->fn_is_trigger)
793         {
794                 if (strcmp(cp[0], "tg_argv") == 0)
795                 {
796                         bool            save_spacescanned = plpgsql_SpaceScanned;
797                         PLpgSQL_trigarg *trigarg;
798
799                         trigarg = palloc0(sizeof(PLpgSQL_trigarg));
800                         trigarg->dtype = PLPGSQL_DTYPE_TRIGARG;
801
802                         if (plpgsql_yylex() != '[')
803                                 plpgsql_yyerror("expected \"[\"");
804
805                         trigarg->argnum = plpgsql_read_expression(']', "]");
806
807                         plpgsql_adddatum((PLpgSQL_datum *) trigarg);
808                         plpgsql_yylval.scalar = (PLpgSQL_datum *) trigarg;
809
810                         plpgsql_SpaceScanned = save_spacescanned;
811                         pfree(cp[0]);
812                         return T_SCALAR;
813                 }
814         }
815
816         /*
817          * Do a lookup on the compiler's namestack
818          */
819         nse = plpgsql_ns_lookup(cp[0], NULL, NULL, NULL);
820         pfree(cp[0]);
821
822         if (nse != NULL)
823         {
824                 switch (nse->itemtype)
825                 {
826                         case PLPGSQL_NSTYPE_VAR:
827                                 plpgsql_yylval.scalar = plpgsql_Datums[nse->itemno];
828                                 return T_SCALAR;
829
830                         case PLPGSQL_NSTYPE_REC:
831                                 plpgsql_yylval.rec = (PLpgSQL_rec *) (plpgsql_Datums[nse->itemno]);
832                                 return T_RECORD;
833
834                         case PLPGSQL_NSTYPE_ROW:
835                                 plpgsql_yylval.row = (PLpgSQL_row *) (plpgsql_Datums[nse->itemno]);
836                                 return T_ROW;
837
838                         default:
839                                 return T_ERROR;
840                 }
841         }
842
843         /*
844          * Nothing found - up to now it's a word without any special meaning for
845          * us.
846          */
847         return T_WORD;
848 }
849
850
851 /* ----------
852  * plpgsql_parse_dblword                Same lookup for two words
853  *                                      separated by a dot.
854  * ----------
855  */
856 int
857 plpgsql_parse_dblword(const char *word)
858 {
859         PLpgSQL_nsitem *ns;
860         char       *cp[2];
861         int                     nnames;
862
863         /* Do case conversion and word separation */
864         plpgsql_convert_ident(word, cp, 2);
865
866         /*
867          * Do a lookup on the compiler's namestack
868          */
869         ns = plpgsql_ns_lookup(cp[0], cp[1], NULL, &nnames);
870         if (ns == NULL)
871         {
872                 pfree(cp[0]);
873                 pfree(cp[1]);
874                 return T_ERROR;
875         }
876
877         switch (ns->itemtype)
878         {
879                 case PLPGSQL_NSTYPE_VAR:
880                         /* Block-qualified reference to scalar variable. */
881                         plpgsql_yylval.scalar = plpgsql_Datums[ns->itemno];
882                         pfree(cp[0]);
883                         pfree(cp[1]);
884                         return T_SCALAR;
885
886                 case PLPGSQL_NSTYPE_REC:
887                         if (nnames == 1)
888                         {
889                                 /*
890                                  * First word is a record name, so second word must be a field
891                                  * in this record.
892                                  */
893                                 PLpgSQL_recfield *new;
894
895                                 new = palloc(sizeof(PLpgSQL_recfield));
896                                 new->dtype = PLPGSQL_DTYPE_RECFIELD;
897                                 new->fieldname = pstrdup(cp[1]);
898                                 new->recparentno = ns->itemno;
899
900                                 plpgsql_adddatum((PLpgSQL_datum *) new);
901
902                                 plpgsql_yylval.scalar = (PLpgSQL_datum *) new;
903
904                                 pfree(cp[0]);
905                                 pfree(cp[1]);
906                                 return T_SCALAR;
907                         }
908                         else
909                         {
910                                 /* Block-qualified reference to record variable. */
911                                 plpgsql_yylval.rec = (PLpgSQL_rec *) (plpgsql_Datums[ns->itemno]);
912                                 pfree(cp[0]);
913                                 pfree(cp[1]);
914                                 return T_RECORD;
915                         }
916
917                 case PLPGSQL_NSTYPE_ROW:
918                         if (nnames == 1)
919                         {
920                                 /*
921                                  * First word is a row name, so second word must be a field in
922                                  * this row.
923                                  */
924                                 PLpgSQL_row *row;
925                                 int                     i;
926
927                                 row = (PLpgSQL_row *) (plpgsql_Datums[ns->itemno]);
928                                 for (i = 0; i < row->nfields; i++)
929                                 {
930                                         if (row->fieldnames[i] &&
931                                                 strcmp(row->fieldnames[i], cp[1]) == 0)
932                                         {
933                                                 plpgsql_yylval.scalar = plpgsql_Datums[row->varnos[i]];
934                                                 pfree(cp[0]);
935                                                 pfree(cp[1]);
936                                                 return T_SCALAR;
937                                         }
938                                 }
939                                 ereport(ERROR,
940                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
941                                                  errmsg("row \"%s\" has no field \"%s\"",
942                                                                 cp[0], cp[1])));
943                         }
944                         else
945                         {
946                                 /* Block-qualified reference to row variable. */
947                                 plpgsql_yylval.row = (PLpgSQL_row *) (plpgsql_Datums[ns->itemno]);
948                                 pfree(cp[0]);
949                                 pfree(cp[1]);
950                                 return T_ROW;
951                         }
952
953                 default:
954                         break;
955         }
956
957         pfree(cp[0]);
958         pfree(cp[1]);
959         return T_ERROR;
960 }
961
962
963 /* ----------
964  * plpgsql_parse_tripword               Same lookup for three words
965  *                                      separated by dots.
966  * ----------
967  */
968 int
969 plpgsql_parse_tripword(const char *word)
970 {
971         PLpgSQL_nsitem *ns;
972         char       *cp[3];
973         int                     nnames;
974
975         /* Do case conversion and word separation */
976         plpgsql_convert_ident(word, cp, 3);
977
978         /*
979          * Do a lookup on the compiler's namestack. Must find a qualified
980          * reference.
981          */
982         ns = plpgsql_ns_lookup(cp[0], cp[1], cp[2], &nnames);
983         if (ns == NULL || nnames != 2)
984         {
985                 pfree(cp[0]);
986                 pfree(cp[1]);
987                 pfree(cp[2]);
988                 return T_ERROR;
989         }
990
991         switch (ns->itemtype)
992         {
993                 case PLPGSQL_NSTYPE_REC:
994                         {
995                                 /*
996                                  * words 1/2 are a record name, so third word must be a field
997                                  * in this record.
998                                  */
999                                 PLpgSQL_recfield *new;
1000
1001                                 new = palloc(sizeof(PLpgSQL_recfield));
1002                                 new->dtype = PLPGSQL_DTYPE_RECFIELD;
1003                                 new->fieldname = pstrdup(cp[2]);
1004                                 new->recparentno = ns->itemno;
1005
1006                                 plpgsql_adddatum((PLpgSQL_datum *) new);
1007
1008                                 plpgsql_yylval.scalar = (PLpgSQL_datum *) new;
1009
1010                                 pfree(cp[0]);
1011                                 pfree(cp[1]);
1012                                 pfree(cp[2]);
1013
1014                                 return T_SCALAR;
1015                         }
1016
1017                 case PLPGSQL_NSTYPE_ROW:
1018                         {
1019                                 /*
1020                                  * words 1/2 are a row name, so third word must be a field in
1021                                  * this row.
1022                                  */
1023                                 PLpgSQL_row *row;
1024                                 int                     i;
1025
1026                                 row = (PLpgSQL_row *) (plpgsql_Datums[ns->itemno]);
1027                                 for (i = 0; i < row->nfields; i++)
1028                                 {
1029                                         if (row->fieldnames[i] &&
1030                                                 strcmp(row->fieldnames[i], cp[2]) == 0)
1031                                         {
1032                                                 plpgsql_yylval.scalar = plpgsql_Datums[row->varnos[i]];
1033
1034                                                 pfree(cp[0]);
1035                                                 pfree(cp[1]);
1036                                                 pfree(cp[2]);
1037
1038                                                 return T_SCALAR;
1039                                         }
1040                                 }
1041                                 ereport(ERROR,
1042                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1043                                                  errmsg("row \"%s.%s\" has no field \"%s\"",
1044                                                                 cp[0], cp[1], cp[2])));
1045                         }
1046
1047                 default:
1048                         break;
1049         }
1050
1051         pfree(cp[0]);
1052         pfree(cp[1]);
1053         pfree(cp[2]);
1054         return T_ERROR;
1055 }
1056
1057
1058 /* ----------
1059  * plpgsql_parse_wordtype       The scanner found word%TYPE. word can be
1060  *                              a variable name or a basetype.
1061  * ----------
1062  */
1063 int
1064 plpgsql_parse_wordtype(char *word)
1065 {
1066         PLpgSQL_nsitem *nse;
1067         bool            old_nsstate;
1068         HeapTuple       typeTup;
1069         char       *cp[2];
1070         int                     i;
1071
1072         /* Do case conversion and word separation */
1073         /* We convert %type to .type momentarily to keep converter happy */
1074         i = strlen(word) - 5;
1075         Assert(word[i] == '%');
1076         word[i] = '.';
1077         plpgsql_convert_ident(word, cp, 2);
1078         word[i] = '%';
1079         pfree(cp[1]);
1080
1081         /*
1082          * Do a lookup on the compiler's namestack.  Ensure we scan all levels.
1083          */
1084         old_nsstate = plpgsql_ns_setlocal(false);
1085         nse = plpgsql_ns_lookup(cp[0], NULL, NULL, NULL);
1086         plpgsql_ns_setlocal(old_nsstate);
1087
1088         if (nse != NULL)
1089         {
1090                 pfree(cp[0]);
1091                 switch (nse->itemtype)
1092                 {
1093                         case PLPGSQL_NSTYPE_VAR:
1094                                 plpgsql_yylval.dtype = ((PLpgSQL_var *) (plpgsql_Datums[nse->itemno]))->datatype;
1095                                 return T_DTYPE;
1096
1097                                 /* XXX perhaps allow REC here? */
1098
1099                         default:
1100                                 return T_ERROR;
1101                 }
1102         }
1103
1104         /*
1105          * Word wasn't found on the namestack. Try to find a data type with that
1106          * name, but ignore shell types and complex types.
1107          */
1108         typeTup = LookupTypeName(NULL, makeTypeName(cp[0]), NULL);
1109         if (typeTup)
1110         {
1111                 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1112
1113                 if (!typeStruct->typisdefined ||
1114                         typeStruct->typrelid != InvalidOid)
1115                 {
1116                         ReleaseSysCache(typeTup);
1117                         pfree(cp[0]);
1118                         return T_ERROR;
1119                 }
1120
1121                 plpgsql_yylval.dtype = build_datatype(typeTup, -1);
1122
1123                 ReleaseSysCache(typeTup);
1124                 pfree(cp[0]);
1125                 return T_DTYPE;
1126         }
1127
1128         /*
1129          * Nothing found - up to now it's a word without any special meaning for
1130          * us.
1131          */
1132         pfree(cp[0]);
1133         return T_ERROR;
1134 }
1135
1136
1137 /* ----------
1138  * plpgsql_parse_dblwordtype            Same lookup for word.word%TYPE
1139  * ----------
1140  */
1141 int
1142 plpgsql_parse_dblwordtype(char *word)
1143 {
1144         PLpgSQL_nsitem *nse;
1145         bool            old_nsstate;
1146         Oid                     classOid;
1147         HeapTuple       classtup = NULL;
1148         HeapTuple       attrtup = NULL;
1149         HeapTuple       typetup = NULL;
1150         Form_pg_class classStruct;
1151         Form_pg_attribute attrStruct;
1152         char       *cp[3];
1153         int                     i;
1154         MemoryContext oldCxt;
1155         int                     result = T_ERROR;
1156
1157         /* Avoid memory leaks in the long-term function context */
1158         oldCxt = MemoryContextSwitchTo(compile_tmp_cxt);
1159
1160         /* Do case conversion and word separation */
1161         /* We convert %type to .type momentarily to keep converter happy */
1162         i = strlen(word) - 5;
1163         Assert(word[i] == '%');
1164         word[i] = '.';
1165         plpgsql_convert_ident(word, cp, 3);
1166         word[i] = '%';
1167         pfree(cp[2]);
1168
1169         /*
1170          * Do a lookup on the compiler's namestack.  Ensure we scan all levels. We
1171          * don't need to check number of names matched, because we will only
1172          * consider scalar variables.
1173          */
1174         old_nsstate = plpgsql_ns_setlocal(false);
1175         nse = plpgsql_ns_lookup(cp[0], cp[1], NULL, NULL);
1176         plpgsql_ns_setlocal(old_nsstate);
1177
1178         if (nse != NULL && nse->itemtype == PLPGSQL_NSTYPE_VAR)
1179         {
1180                 plpgsql_yylval.dtype = ((PLpgSQL_var *) (plpgsql_Datums[nse->itemno]))->datatype;
1181                 result = T_DTYPE;
1182                 goto done;
1183         }
1184
1185         /*
1186          * First word could also be a table name
1187          */
1188         classOid = RelnameGetRelid(cp[0]);
1189         if (!OidIsValid(classOid))
1190                 goto done;
1191
1192         classtup = SearchSysCache(RELOID,
1193                                                           ObjectIdGetDatum(classOid),
1194                                                           0, 0, 0);
1195         if (!HeapTupleIsValid(classtup))
1196                 goto done;
1197         classStruct = (Form_pg_class) GETSTRUCT(classtup);
1198
1199         /*
1200          * It must be a relation, sequence, view, or type
1201          */
1202         if (classStruct->relkind != RELKIND_RELATION &&
1203                 classStruct->relkind != RELKIND_SEQUENCE &&
1204                 classStruct->relkind != RELKIND_VIEW &&
1205                 classStruct->relkind != RELKIND_COMPOSITE_TYPE)
1206                 goto done;
1207
1208         /*
1209          * Fetch the named table field and its type
1210          */
1211         attrtup = SearchSysCacheAttName(classOid, cp[1]);
1212         if (!HeapTupleIsValid(attrtup))
1213                 goto done;
1214         attrStruct = (Form_pg_attribute) GETSTRUCT(attrtup);
1215
1216         typetup = SearchSysCache(TYPEOID,
1217                                                          ObjectIdGetDatum(attrStruct->atttypid),
1218                                                          0, 0, 0);
1219         if (!HeapTupleIsValid(typetup))
1220                 elog(ERROR, "cache lookup failed for type %u", attrStruct->atttypid);
1221
1222         /*
1223          * Found that - build a compiler type struct in the caller's cxt and
1224          * return it
1225          */
1226         MemoryContextSwitchTo(oldCxt);
1227         plpgsql_yylval.dtype = build_datatype(typetup, attrStruct->atttypmod);
1228         MemoryContextSwitchTo(compile_tmp_cxt);
1229         result = T_DTYPE;
1230
1231 done:
1232         if (HeapTupleIsValid(classtup))
1233                 ReleaseSysCache(classtup);
1234         if (HeapTupleIsValid(attrtup))
1235                 ReleaseSysCache(attrtup);
1236         if (HeapTupleIsValid(typetup))
1237                 ReleaseSysCache(typetup);
1238
1239         MemoryContextSwitchTo(oldCxt);
1240         return result;
1241 }
1242
1243 /* ----------
1244  * plpgsql_parse_tripwordtype           Same lookup for word.word.word%TYPE
1245  * ----------
1246  */
1247 int
1248 plpgsql_parse_tripwordtype(char *word)
1249 {
1250         Oid                     classOid;
1251         HeapTuple       classtup = NULL;
1252         HeapTuple       attrtup = NULL;
1253         HeapTuple       typetup = NULL;
1254         Form_pg_class classStruct;
1255         Form_pg_attribute attrStruct;
1256         char       *cp[4];
1257         int                     i;
1258         RangeVar   *relvar;
1259         MemoryContext oldCxt;
1260         int                     result = T_ERROR;
1261
1262         /* Avoid memory leaks in the long-term function context */
1263         oldCxt = MemoryContextSwitchTo(compile_tmp_cxt);
1264
1265         /* Do case conversion and word separation */
1266         /* We convert %type to .type momentarily to keep converter happy */
1267         i = strlen(word) - 5;
1268         Assert(word[i] == '%');
1269         word[i] = '.';
1270         plpgsql_convert_ident(word, cp, 4);
1271         word[i] = '%';
1272         pfree(cp[3]);
1273
1274         relvar = makeRangeVar(cp[0], cp[1], -1);
1275         classOid = RangeVarGetRelid(relvar, true);
1276         if (!OidIsValid(classOid))
1277                 goto done;
1278
1279         classtup = SearchSysCache(RELOID,
1280                                                           ObjectIdGetDatum(classOid),
1281                                                           0, 0, 0);
1282         if (!HeapTupleIsValid(classtup))
1283                 goto done;
1284         classStruct = (Form_pg_class) GETSTRUCT(classtup);
1285
1286         /*
1287          * It must be a relation, sequence, view, or type
1288          */
1289         if (classStruct->relkind != RELKIND_RELATION &&
1290                 classStruct->relkind != RELKIND_SEQUENCE &&
1291                 classStruct->relkind != RELKIND_VIEW &&
1292                 classStruct->relkind != RELKIND_COMPOSITE_TYPE)
1293                 goto done;
1294
1295         /*
1296          * Fetch the named table field and its type
1297          */
1298         attrtup = SearchSysCacheAttName(classOid, cp[2]);
1299         if (!HeapTupleIsValid(attrtup))
1300                 goto done;
1301         attrStruct = (Form_pg_attribute) GETSTRUCT(attrtup);
1302
1303         typetup = SearchSysCache(TYPEOID,
1304                                                          ObjectIdGetDatum(attrStruct->atttypid),
1305                                                          0, 0, 0);
1306         if (!HeapTupleIsValid(typetup))
1307                 elog(ERROR, "cache lookup failed for type %u", attrStruct->atttypid);
1308
1309         /*
1310          * Found that - build a compiler type struct in the caller's cxt and
1311          * return it
1312          */
1313         MemoryContextSwitchTo(oldCxt);
1314         plpgsql_yylval.dtype = build_datatype(typetup, attrStruct->atttypmod);
1315         MemoryContextSwitchTo(compile_tmp_cxt);
1316         result = T_DTYPE;
1317
1318 done:
1319         if (HeapTupleIsValid(classtup))
1320                 ReleaseSysCache(classtup);
1321         if (HeapTupleIsValid(attrtup))
1322                 ReleaseSysCache(attrtup);
1323         if (HeapTupleIsValid(typetup))
1324                 ReleaseSysCache(typetup);
1325
1326         MemoryContextSwitchTo(oldCxt);
1327         return result;
1328 }
1329
1330 /* ----------
1331  * plpgsql_parse_wordrowtype            Scanner found word%ROWTYPE.
1332  *                                      So word must be a table name.
1333  * ----------
1334  */
1335 int
1336 plpgsql_parse_wordrowtype(char *word)
1337 {
1338         Oid                     classOid;
1339         char       *cp[2];
1340         int                     i;
1341
1342         /* Do case conversion and word separation */
1343         /* We convert %rowtype to .rowtype momentarily to keep converter happy */
1344         i = strlen(word) - 8;
1345         Assert(word[i] == '%');
1346         word[i] = '.';
1347         plpgsql_convert_ident(word, cp, 2);
1348         word[i] = '%';
1349
1350         /* Lookup the relation */
1351         classOid = RelnameGetRelid(cp[0]);
1352         if (!OidIsValid(classOid))
1353                 ereport(ERROR,
1354                                 (errcode(ERRCODE_UNDEFINED_TABLE),
1355                                  errmsg("relation \"%s\" does not exist", cp[0])));
1356
1357         /*
1358          * Build and return the row type struct
1359          */
1360         plpgsql_yylval.dtype = plpgsql_build_datatype(get_rel_type_id(classOid),
1361                                                                                                   -1);
1362
1363         pfree(cp[0]);
1364         pfree(cp[1]);
1365
1366         return T_DTYPE;
1367 }
1368
1369 /* ----------
1370  * plpgsql_parse_dblwordrowtype         Scanner found word.word%ROWTYPE.
1371  *                      So word must be a namespace qualified table name.
1372  * ----------
1373  */
1374 int
1375 plpgsql_parse_dblwordrowtype(char *word)
1376 {
1377         Oid                     classOid;
1378         char       *cp[3];
1379         int                     i;
1380         RangeVar   *relvar;
1381         MemoryContext oldCxt;
1382
1383         /* Avoid memory leaks in long-term function context */
1384         oldCxt = MemoryContextSwitchTo(compile_tmp_cxt);
1385
1386         /* Do case conversion and word separation */
1387         /* We convert %rowtype to .rowtype momentarily to keep converter happy */
1388         i = strlen(word) - 8;
1389         Assert(word[i] == '%');
1390         word[i] = '.';
1391         plpgsql_convert_ident(word, cp, 3);
1392         word[i] = '%';
1393
1394         /* Lookup the relation */
1395         relvar = makeRangeVar(cp[0], cp[1], -1);
1396         classOid = RangeVarGetRelid(relvar, true);
1397         if (!OidIsValid(classOid))
1398                 ereport(ERROR,
1399                                 (errcode(ERRCODE_UNDEFINED_TABLE),
1400                                  errmsg("relation \"%s.%s\" does not exist", cp[0], cp[1])));
1401
1402         /* Build and return the row type struct */
1403         plpgsql_yylval.dtype = plpgsql_build_datatype(get_rel_type_id(classOid),
1404                                                                                                   -1);
1405
1406         MemoryContextSwitchTo(oldCxt);
1407         return T_DTYPE;
1408 }
1409
1410 /*
1411  * plpgsql_build_variable - build a datum-array entry of a given
1412  * datatype
1413  *
1414  * The returned struct may be a PLpgSQL_var, PLpgSQL_row, or
1415  * PLpgSQL_rec depending on the given datatype, and is allocated via
1416  * palloc.      The struct is automatically added to the current datum
1417  * array, and optionally to the current namespace.
1418  */
1419 PLpgSQL_variable *
1420 plpgsql_build_variable(const char *refname, int lineno, PLpgSQL_type *dtype,
1421                                            bool add2namespace)
1422 {
1423         PLpgSQL_variable *result;
1424
1425         switch (dtype->ttype)
1426         {
1427                 case PLPGSQL_TTYPE_SCALAR:
1428                         {
1429                                 /* Ordinary scalar datatype */
1430                                 PLpgSQL_var *var;
1431
1432                                 var = palloc0(sizeof(PLpgSQL_var));
1433                                 var->dtype = PLPGSQL_DTYPE_VAR;
1434                                 var->refname = pstrdup(refname);
1435                                 var->lineno = lineno;
1436                                 var->datatype = dtype;
1437                                 /* other fields might be filled by caller */
1438
1439                                 /* preset to NULL */
1440                                 var->value = 0;
1441                                 var->isnull = true;
1442                                 var->freeval = false;
1443
1444                                 plpgsql_adddatum((PLpgSQL_datum *) var);
1445                                 if (add2namespace)
1446                                         plpgsql_ns_additem(PLPGSQL_NSTYPE_VAR,
1447                                                                            var->dno,
1448                                                                            refname);
1449                                 result = (PLpgSQL_variable *) var;
1450                                 break;
1451                         }
1452                 case PLPGSQL_TTYPE_ROW:
1453                         {
1454                                 /* Composite type -- build a row variable */
1455                                 PLpgSQL_row *row;
1456
1457                                 row = build_row_from_class(dtype->typrelid);
1458
1459                                 row->dtype = PLPGSQL_DTYPE_ROW;
1460                                 row->refname = pstrdup(refname);
1461                                 row->lineno = lineno;
1462
1463                                 plpgsql_adddatum((PLpgSQL_datum *) row);
1464                                 if (add2namespace)
1465                                         plpgsql_ns_additem(PLPGSQL_NSTYPE_ROW,
1466                                                                            row->dno,
1467                                                                            refname);
1468                                 result = (PLpgSQL_variable *) row;
1469                                 break;
1470                         }
1471                 case PLPGSQL_TTYPE_REC:
1472                         {
1473                                 /* "record" type -- build a record variable */
1474                                 PLpgSQL_rec *rec;
1475
1476                                 rec = plpgsql_build_record(refname, lineno, add2namespace);
1477                                 result = (PLpgSQL_variable *) rec;
1478                                 break;
1479                         }
1480                 case PLPGSQL_TTYPE_PSEUDO:
1481                         ereport(ERROR,
1482                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1483                                          errmsg("variable \"%s\" has pseudo-type %s",
1484                                                         refname, format_type_be(dtype->typoid))));
1485                         result = NULL;          /* keep compiler quiet */
1486                         break;
1487                 default:
1488                         elog(ERROR, "unrecognized ttype: %d", dtype->ttype);
1489                         result = NULL;          /* keep compiler quiet */
1490                         break;
1491         }
1492
1493         return result;
1494 }
1495
1496 /*
1497  * Build empty named record variable, and optionally add it to namespace
1498  */
1499 PLpgSQL_rec *
1500 plpgsql_build_record(const char *refname, int lineno, bool add2namespace)
1501 {
1502         PLpgSQL_rec *rec;
1503
1504         rec = palloc0(sizeof(PLpgSQL_rec));
1505         rec->dtype = PLPGSQL_DTYPE_REC;
1506         rec->refname = pstrdup(refname);
1507         rec->lineno = lineno;
1508         rec->tup = NULL;
1509         rec->tupdesc = NULL;
1510         rec->freetup = false;
1511         plpgsql_adddatum((PLpgSQL_datum *) rec);
1512         if (add2namespace)
1513                 plpgsql_ns_additem(PLPGSQL_NSTYPE_REC, rec->dno, rec->refname);
1514
1515         return rec;
1516 }
1517
1518 /*
1519  * Build a row-variable data structure given the pg_class OID.
1520  */
1521 static PLpgSQL_row *
1522 build_row_from_class(Oid classOid)
1523 {
1524         PLpgSQL_row *row;
1525         Relation        rel;
1526         Form_pg_class classStruct;
1527         const char *relname;
1528         int                     i;
1529
1530         /*
1531          * Open the relation to get info.
1532          */
1533         rel = relation_open(classOid, AccessShareLock);
1534         classStruct = RelationGetForm(rel);
1535         relname = RelationGetRelationName(rel);
1536
1537         /* accept relation, sequence, view, or composite type entries */
1538         if (classStruct->relkind != RELKIND_RELATION &&
1539                 classStruct->relkind != RELKIND_SEQUENCE &&
1540                 classStruct->relkind != RELKIND_VIEW &&
1541                 classStruct->relkind != RELKIND_COMPOSITE_TYPE)
1542                 ereport(ERROR,
1543                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1544                                  errmsg("relation \"%s\" is not a table", relname)));
1545
1546         /*
1547          * Create a row datum entry and all the required variables that it will
1548          * point to.
1549          */
1550         row = palloc0(sizeof(PLpgSQL_row));
1551         row->dtype = PLPGSQL_DTYPE_ROW;
1552         row->rowtupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
1553         row->nfields = classStruct->relnatts;
1554         row->fieldnames = palloc(sizeof(char *) * row->nfields);
1555         row->varnos = palloc(sizeof(int) * row->nfields);
1556
1557         for (i = 0; i < row->nfields; i++)
1558         {
1559                 Form_pg_attribute attrStruct;
1560
1561                 /*
1562                  * Get the attribute and check for dropped column
1563                  */
1564                 attrStruct = row->rowtupdesc->attrs[i];
1565
1566                 if (!attrStruct->attisdropped)
1567                 {
1568                         char       *attname;
1569                         char            refname[(NAMEDATALEN * 2) + 100];
1570                         PLpgSQL_variable *var;
1571
1572                         attname = NameStr(attrStruct->attname);
1573                         snprintf(refname, sizeof(refname), "%s.%s", relname, attname);
1574
1575                         /*
1576                          * Create the internal variable for the field
1577                          *
1578                          * We know if the table definitions contain a default value or if
1579                          * the field is declared in the table as NOT NULL. But it's
1580                          * possible to create a table field as NOT NULL without a default
1581                          * value and that would lead to problems later when initializing
1582                          * the variables due to entering a block at execution time. Thus
1583                          * we ignore this information for now.
1584                          */
1585                         var = plpgsql_build_variable(refname, 0,
1586                                                                  plpgsql_build_datatype(attrStruct->atttypid,
1587                                                                                                           attrStruct->atttypmod),
1588                                                                                  false);
1589
1590                         /* Add the variable to the row */
1591                         row->fieldnames[i] = attname;
1592                         row->varnos[i] = var->dno;
1593                 }
1594                 else
1595                 {
1596                         /* Leave a hole in the row structure for the dropped col */
1597                         row->fieldnames[i] = NULL;
1598                         row->varnos[i] = -1;
1599                 }
1600         }
1601
1602         relation_close(rel, AccessShareLock);
1603
1604         return row;
1605 }
1606
1607 /*
1608  * Build a row-variable data structure given the component variables.
1609  */
1610 static PLpgSQL_row *
1611 build_row_from_vars(PLpgSQL_variable **vars, int numvars)
1612 {
1613         PLpgSQL_row *row;
1614         int                     i;
1615
1616         row = palloc0(sizeof(PLpgSQL_row));
1617         row->dtype = PLPGSQL_DTYPE_ROW;
1618         row->rowtupdesc = CreateTemplateTupleDesc(numvars, false);
1619         row->nfields = numvars;
1620         row->fieldnames = palloc(numvars * sizeof(char *));
1621         row->varnos = palloc(numvars * sizeof(int));
1622
1623         for (i = 0; i < numvars; i++)
1624         {
1625                 PLpgSQL_variable *var = vars[i];
1626                 Oid                     typoid = RECORDOID;
1627                 int32           typmod = -1;
1628
1629                 switch (var->dtype)
1630                 {
1631                         case PLPGSQL_DTYPE_VAR:
1632                                 typoid = ((PLpgSQL_var *) var)->datatype->typoid;
1633                                 typmod = ((PLpgSQL_var *) var)->datatype->atttypmod;
1634                                 break;
1635
1636                         case PLPGSQL_DTYPE_REC:
1637                                 break;
1638
1639                         case PLPGSQL_DTYPE_ROW:
1640                                 if (((PLpgSQL_row *) var)->rowtupdesc)
1641                                 {
1642                                         typoid = ((PLpgSQL_row *) var)->rowtupdesc->tdtypeid;
1643                                         typmod = ((PLpgSQL_row *) var)->rowtupdesc->tdtypmod;
1644                                 }
1645                                 break;
1646
1647                         default:
1648                                 elog(ERROR, "unrecognized dtype: %d", var->dtype);
1649                 }
1650
1651                 row->fieldnames[i] = var->refname;
1652                 row->varnos[i] = var->dno;
1653
1654                 TupleDescInitEntry(row->rowtupdesc, i + 1,
1655                                                    var->refname,
1656                                                    typoid, typmod,
1657                                                    0);
1658         }
1659
1660         return row;
1661 }
1662
1663
1664 /* ----------
1665  * plpgsql_parse_datatype                       Scanner found something that should
1666  *                                      be a datatype name.
1667  * ----------
1668  */
1669 PLpgSQL_type *
1670 plpgsql_parse_datatype(const char *string)
1671 {
1672         Oid                     type_id;
1673         int32           typmod;
1674
1675         /* Let the main parser try to parse it under standard SQL rules */
1676         parseTypeString(string, &type_id, &typmod);
1677
1678         /* Okay, build a PLpgSQL_type data structure for it */
1679         return plpgsql_build_datatype(type_id, typmod);
1680 }
1681
1682 /*
1683  * plpgsql_build_datatype
1684  *              Build PLpgSQL_type struct given type OID and typmod.
1685  */
1686 PLpgSQL_type *
1687 plpgsql_build_datatype(Oid typeOid, int32 typmod)
1688 {
1689         HeapTuple       typeTup;
1690         PLpgSQL_type *typ;
1691
1692         typeTup = SearchSysCache(TYPEOID,
1693                                                          ObjectIdGetDatum(typeOid),
1694                                                          0, 0, 0);
1695         if (!HeapTupleIsValid(typeTup))
1696                 elog(ERROR, "cache lookup failed for type %u", typeOid);
1697
1698         typ = build_datatype(typeTup, typmod);
1699
1700         ReleaseSysCache(typeTup);
1701
1702         return typ;
1703 }
1704
1705 /*
1706  * Utility subroutine to make a PLpgSQL_type struct given a pg_type entry
1707  */
1708 static PLpgSQL_type *
1709 build_datatype(HeapTuple typeTup, int32 typmod)
1710 {
1711         Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1712         PLpgSQL_type *typ;
1713
1714         if (!typeStruct->typisdefined)
1715                 ereport(ERROR,
1716                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1717                                  errmsg("type \"%s\" is only a shell",
1718                                                 NameStr(typeStruct->typname))));
1719
1720         typ = (PLpgSQL_type *) palloc(sizeof(PLpgSQL_type));
1721
1722         typ->typname = pstrdup(NameStr(typeStruct->typname));
1723         typ->typoid = HeapTupleGetOid(typeTup);
1724         switch (typeStruct->typtype)
1725         {
1726                 case TYPTYPE_BASE:
1727                 case TYPTYPE_DOMAIN:
1728                 case TYPTYPE_ENUM:
1729                         typ->ttype = PLPGSQL_TTYPE_SCALAR;
1730                         break;
1731                 case TYPTYPE_COMPOSITE:
1732                         Assert(OidIsValid(typeStruct->typrelid));
1733                         typ->ttype = PLPGSQL_TTYPE_ROW;
1734                         break;
1735                 case TYPTYPE_PSEUDO:
1736                         if (typ->typoid == RECORDOID)
1737                                 typ->ttype = PLPGSQL_TTYPE_REC;
1738                         else
1739                                 typ->ttype = PLPGSQL_TTYPE_PSEUDO;
1740                         break;
1741                 default:
1742                         elog(ERROR, "unrecognized typtype: %d",
1743                                  (int) typeStruct->typtype);
1744                         break;
1745         }
1746         typ->typlen = typeStruct->typlen;
1747         typ->typbyval = typeStruct->typbyval;
1748         typ->typrelid = typeStruct->typrelid;
1749         typ->typioparam = getTypeIOParam(typeTup);
1750         fmgr_info(typeStruct->typinput, &(typ->typinput));
1751         typ->atttypmod = typmod;
1752
1753         return typ;
1754 }
1755
1756 /*
1757  *      plpgsql_recognize_err_condition
1758  *              Check condition name and translate it to SQLSTATE.
1759  *
1760  * Note: there are some cases where the same condition name has multiple
1761  * entries in the table.  We arbitrarily return the first match.
1762  */
1763 int
1764 plpgsql_recognize_err_condition(const char *condname, bool allow_sqlstate)
1765 {
1766         int                     i;
1767
1768         if (allow_sqlstate)
1769         {
1770                 if (strlen(condname) == 5 &&
1771                         strspn(condname, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") == 5)
1772                         return MAKE_SQLSTATE(condname[0],
1773                                                                  condname[1],
1774                                                                  condname[2],
1775                                                                  condname[3],
1776                                                                  condname[4]);
1777         }
1778
1779         for (i = 0; exception_label_map[i].label != NULL; i++)
1780         {
1781                 if (strcmp(condname, exception_label_map[i].label) == 0)
1782                         return exception_label_map[i].sqlerrstate;
1783         }
1784
1785         ereport(ERROR,
1786                         (errcode(ERRCODE_UNDEFINED_OBJECT),
1787                          errmsg("unrecognized exception condition \"%s\"",
1788                                         condname)));
1789         return 0;                                       /* keep compiler quiet */
1790 }
1791
1792 /*
1793  * plpgsql_parse_err_condition
1794  *              Generate PLpgSQL_condition entry(s) for an exception condition name
1795  *
1796  * This has to be able to return a list because there are some duplicate
1797  * names in the table of error code names.
1798  */
1799 PLpgSQL_condition *
1800 plpgsql_parse_err_condition(char *condname)
1801 {
1802         int                     i;
1803         PLpgSQL_condition *new;
1804         PLpgSQL_condition *prev;
1805
1806         /*
1807          * XXX Eventually we will want to look for user-defined exception names
1808          * here.
1809          */
1810
1811         /*
1812          * OTHERS is represented as code 0 (which would map to '00000', but we
1813          * have no need to represent that as an exception condition).
1814          */
1815         if (strcmp(condname, "others") == 0)
1816         {
1817                 new = palloc(sizeof(PLpgSQL_condition));
1818                 new->sqlerrstate = 0;
1819                 new->condname = condname;
1820                 new->next = NULL;
1821                 return new;
1822         }
1823
1824         prev = NULL;
1825         for (i = 0; exception_label_map[i].label != NULL; i++)
1826         {
1827                 if (strcmp(condname, exception_label_map[i].label) == 0)
1828                 {
1829                         new = palloc(sizeof(PLpgSQL_condition));
1830                         new->sqlerrstate = exception_label_map[i].sqlerrstate;
1831                         new->condname = condname;
1832                         new->next = prev;
1833                         prev = new;
1834                 }
1835         }
1836
1837         if (!prev)
1838                 ereport(ERROR,
1839                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1840                                  errmsg("unrecognized exception condition \"%s\"",
1841                                                 condname)));
1842
1843         return prev;
1844 }
1845
1846 /* ----------
1847  * plpgsql_adddatum                     Add a variable, record or row
1848  *                                      to the compiler's datum list.
1849  * ----------
1850  */
1851 void
1852 plpgsql_adddatum(PLpgSQL_datum *new)
1853 {
1854         if (plpgsql_nDatums == datums_alloc)
1855         {
1856                 datums_alloc *= 2;
1857                 plpgsql_Datums = repalloc(plpgsql_Datums, sizeof(PLpgSQL_datum *) * datums_alloc);
1858         }
1859
1860         new->dno = plpgsql_nDatums;
1861         plpgsql_Datums[plpgsql_nDatums++] = new;
1862 }
1863
1864
1865 /* ----------
1866  * plpgsql_add_initdatums               Make an array of the datum numbers of
1867  *                                      all the simple VAR datums created since the last call
1868  *                                      to this function.
1869  *
1870  * If varnos is NULL, we just forget any datum entries created since the
1871  * last call.
1872  *
1873  * This is used around a DECLARE section to create a list of the VARs
1874  * that have to be initialized at block entry.  Note that VARs can also
1875  * be created elsewhere than DECLARE, eg by a FOR-loop, but it is then
1876  * the responsibility of special-purpose code to initialize them.
1877  * ----------
1878  */
1879 int
1880 plpgsql_add_initdatums(int **varnos)
1881 {
1882         int                     i;
1883         int                     n = 0;
1884
1885         for (i = datums_last; i < plpgsql_nDatums; i++)
1886         {
1887                 switch (plpgsql_Datums[i]->dtype)
1888                 {
1889                         case PLPGSQL_DTYPE_VAR:
1890                                 n++;
1891                                 break;
1892
1893                         default:
1894                                 break;
1895                 }
1896         }
1897
1898         if (varnos != NULL)
1899         {
1900                 if (n > 0)
1901                 {
1902                         *varnos = (int *) palloc(sizeof(int) * n);
1903
1904                         n = 0;
1905                         for (i = datums_last; i < plpgsql_nDatums; i++)
1906                         {
1907                                 switch (plpgsql_Datums[i]->dtype)
1908                                 {
1909                                         case PLPGSQL_DTYPE_VAR:
1910                                                 (*varnos)[n++] = plpgsql_Datums[i]->dno;
1911
1912                                         default:
1913                                                 break;
1914                                 }
1915                         }
1916                 }
1917                 else
1918                         *varnos = NULL;
1919         }
1920
1921         datums_last = plpgsql_nDatums;
1922         return n;
1923 }
1924
1925
1926 /*
1927  * Compute the hashkey for a given function invocation
1928  *
1929  * The hashkey is returned into the caller-provided storage at *hashkey.
1930  */
1931 static void
1932 compute_function_hashkey(FunctionCallInfo fcinfo,
1933                                                  Form_pg_proc procStruct,
1934                                                  PLpgSQL_func_hashkey *hashkey,
1935                                                  bool forValidator)
1936 {
1937         /* Make sure any unused bytes of the struct are zero */
1938         MemSet(hashkey, 0, sizeof(PLpgSQL_func_hashkey));
1939
1940         /* get function OID */
1941         hashkey->funcOid = fcinfo->flinfo->fn_oid;
1942
1943         /* get call context */
1944         hashkey->isTrigger = CALLED_AS_TRIGGER(fcinfo);
1945
1946         /*
1947          * if trigger, get relation OID.  In validation mode we do not know what
1948          * relation is intended to be used, so we leave trigrelOid zero; the hash
1949          * entry built in this case will never really be used.
1950          */
1951         if (hashkey->isTrigger && !forValidator)
1952         {
1953                 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1954
1955                 hashkey->trigrelOid = RelationGetRelid(trigdata->tg_relation);
1956         }
1957
1958         if (procStruct->pronargs > 0)
1959         {
1960                 /* get the argument types */
1961                 memcpy(hashkey->argtypes, procStruct->proargtypes.values,
1962                            procStruct->pronargs * sizeof(Oid));
1963
1964                 /* resolve any polymorphic argument types */
1965                 plpgsql_resolve_polymorphic_argtypes(procStruct->pronargs,
1966                                                                                          hashkey->argtypes,
1967                                                                                          NULL,
1968                                                                                          fcinfo->flinfo->fn_expr,
1969                                                                                          forValidator,
1970                                                                                          NameStr(procStruct->proname));
1971         }
1972 }
1973
1974 /*
1975  * This is the same as the standard resolve_polymorphic_argtypes() function,
1976  * but with a special case for validation: assume that polymorphic arguments
1977  * are integer or integer-array.  Also, we go ahead and report the error
1978  * if we can't resolve the types.
1979  */
1980 static void
1981 plpgsql_resolve_polymorphic_argtypes(int numargs,
1982                                                                          Oid *argtypes, char *argmodes,
1983                                                                          Node *call_expr, bool forValidator,
1984                                                                          const char *proname)
1985 {
1986         int                     i;
1987
1988         if (!forValidator)
1989         {
1990                 /* normal case, pass to standard routine */
1991                 if (!resolve_polymorphic_argtypes(numargs, argtypes, argmodes,
1992                                                                                   call_expr))
1993                         ereport(ERROR,
1994                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1995                                          errmsg("could not determine actual argument "
1996                                                         "type for polymorphic function \"%s\"",
1997                                                         proname)));
1998         }
1999         else
2000         {
2001                 /* special validation case */
2002                 for (i = 0; i < numargs; i++)
2003                 {
2004                         switch (argtypes[i])
2005                         {
2006                                 case ANYELEMENTOID:
2007                                 case ANYNONARRAYOID:
2008                                 case ANYENUMOID:                /* XXX dubious */
2009                                         argtypes[i] = INT4OID;
2010                                         break;
2011                                 case ANYARRAYOID:
2012                                         argtypes[i] = INT4ARRAYOID;
2013                                         break;
2014                                 default:
2015                                         break;
2016                         }
2017                 }
2018         }
2019 }
2020
2021 /*
2022  * delete_function - clean up as much as possible of a stale function cache
2023  *
2024  * We can't release the PLpgSQL_function struct itself, because of the
2025  * possibility that there are fn_extra pointers to it.  We can release
2026  * the subsidiary storage, but only if there are no active evaluations
2027  * in progress.  Otherwise we'll just leak that storage.  Since the
2028  * case would only occur if a pg_proc update is detected during a nested
2029  * recursive call on the function, a leak seems acceptable.
2030  *
2031  * Note that this can be called more than once if there are multiple fn_extra
2032  * pointers to the same function cache.  Hence be careful not to do things
2033  * twice.
2034  */
2035 static void
2036 delete_function(PLpgSQL_function *func)
2037 {
2038         /* remove function from hash table (might be done already) */
2039         plpgsql_HashTableDelete(func);
2040
2041         /* release the function's storage if safe and not done already */
2042         if (func->use_count == 0 && func->fn_cxt)
2043         {
2044                 MemoryContextDelete(func->fn_cxt);
2045                 func->fn_cxt = NULL;
2046         }
2047 }
2048
2049 /* exported so we can call it from plpgsql_init() */
2050 void
2051 plpgsql_HashTableInit(void)
2052 {
2053         HASHCTL         ctl;
2054
2055         /* don't allow double-initialization */
2056         Assert(plpgsql_HashTable == NULL);
2057
2058         memset(&ctl, 0, sizeof(ctl));
2059         ctl.keysize = sizeof(PLpgSQL_func_hashkey);
2060         ctl.entrysize = sizeof(plpgsql_HashEnt);
2061         ctl.hash = tag_hash;
2062         plpgsql_HashTable = hash_create("PLpgSQL function cache",
2063                                                                         FUNCS_PER_USER,
2064                                                                         &ctl,
2065                                                                         HASH_ELEM | HASH_FUNCTION);
2066 }
2067
2068 static PLpgSQL_function *
2069 plpgsql_HashTableLookup(PLpgSQL_func_hashkey *func_key)
2070 {
2071         plpgsql_HashEnt *hentry;
2072
2073         hentry = (plpgsql_HashEnt *) hash_search(plpgsql_HashTable,
2074                                                                                          (void *) func_key,
2075                                                                                          HASH_FIND,
2076                                                                                          NULL);
2077         if (hentry)
2078                 return hentry->function;
2079         else
2080                 return NULL;
2081 }
2082
2083 static void
2084 plpgsql_HashTableInsert(PLpgSQL_function *function,
2085                                                 PLpgSQL_func_hashkey *func_key)
2086 {
2087         plpgsql_HashEnt *hentry;
2088         bool            found;
2089
2090         hentry = (plpgsql_HashEnt *) hash_search(plpgsql_HashTable,
2091                                                                                          (void *) func_key,
2092                                                                                          HASH_ENTER,
2093                                                                                          &found);
2094         if (found)
2095                 elog(WARNING, "trying to insert a function that already exists");
2096
2097         hentry->function = function;
2098         /* prepare back link from function to hashtable key */
2099         function->fn_hashkey = &hentry->key;
2100 }
2101
2102 static void
2103 plpgsql_HashTableDelete(PLpgSQL_function *function)
2104 {
2105         plpgsql_HashEnt *hentry;
2106
2107         /* do nothing if not in table */
2108         if (function->fn_hashkey == NULL)
2109                 return;
2110
2111         hentry = (plpgsql_HashEnt *) hash_search(plpgsql_HashTable,
2112                                                                                          (void *) function->fn_hashkey,
2113                                                                                          HASH_REMOVE,
2114                                                                                          NULL);
2115         if (hentry == NULL)
2116                 elog(WARNING, "trying to delete function that does not exist");
2117
2118         /* remove back link, which no longer points to allocated storage */
2119         function->fn_hashkey = NULL;
2120 }