OSDN Git Service

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