1 /*-------------------------------------------------------------------------
3 * pl_comp.c - Compiler part of the PL/pgSQL
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/pl/plpgsql/src/pl_comp.c
13 *-------------------------------------------------------------------------
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"
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"
39 * Our own local and global variables
42 PLpgSQL_stmt_block *plpgsql_parse_result;
44 static int datums_alloc;
46 PLpgSQL_datum **plpgsql_Datums;
47 static int datums_last = 0;
49 char *plpgsql_error_funcname;
50 bool plpgsql_DumpExecTree = false;
51 bool plpgsql_check_syntax = false;
53 PLpgSQL_function *plpgsql_curr_compile;
55 /* A context appropriate for short-term allocs during compilation */
56 MemoryContext compile_tmp_cxt;
59 * Hash table for compiled functions
62 static HTAB *plpgsql_HashTable = NULL;
64 typedef struct plpgsql_hashent
66 PLpgSQL_func_hashkey key;
67 PLpgSQL_function *function;
70 #define FUNCS_PER_USER 128 /* initial table size */
73 * Lookup table for EXCEPTION condition names
82 static const ExceptionLabelMap exception_label_map[] = {
83 #include "plerrcodes.h"
92 static PLpgSQL_function *do_compile(FunctionCallInfo fcinfo,
94 PLpgSQL_function *function,
95 PLpgSQL_func_hashkey *hashkey,
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,
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);
124 * plpgsql_compile Make an execution tree for a PL/pgSQL function.
126 * If forValidator is true, we're only compiling for validation purposes,
127 * and so some checks are skipped.
129 * Note: it's important for this to fall through quickly if the function
130 * has already been compiled.
134 plpgsql_compile(FunctionCallInfo fcinfo, bool forValidator)
136 Oid funcOid = fcinfo->flinfo->fn_oid;
138 Form_pg_proc procStruct;
139 PLpgSQL_function *function;
140 PLpgSQL_func_hashkey hashkey;
141 bool function_valid = false;
142 bool hashkey_valid = false;
145 * Lookup the pg_proc tuple by Oid; we'll need it in any case
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);
153 * See if there's already a cache entry for the current FmgrInfo. If not,
154 * try to find one in the hash table.
156 function = (PLpgSQL_function *) fcinfo->flinfo->fn_extra;
161 /* Compute hashkey using function signature and actual arg types */
162 compute_function_hashkey(fcinfo, procStruct, &hashkey, forValidator);
163 hashkey_valid = true;
165 /* And do the lookup */
166 function = plpgsql_HashTableLookup(&hashkey);
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;
178 * Nope, so remove it from hashtable and try to drop associated
179 * storage (if not done already).
181 delete_function(function);
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.)
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
197 if (function->use_count != 0)
207 * If the function wasn't found or was out-of-date, we have to compile it
212 * Calculate hashkey if we didn't already; we'll need it to store the
213 * completed function.
216 compute_function_hashkey(fcinfo, procStruct, &hashkey,
222 function = do_compile(fcinfo, procTup, function,
223 &hashkey, forValidator);
226 ReleaseSysCache(procTup);
229 * Save pointer in FmgrInfo to avoid search on subsequent calls
231 fcinfo->flinfo->fn_extra = (void *) function;
234 * Finally return the compiled function
240 * This is the slow part of plpgsql_compile().
242 * The passed-in "function" pointer is either NULL or an already-allocated
243 * function struct to overwrite.
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.
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.
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.
261 static PLpgSQL_function *
262 do_compile(FunctionCallInfo fcinfo,
264 PLpgSQL_function *function,
265 PLpgSQL_func_hashkey *hashkey,
268 Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
269 bool is_trigger = CALLED_AS_TRIGGER(fcinfo);
274 Form_pg_type typeStruct;
275 PLpgSQL_variable *var;
278 ErrorContextCallback plerrcontext;
283 int num_out_args = 0;
287 int *in_arg_varnos = NULL;
288 PLpgSQL_variable **out_arg_variables;
289 MemoryContext func_cxt;
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.
296 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
297 Anum_pg_proc_prosrc, &isnull);
299 elog(ERROR, "null prosrc");
300 proc_source = TextDatumGetCString(prosrcdatum);
301 plpgsql_scanner_init(proc_source);
303 plpgsql_error_funcname = pstrdup(NameStr(procStruct->proname));
306 * Setup error traceback support for ereport()
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;
314 * Do extra syntax checks when validating the function definition. We skip
315 * this when actually compiling functions for execution, for performance
318 plpgsql_check_syntax = forValidator;
321 * Create the new function struct, if not done already. The function
322 * structs are never thrown away, so keep them in TopMemoryContext.
324 if (function == NULL)
326 function = (PLpgSQL_function *)
327 MemoryContextAllocZero(TopMemoryContext, sizeof(PLpgSQL_function));
331 /* re-using a previously existing struct, so clear it out */
332 memset(function, 0, sizeof(PLpgSQL_function));
334 plpgsql_curr_compile = function;
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.
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);
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;
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.
363 plpgsql_ns_push(NameStr(procStruct->proname));
364 plpgsql_DumpExecTree = false;
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);
378 * Fetch info about the procedure's parameters. Allocations aren't
379 * needed permanently, so make them in tmp cxt.
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.
385 MemoryContextSwitchTo(compile_tmp_cxt);
387 numargs = get_func_arg_info(procTup,
388 &argtypes, &argnames, &argmodes);
390 plpgsql_resolve_polymorphic_argtypes(numargs, argtypes, argmodes,
391 fcinfo->flinfo->fn_expr,
393 plpgsql_error_funcname);
395 in_arg_varnos = (int *) palloc(numargs * sizeof(int));
396 out_arg_variables = (PLpgSQL_variable **) palloc(numargs * sizeof(PLpgSQL_variable *));
398 MemoryContextSwitchTo(func_cxt);
401 * Create the variables for the procedure's parameters.
403 for (i = 0; i < numargs; i++)
406 Oid argtypeid = argtypes[i];
407 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
408 PLpgSQL_type *argdtype;
409 PLpgSQL_variable *argvariable;
412 /* Create $n name for variable */
413 snprintf(buf, sizeof(buf), "$%d", i + 1);
415 /* Create datatype info */
416 argdtype = plpgsql_build_datatype(argtypeid,
418 function->fn_input_collation);
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)
426 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
427 errmsg("PL/pgSQL functions cannot accept type %s",
428 format_type_be(argtypeid))));
430 /* Build variable and add to datum list */
431 argvariable = plpgsql_build_variable(buf, 0,
434 if (argvariable->dtype == PLPGSQL_DTYPE_VAR)
436 argitemtype = PLPGSQL_NSTYPE_VAR;
440 Assert(argvariable->dtype == PLPGSQL_DTYPE_ROW);
441 argitemtype = PLPGSQL_NSTYPE_ROW;
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;
454 /* Add to namespace under the $n name */
455 add_parameter_name(argitemtype, argvariable->dno, buf);
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,
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
468 if (num_out_args == 1)
469 function->out_param_varno = out_arg_variables[0]->dno;
470 else if (num_out_args > 1)
472 PLpgSQL_row *row = build_row_from_vars(out_arg_variables,
475 plpgsql_adddatum((PLpgSQL_datum *) row);
476 function->out_param_varno = row->dno;
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
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.
489 rettypeid = procStruct->prorettype;
490 if (IsPolymorphicType(rettypeid))
494 if (rettypeid == ANYARRAYOID)
495 rettypeid = INT4ARRAYOID;
496 else /* ANYELEMENT or ANYNONARRAY */
498 /* XXX what could we use for ANYENUM? */
502 rettypeid = get_fn_expr_rettype(fcinfo->flinfo);
503 if (!OidIsValid(rettypeid))
505 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
506 errmsg("could not determine actual return type "
507 "for polymorphic function \"%s\"",
508 plpgsql_error_funcname)));
513 * Normal function has a defined returntype
515 function->fn_rettype = rettypeid;
516 function->fn_retset = procStruct->proretset;
519 * Lookup the function's return type
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);
526 /* Disallow pseudotype result, except VOID or RECORD */
527 /* (note we already replaced polymorphic types) */
528 if (typeStruct->typtype == TYPTYPE_PSEUDO)
530 if (rettypeid == VOIDOID ||
531 rettypeid == RECORDOID)
533 else if (rettypeid == TRIGGEROID)
535 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
536 errmsg("trigger functions can only be called as triggers")));
539 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
540 errmsg("PL/pgSQL functions cannot return type %s",
541 format_type_be(rettypeid))));
544 if (typeStruct->typrelid != InvalidOid ||
545 rettypeid == RECORDOID)
546 function->fn_retistuple = true;
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));
555 * install $0 reference, but only for polymorphic return
556 * types, and not when the return is specified through an
559 if (IsPolymorphicType(procStruct->prorettype) &&
562 (void) plpgsql_build_variable("$0", 0,
563 build_datatype(typeTup,
565 function->fn_input_collation),
569 ReleaseSysCache(typeTup);
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;
579 /* shouldn't be any declared arguments */
580 if (procStruct->pronargs != 0)
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.")));
586 /* Add the record for referencing NEW */
587 rec = plpgsql_build_record("new", 0, true);
588 function->new_varno = rec->dno;
590 /* Add the record for referencing OLD */
591 rec = plpgsql_build_record("old", 0, true);
592 function->old_varno = rec->dno;
594 /* Add the variable tg_name */
595 var = plpgsql_build_variable("tg_name", 0,
596 plpgsql_build_datatype(NAMEOID,
600 function->tg_name_varno = var->dno;
602 /* Add the variable tg_when */
603 var = plpgsql_build_variable("tg_when", 0,
604 plpgsql_build_datatype(TEXTOID,
606 function->fn_input_collation),
608 function->tg_when_varno = var->dno;
610 /* Add the variable tg_level */
611 var = plpgsql_build_variable("tg_level", 0,
612 plpgsql_build_datatype(TEXTOID,
614 function->fn_input_collation),
616 function->tg_level_varno = var->dno;
618 /* Add the variable tg_op */
619 var = plpgsql_build_variable("tg_op", 0,
620 plpgsql_build_datatype(TEXTOID,
622 function->fn_input_collation),
624 function->tg_op_varno = var->dno;
626 /* Add the variable tg_relid */
627 var = plpgsql_build_variable("tg_relid", 0,
628 plpgsql_build_datatype(OIDOID,
632 function->tg_relid_varno = var->dno;
634 /* Add the variable tg_relname */
635 var = plpgsql_build_variable("tg_relname", 0,
636 plpgsql_build_datatype(NAMEOID,
640 function->tg_relname_varno = var->dno;
642 /* tg_table_name is now preferred to tg_relname */
643 var = plpgsql_build_variable("tg_table_name", 0,
644 plpgsql_build_datatype(NAMEOID,
648 function->tg_table_name_varno = var->dno;
650 /* add the variable tg_table_schema */
651 var = plpgsql_build_variable("tg_table_schema", 0,
652 plpgsql_build_datatype(NAMEOID,
656 function->tg_table_schema_varno = var->dno;
658 /* Add the variable tg_nargs */
659 var = plpgsql_build_variable("tg_nargs", 0,
660 plpgsql_build_datatype(INT4OID,
664 function->tg_nargs_varno = var->dno;
666 /* Add the variable tg_argv */
667 var = plpgsql_build_variable("tg_argv", 0,
668 plpgsql_build_datatype(TEXTARRAYOID,
670 function->fn_input_collation),
672 function->tg_argv_varno = var->dno;
677 elog(ERROR, "unrecognized function typecode: %d", (int) is_trigger);
681 /* Remember if function is STABLE/IMMUTABLE */
682 function->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
685 * Create the magic FOUND variable.
687 var = plpgsql_build_variable("found", 0,
688 plpgsql_build_datatype(BOOLOID,
692 function->found_varno = var->dno;
695 * Now parse the function's text
697 parse_rc = plpgsql_yyparse();
699 elog(ERROR, "plpgsql parser returned %d", parse_rc);
700 function->action = plpgsql_parse_result;
702 plpgsql_scanner_finish();
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.
711 if (num_out_args > 0 || function->fn_rettype == VOIDOID ||
713 add_dummy_return(function);
716 * Complete the function's info
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];
726 /* Debug dump for completed functions */
727 if (plpgsql_DumpExecTree)
728 plpgsql_dumptree(function);
731 * add it to the hash table
733 plpgsql_HashTableInsert(function, hashkey);
736 * Pop the error context stack
738 error_context_stack = plerrcontext.previous;
739 plpgsql_error_funcname = NULL;
741 plpgsql_check_syntax = false;
743 MemoryContextSwitchTo(compile_tmp_cxt);
744 compile_tmp_cxt = NULL;
749 * plpgsql_compile_inline Make an execution tree for an anonymous code block.
751 * Note: this is generally parallel to do_compile(); is it worth trying to
754 * Note: we assume the block will be thrown away so there is no need to build
755 * persistent data structures.
759 plpgsql_compile_inline(char *proc_source)
761 char *func_name = "inline_code_block";
762 PLpgSQL_function *function;
763 ErrorContextCallback plerrcontext;
765 PLpgSQL_variable *var;
767 MemoryContext func_cxt;
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.
775 plpgsql_scanner_init(proc_source);
777 plpgsql_error_funcname = func_name;
780 * Setup error traceback support for ereport()
782 plerrcontext.callback = plpgsql_compile_error_callback;
783 plerrcontext.arg = proc_source;
784 plerrcontext.previous = error_context_stack;
785 error_context_stack = &plerrcontext;
787 /* Do extra syntax checking if check_function_bodies is on */
788 plpgsql_check_syntax = check_function_bodies;
790 /* Function struct does not live past current statement */
791 function = (PLpgSQL_function *) palloc0(sizeof(PLpgSQL_function));
793 plpgsql_curr_compile = function;
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.
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);
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;
814 plpgsql_ns_push(func_name);
815 plpgsql_DumpExecTree = false;
819 plpgsql_Datums = palloc(sizeof(PLpgSQL_datum *) * datums_alloc);
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));
833 * Remember if function is STABLE/IMMUTABLE. XXX would it be better to
834 * set this TRUE inside a read-only transaction? Not clear.
836 function->fn_readonly = false;
839 * Create the magic FOUND variable.
841 var = plpgsql_build_variable("found", 0,
842 plpgsql_build_datatype(BOOLOID,
846 function->found_varno = var->dno;
849 * Now parse the function's text
851 parse_rc = plpgsql_yyparse();
853 elog(ERROR, "plpgsql parser returned %d", parse_rc);
854 function->action = plpgsql_parse_result;
856 plpgsql_scanner_finish();
859 * If it returns VOID (always true at the moment), we allow control to
860 * fall off the end without an explicit RETURN statement.
862 if (function->fn_rettype == VOIDOID)
863 add_dummy_return(function);
866 * Complete the function's info
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];
875 * Pop the error context stack
877 error_context_stack = plerrcontext.previous;
878 plpgsql_error_funcname = NULL;
880 plpgsql_check_syntax = false;
882 MemoryContextSwitchTo(compile_tmp_cxt);
883 compile_tmp_cxt = NULL;
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.
894 plpgsql_compile_error_callback(void *arg)
899 * Try to convert syntax error position to reference text of original
900 * CREATE FUNCTION or DO command.
902 if (function_parse_error_transpose((const char *) arg))
906 * Done if a syntax error position was reported; otherwise we have to
907 * fall back to a "near line N" report.
911 if (plpgsql_error_funcname)
912 errcontext("compilation of PL/pgSQL function \"%s\" near line %d",
913 plpgsql_error_funcname, plpgsql_latest_lineno());
918 * Add a name for a function parameter to the function's namespace
921 add_parameter_name(int itemtype, int itemno, const char *name)
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
930 if (plpgsql_ns_lookup(plpgsql_ns_top(), true,
934 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
935 errmsg("parameter name \"%s\" used more than once",
938 /* OK, add the name */
939 plpgsql_ns_additem(itemtype, itemno, name);
943 * Add a dummy RETURN statement to the given function's body
946 add_dummy_return(PLpgSQL_function *function)
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
953 if (function->action->exceptions != NULL)
955 PLpgSQL_stmt_block *new;
957 new = palloc0(sizeof(PLpgSQL_stmt_block));
958 new->cmd_type = PLPGSQL_STMT_BLOCK;
959 new->body = list_make1(function->action);
961 function->action = new;
963 if (function->action->body == NIL ||
964 ((PLpgSQL_stmt *) llast(function->action->body))->cmd_type != PLPGSQL_STMT_RETURN)
966 PLpgSQL_stmt_return *new;
968 new = palloc0(sizeof(PLpgSQL_stmt_return));
969 new->cmd_type = PLPGSQL_STMT_RETURN;
971 new->retvarno = function->out_param_varno;
973 function->action->body = lappend(function->action->body, new);
979 * plpgsql_parser_setup set up parser hooks for dynamic parameters
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.
987 plpgsql_parser_setup(struct ParseState *pstate, PLpgSQL_expr *expr)
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;
997 * plpgsql_pre_column_ref parser callback before parsing a ColumnRef
1000 plpgsql_pre_column_ref(ParseState *pstate, ColumnRef *cref)
1002 PLpgSQL_expr *expr = (PLpgSQL_expr *) pstate->p_ref_hook_state;
1004 if (expr->func->resolve_option == PLPGSQL_RESOLVE_VARIABLE)
1005 return resolve_column_ref(pstate, expr, cref, false);
1011 * plpgsql_post_column_ref parser callback after parsing a ColumnRef
1014 plpgsql_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
1016 PLpgSQL_expr *expr = (PLpgSQL_expr *) pstate->p_ref_hook_state;
1019 if (expr->func->resolve_option == PLPGSQL_RESOLVE_VARIABLE)
1020 return NULL; /* we already found there's no match */
1022 if (expr->func->resolve_option == PLPGSQL_RESOLVE_COLUMN && var != NULL)
1023 return NULL; /* there's a table column, prefer that */
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.)
1035 myvar = resolve_column_ref(pstate, expr, cref, (var == NULL));
1037 if (myvar != NULL && var != NULL)
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.
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)));
1055 * plpgsql_param_ref parser callback for ParamRefs ($n symbols)
1058 plpgsql_param_ref(ParseState *pstate, ParamRef *pref)
1060 PLpgSQL_expr *expr = (PLpgSQL_expr *) pstate->p_ref_hook_state;
1062 PLpgSQL_nsitem *nse;
1064 snprintf(pname, sizeof(pname), "$%d", pref->number);
1066 nse = plpgsql_ns_lookup(expr->ns, false,
1071 return NULL; /* name not known to plpgsql */
1073 return make_datum_param(expr, nse->itemno, pref->location);
1077 * resolve_column_ref attempt to resolve a ColumnRef as a plpgsql var
1079 * Returns the translated node structure, or NULL if name not found
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.
1085 resolve_column_ref(ParseState *pstate, PLpgSQL_expr *expr,
1086 ColumnRef *cref, bool error_if_no_field)
1088 PLpgSQL_execstate *estate;
1089 PLpgSQL_nsitem *nse;
1091 const char *name2 = NULL;
1092 const char *name3 = NULL;
1093 const char *colname = NULL;
1095 int nnames_scalar = 0;
1096 int nnames_wholerow = 0;
1097 int nnames_field = 0;
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 ...
1104 estate = expr->func->cur_estate;
1107 * The allowed syntaxes are:
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.
1116 switch (list_length(cref->fields))
1120 Node *field1 = (Node *) linitial(cref->fields);
1122 Assert(IsA(field1, String));
1123 name1 = strVal(field1);
1125 nnames_wholerow = 1;
1130 Node *field1 = (Node *) linitial(cref->fields);
1131 Node *field2 = (Node *) lsecond(cref->fields);
1133 Assert(IsA(field1, String));
1134 name1 = strVal(field1);
1136 /* Whole-row reference? */
1137 if (IsA(field2, A_Star))
1139 /* Set name2 to prevent matches to scalar variables */
1141 nnames_wholerow = 1;
1145 Assert(IsA(field2, String));
1146 name2 = strVal(field2);
1149 nnames_wholerow = 2;
1155 Node *field1 = (Node *) linitial(cref->fields);
1156 Node *field2 = (Node *) lsecond(cref->fields);
1157 Node *field3 = (Node *) lthird(cref->fields);
1159 Assert(IsA(field1, String));
1160 name1 = strVal(field1);
1161 Assert(IsA(field2, String));
1162 name2 = strVal(field2);
1164 /* Whole-row reference? */
1165 if (IsA(field3, A_Star))
1167 /* Set name3 to prevent matches to scalar variables */
1169 nnames_wholerow = 2;
1173 Assert(IsA(field3, String));
1174 name3 = strVal(field3);
1180 /* too many names, ignore */
1184 nse = plpgsql_ns_lookup(expr->ns, false,
1185 name1, name2, name3,
1189 return NULL; /* name not known to plpgsql */
1191 switch (nse->itemtype)
1193 case PLPGSQL_NSTYPE_VAR:
1194 if (nnames == nnames_scalar)
1195 return make_datum_param(expr, nse->itemno, cref->location);
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)
1202 /* colname could be a field in this record */
1205 /* search for a datum referencing this field */
1206 for (i = 0; i < estate->ndatums; i++)
1208 PLpgSQL_recfield *fld = (PLpgSQL_recfield *) estate->datums[i];
1210 if (fld->dtype == PLPGSQL_DTYPE_RECFIELD &&
1211 fld->recparentno == nse->itemno &&
1212 strcmp(fld->fieldname, colname) == 0)
1214 return make_datum_param(expr, i, cref->location);
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.
1224 if (error_if_no_field)
1226 (errcode(ERRCODE_UNDEFINED_COLUMN),
1227 errmsg("record \"%s\" has no field \"%s\"",
1228 (nnames_field == 1) ? name1 : name2,
1230 parser_errposition(pstate, cref->location)));
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)
1238 /* colname could be a field in this row */
1239 PLpgSQL_row *row = (PLpgSQL_row *) estate->datums[nse->itemno];
1242 for (i = 0; i < row->nfields; i++)
1244 if (row->fieldnames[i] &&
1245 strcmp(row->fieldnames[i], colname) == 0)
1247 return make_datum_param(expr, row->varnos[i],
1251 /* Not found, so throw error or return NULL */
1252 if (error_if_no_field)
1254 (errcode(ERRCODE_UNDEFINED_COLUMN),
1255 errmsg("record \"%s\" has no field \"%s\"",
1256 (nnames_field == 1) ? name1 : name2,
1258 parser_errposition(pstate, cref->location)));
1262 elog(ERROR, "unrecognized plpgsql itemtype: %d", nse->itemtype);
1265 /* Name format doesn't match the plpgsql variable type */
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.
1274 make_datum_param(PLpgSQL_expr *expr, int dno, int location)
1276 PLpgSQL_execstate *estate;
1277 PLpgSQL_datum *datum;
1279 MemoryContext oldcontext;
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];
1287 * Bitmapset must be allocated in function's permanent memory context
1289 oldcontext = MemoryContextSwitchTo(expr->func->fn_cxt);
1290 expr->paramnos = bms_add_member(expr->paramnos, dno);
1291 MemoryContextSwitchTo(oldcontext);
1293 param = makeNode(Param);
1294 param->paramkind = PARAM_EXTERN;
1295 param->paramid = dno + 1;
1296 exec_get_datum_type_info(estate,
1299 ¶m->paramtypmod,
1300 ¶m->paramcollid);
1301 param->location = location;
1303 return (Node *) param;
1308 * plpgsql_parse_word The scanner calls this to postparse
1309 * any single word that is not a reserved keyword.
1311 * word1 is the downcased/dequoted identifier; it must be palloc'd in the
1312 * function's long-term memory context.
1314 * yytxt is the original token text; we need this to check for quoting,
1315 * so that later checks for unreserved keywords work properly.
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.)
1324 plpgsql_parse_word(char *word1, const char *yytxt,
1325 PLwdatum *wdatum, PLword *word)
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.
1334 if (plpgsql_IdentifierLookup == IDENTIFIER_LOOKUP_NORMAL)
1337 * Do a lookup in the current namespace stack
1339 ns = plpgsql_ns_lookup(plpgsql_ns_top(), false,
1345 switch (ns->itemtype)
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;
1357 /* plpgsql_ns_lookup should never return anything else */
1358 elog(ERROR, "unrecognized plpgsql itemtype: %d",
1365 * Nothing found - up to now it's a word without any special meaning for
1368 word->ident = word1;
1369 word->quoted = (yytxt[0] == '"');
1375 * plpgsql_parse_dblword Same lookup for two words
1376 * separated by a dot.
1380 plpgsql_parse_dblword(char *word1, char *word2,
1381 PLwdatum *wdatum, PLcword *cword)
1387 idents = list_make2(makeString(word1),
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
1395 if (plpgsql_IdentifierLookup != IDENTIFIER_LOOKUP_DECLARE)
1398 * Do a lookup in the current namespace stack
1400 ns = plpgsql_ns_lookup(plpgsql_ns_top(), false,
1405 switch (ns->itemtype)
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;
1415 case PLPGSQL_NSTYPE_REC:
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
1424 PLpgSQL_recfield *new;
1426 new = palloc(sizeof(PLpgSQL_recfield));
1427 new->dtype = PLPGSQL_DTYPE_RECFIELD;
1428 new->fieldname = pstrdup(word2);
1429 new->recparentno = ns->itemno;
1431 plpgsql_adddatum((PLpgSQL_datum *) new);
1433 wdatum->datum = (PLpgSQL_datum *) new;
1437 /* Block-qualified reference to record variable. */
1438 wdatum->datum = plpgsql_Datums[ns->itemno];
1440 wdatum->ident = NULL;
1441 wdatum->quoted = false; /* not used */
1442 wdatum->idents = idents;
1445 case PLPGSQL_NSTYPE_ROW:
1449 * First word is a row name, so second word could be a
1450 * field in this row. Again, no error now if it
1456 row = (PLpgSQL_row *) (plpgsql_Datums[ns->itemno]);
1457 for (i = 0; i < row->nfields; i++)
1459 if (row->fieldnames[i] &&
1460 strcmp(row->fieldnames[i], word2) == 0)
1462 wdatum->datum = plpgsql_Datums[row->varnos[i]];
1463 wdatum->ident = NULL;
1464 wdatum->quoted = false; /* not used */
1465 wdatum->idents = idents;
1469 /* fall through to return CWORD */
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;
1489 cword->idents = idents;
1495 * plpgsql_parse_tripword Same lookup for three words
1496 * separated by dots.
1500 plpgsql_parse_tripword(char *word1, char *word2, char *word3,
1501 PLwdatum *wdatum, PLcword *cword)
1507 idents = list_make3(makeString(word1),
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
1516 if (plpgsql_IdentifierLookup != IDENTIFIER_LOOKUP_DECLARE)
1519 * Do a lookup in the current namespace stack. Must find a qualified
1520 * reference, else ignore.
1522 ns = plpgsql_ns_lookup(plpgsql_ns_top(), false,
1523 word1, word2, word3,
1525 if (ns != NULL && nnames == 2)
1527 switch (ns->itemtype)
1529 case PLPGSQL_NSTYPE_REC:
1532 * words 1/2 are a record name, so third word could be
1533 * a field in this record.
1535 PLpgSQL_recfield *new;
1537 new = palloc(sizeof(PLpgSQL_recfield));
1538 new->dtype = PLPGSQL_DTYPE_RECFIELD;
1539 new->fieldname = pstrdup(word3);
1540 new->recparentno = ns->itemno;
1542 plpgsql_adddatum((PLpgSQL_datum *) new);
1544 wdatum->datum = (PLpgSQL_datum *) new;
1545 wdatum->ident = NULL;
1546 wdatum->quoted = false; /* not used */
1547 wdatum->idents = idents;
1551 case PLPGSQL_NSTYPE_ROW:
1554 * words 1/2 are a row name, so third word could be a
1555 * field in this row.
1560 row = (PLpgSQL_row *) (plpgsql_Datums[ns->itemno]);
1561 for (i = 0; i < row->nfields; i++)
1563 if (row->fieldnames[i] &&
1564 strcmp(row->fieldnames[i], word3) == 0)
1566 wdatum->datum = plpgsql_Datums[row->varnos[i]];
1567 wdatum->ident = NULL;
1568 wdatum->quoted = false; /* not used */
1569 wdatum->idents = idents;
1573 /* fall through to return CWORD */
1584 cword->idents = idents;
1590 * plpgsql_parse_wordtype The scanner found word%TYPE. word can be
1591 * a variable name or a basetype.
1593 * Returns datatype struct, or NULL if no match found for word.
1597 plpgsql_parse_wordtype(char *ident)
1599 PLpgSQL_type *dtype;
1600 PLpgSQL_nsitem *nse;
1604 * Do a lookup in the current namespace stack
1606 nse = plpgsql_ns_lookup(plpgsql_ns_top(), false,
1612 switch (nse->itemtype)
1614 case PLPGSQL_NSTYPE_VAR:
1615 return ((PLpgSQL_var *) (plpgsql_Datums[nse->itemno]))->datatype;
1617 /* XXX perhaps allow REC/ROW here? */
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.
1628 typeTup = LookupTypeName(NULL, makeTypeName(ident), NULL);
1631 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1633 if (!typeStruct->typisdefined ||
1634 typeStruct->typrelid != InvalidOid)
1636 ReleaseSysCache(typeTup);
1640 dtype = build_datatype(typeTup, -1,
1641 plpgsql_curr_compile->fn_input_collation);
1643 ReleaseSysCache(typeTup);
1648 * Nothing found - up to now it's a word without any special meaning for
1656 * plpgsql_parse_cwordtype Same lookup for compositeword%TYPE
1660 plpgsql_parse_cwordtype(List *idents)
1662 PLpgSQL_type *dtype = NULL;
1663 PLpgSQL_nsitem *nse;
1664 const char *fldname;
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;
1673 /* Avoid memory leaks in the long-term function context */
1674 oldCxt = MemoryContextSwitchTo(compile_tmp_cxt);
1676 if (list_length(idents) == 2)
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
1683 nse = plpgsql_ns_lookup(plpgsql_ns_top(), false,
1684 strVal(linitial(idents)),
1685 strVal(lsecond(idents)),
1689 if (nse != NULL && nse->itemtype == PLPGSQL_NSTYPE_VAR)
1691 dtype = ((PLpgSQL_var *) (plpgsql_Datums[nse->itemno]))->datatype;
1696 * First word could also be a table name
1698 classOid = RelnameGetRelid(strVal(linitial(idents)));
1699 if (!OidIsValid(classOid))
1701 fldname = strVal(lsecond(idents));
1703 else if (list_length(idents) == 3)
1707 relvar = makeRangeVar(strVal(linitial(idents)),
1708 strVal(lsecond(idents)),
1710 classOid = RangeVarGetRelid(relvar, true);
1711 if (!OidIsValid(classOid))
1713 fldname = strVal(lthird(idents));
1718 classtup = SearchSysCache1(RELOID, ObjectIdGetDatum(classOid));
1719 if (!HeapTupleIsValid(classtup))
1721 classStruct = (Form_pg_class) GETSTRUCT(classtup);
1724 * It must be a relation, sequence, view, or type
1726 if (classStruct->relkind != RELKIND_RELATION &&
1727 classStruct->relkind != RELKIND_SEQUENCE &&
1728 classStruct->relkind != RELKIND_VIEW &&
1729 classStruct->relkind != RELKIND_COMPOSITE_TYPE)
1733 * Fetch the named table field and its type
1735 attrtup = SearchSysCacheAttName(classOid, fldname);
1736 if (!HeapTupleIsValid(attrtup))
1738 attrStruct = (Form_pg_attribute) GETSTRUCT(attrtup);
1740 typetup = SearchSysCache1(TYPEOID,
1741 ObjectIdGetDatum(attrStruct->atttypid));
1742 if (!HeapTupleIsValid(typetup))
1743 elog(ERROR, "cache lookup failed for type %u", attrStruct->atttypid);
1746 * Found that - build a compiler type struct in the caller's cxt and
1749 MemoryContextSwitchTo(oldCxt);
1750 dtype = build_datatype(typetup,
1751 attrStruct->atttypmod,
1752 attrStruct->attcollation);
1753 MemoryContextSwitchTo(compile_tmp_cxt);
1756 if (HeapTupleIsValid(classtup))
1757 ReleaseSysCache(classtup);
1758 if (HeapTupleIsValid(attrtup))
1759 ReleaseSysCache(attrtup);
1760 if (HeapTupleIsValid(typetup))
1761 ReleaseSysCache(typetup);
1763 MemoryContextSwitchTo(oldCxt);
1768 * plpgsql_parse_wordrowtype Scanner found word%ROWTYPE.
1769 * So word must be a table name.
1773 plpgsql_parse_wordrowtype(char *ident)
1777 /* Lookup the relation */
1778 classOid = RelnameGetRelid(ident);
1779 if (!OidIsValid(classOid))
1781 (errcode(ERRCODE_UNDEFINED_TABLE),
1782 errmsg("relation \"%s\" does not exist", ident)));
1784 /* Build and return the row type struct */
1785 return plpgsql_build_datatype(get_rel_type_id(classOid), -1, InvalidOid);
1789 * plpgsql_parse_cwordrowtype Scanner found compositeword%ROWTYPE.
1790 * So word must be a namespace qualified table name.
1794 plpgsql_parse_cwordrowtype(List *idents)
1798 MemoryContext oldCxt;
1800 if (list_length(idents) != 2)
1803 /* Avoid memory leaks in long-term function context */
1804 oldCxt = MemoryContextSwitchTo(compile_tmp_cxt);
1806 /* Lookup the relation */
1807 relvar = makeRangeVar(strVal(linitial(idents)),
1808 strVal(lsecond(idents)),
1810 classOid = RangeVarGetRelid(relvar, true);
1811 if (!OidIsValid(classOid))
1813 (errcode(ERRCODE_UNDEFINED_TABLE),
1814 errmsg("relation \"%s.%s\" does not exist",
1815 strVal(linitial(idents)), strVal(lsecond(idents)))));
1817 MemoryContextSwitchTo(oldCxt);
1819 /* Build and return the row type struct */
1820 return plpgsql_build_datatype(get_rel_type_id(classOid), -1, InvalidOid);
1824 * plpgsql_build_variable - build a datum-array entry of a given
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.
1833 plpgsql_build_variable(const char *refname, int lineno, PLpgSQL_type *dtype,
1836 PLpgSQL_variable *result;
1838 switch (dtype->ttype)
1840 case PLPGSQL_TTYPE_SCALAR:
1842 /* Ordinary scalar datatype */
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 */
1852 /* preset to NULL */
1855 var->freeval = false;
1857 plpgsql_adddatum((PLpgSQL_datum *) var);
1859 plpgsql_ns_additem(PLPGSQL_NSTYPE_VAR,
1862 result = (PLpgSQL_variable *) var;
1865 case PLPGSQL_TTYPE_ROW:
1867 /* Composite type -- build a row variable */
1870 row = build_row_from_class(dtype->typrelid);
1872 row->dtype = PLPGSQL_DTYPE_ROW;
1873 row->refname = pstrdup(refname);
1874 row->lineno = lineno;
1876 plpgsql_adddatum((PLpgSQL_datum *) row);
1878 plpgsql_ns_additem(PLPGSQL_NSTYPE_ROW,
1881 result = (PLpgSQL_variable *) row;
1884 case PLPGSQL_TTYPE_REC:
1886 /* "record" type -- build a record variable */
1889 rec = plpgsql_build_record(refname, lineno, add2namespace);
1890 result = (PLpgSQL_variable *) rec;
1893 case PLPGSQL_TTYPE_PSEUDO:
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 */
1901 elog(ERROR, "unrecognized ttype: %d", dtype->ttype);
1902 result = NULL; /* keep compiler quiet */
1910 * Build empty named record variable, and optionally add it to namespace
1913 plpgsql_build_record(const char *refname, int lineno, bool add2namespace)
1917 rec = palloc0(sizeof(PLpgSQL_rec));
1918 rec->dtype = PLPGSQL_DTYPE_REC;
1919 rec->refname = pstrdup(refname);
1920 rec->lineno = lineno;
1922 rec->tupdesc = NULL;
1923 rec->freetup = false;
1924 plpgsql_adddatum((PLpgSQL_datum *) rec);
1926 plpgsql_ns_additem(PLPGSQL_NSTYPE_REC, rec->dno, rec->refname);
1932 * Build a row-variable data structure given the pg_class OID.
1934 static PLpgSQL_row *
1935 build_row_from_class(Oid classOid)
1939 Form_pg_class classStruct;
1940 const char *relname;
1944 * Open the relation to get info.
1946 rel = relation_open(classOid, AccessShareLock);
1947 classStruct = RelationGetForm(rel);
1948 relname = RelationGetRelationName(rel);
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)
1956 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1957 errmsg("relation \"%s\" is not a table", relname)));
1960 * Create a row datum entry and all the required variables that it will
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);
1970 for (i = 0; i < row->nfields; i++)
1972 Form_pg_attribute attrStruct;
1975 * Get the attribute and check for dropped column
1977 attrStruct = row->rowtupdesc->attrs[i];
1979 if (!attrStruct->attisdropped)
1982 char refname[(NAMEDATALEN * 2) + 100];
1983 PLpgSQL_variable *var;
1985 attname = NameStr(attrStruct->attname);
1986 snprintf(refname, sizeof(refname), "%s.%s", relname, attname);
1989 * Create the internal variable for the field
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.
1998 var = plpgsql_build_variable(refname, 0,
1999 plpgsql_build_datatype(attrStruct->atttypid,
2000 attrStruct->atttypmod,
2001 attrStruct->attcollation),
2004 /* Add the variable to the row */
2005 row->fieldnames[i] = attname;
2006 row->varnos[i] = var->dno;
2010 /* Leave a hole in the row structure for the dropped col */
2011 row->fieldnames[i] = NULL;
2012 row->varnos[i] = -1;
2016 relation_close(rel, AccessShareLock);
2022 * Build a row-variable data structure given the component variables.
2024 static PLpgSQL_row *
2025 build_row_from_vars(PLpgSQL_variable **vars, int numvars)
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));
2037 for (i = 0; i < numvars; i++)
2039 PLpgSQL_variable *var = vars[i];
2040 Oid typoid = RECORDOID;
2042 Oid typcoll = InvalidOid;
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;
2052 case PLPGSQL_DTYPE_REC:
2055 case PLPGSQL_DTYPE_ROW:
2056 if (((PLpgSQL_row *) var)->rowtupdesc)
2058 typoid = ((PLpgSQL_row *) var)->rowtupdesc->tdtypeid;
2059 typmod = ((PLpgSQL_row *) var)->rowtupdesc->tdtypmod;
2060 /* composite types have no collation */
2065 elog(ERROR, "unrecognized dtype: %d", var->dtype);
2068 row->fieldnames[i] = var->refname;
2069 row->varnos[i] = var->dno;
2071 TupleDescInitEntry(row->rowtupdesc, i + 1,
2075 TupleDescInitEntryCollation(row->rowtupdesc, i + 1, typcoll);
2082 * plpgsql_build_datatype
2083 * Build PLpgSQL_type struct given type OID, typmod, and collation.
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.
2089 plpgsql_build_datatype(Oid typeOid, int32 typmod, Oid collation)
2094 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
2095 if (!HeapTupleIsValid(typeTup))
2096 elog(ERROR, "cache lookup failed for type %u", typeOid);
2098 typ = build_datatype(typeTup, typmod, collation);
2100 ReleaseSysCache(typeTup);
2106 * Utility subroutine to make a PLpgSQL_type struct given a pg_type entry
2108 static PLpgSQL_type *
2109 build_datatype(HeapTuple typeTup, int32 typmod, Oid collation)
2111 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2114 if (!typeStruct->typisdefined)
2116 (errcode(ERRCODE_UNDEFINED_OBJECT),
2117 errmsg("type \"%s\" is only a shell",
2118 NameStr(typeStruct->typname))));
2120 typ = (PLpgSQL_type *) palloc(sizeof(PLpgSQL_type));
2122 typ->typname = pstrdup(NameStr(typeStruct->typname));
2123 typ->typoid = HeapTupleGetOid(typeTup);
2124 switch (typeStruct->typtype)
2127 case TYPTYPE_DOMAIN:
2129 typ->ttype = PLPGSQL_TTYPE_SCALAR;
2131 case TYPTYPE_COMPOSITE:
2132 Assert(OidIsValid(typeStruct->typrelid));
2133 typ->ttype = PLPGSQL_TTYPE_ROW;
2135 case TYPTYPE_PSEUDO:
2136 if (typ->typoid == RECORDOID)
2137 typ->ttype = PLPGSQL_TTYPE_REC;
2139 typ->ttype = PLPGSQL_TTYPE_PSEUDO;
2142 elog(ERROR, "unrecognized typtype: %d",
2143 (int) typeStruct->typtype);
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;
2160 * plpgsql_recognize_err_condition
2161 * Check condition name and translate it to SQLSTATE.
2163 * Note: there are some cases where the same condition name has multiple
2164 * entries in the table. We arbitrarily return the first match.
2167 plpgsql_recognize_err_condition(const char *condname, bool allow_sqlstate)
2173 if (strlen(condname) == 5 &&
2174 strspn(condname, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") == 5)
2175 return MAKE_SQLSTATE(condname[0],
2182 for (i = 0; exception_label_map[i].label != NULL; i++)
2184 if (strcmp(condname, exception_label_map[i].label) == 0)
2185 return exception_label_map[i].sqlerrstate;
2189 (errcode(ERRCODE_UNDEFINED_OBJECT),
2190 errmsg("unrecognized exception condition \"%s\"",
2192 return 0; /* keep compiler quiet */
2196 * plpgsql_parse_err_condition
2197 * Generate PLpgSQL_condition entry(s) for an exception condition name
2199 * This has to be able to return a list because there are some duplicate
2200 * names in the table of error code names.
2203 plpgsql_parse_err_condition(char *condname)
2206 PLpgSQL_condition *new;
2207 PLpgSQL_condition *prev;
2210 * XXX Eventually we will want to look for user-defined exception names
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).
2218 if (strcmp(condname, "others") == 0)
2220 new = palloc(sizeof(PLpgSQL_condition));
2221 new->sqlerrstate = 0;
2222 new->condname = condname;
2228 for (i = 0; exception_label_map[i].label != NULL; i++)
2230 if (strcmp(condname, exception_label_map[i].label) == 0)
2232 new = palloc(sizeof(PLpgSQL_condition));
2233 new->sqlerrstate = exception_label_map[i].sqlerrstate;
2234 new->condname = condname;
2242 (errcode(ERRCODE_UNDEFINED_OBJECT),
2243 errmsg("unrecognized exception condition \"%s\"",
2250 * plpgsql_adddatum Add a variable, record or row
2251 * to the compiler's datum list.
2255 plpgsql_adddatum(PLpgSQL_datum *new)
2257 if (plpgsql_nDatums == datums_alloc)
2260 plpgsql_Datums = repalloc(plpgsql_Datums, sizeof(PLpgSQL_datum *) * datums_alloc);
2263 new->dno = plpgsql_nDatums;
2264 plpgsql_Datums[plpgsql_nDatums++] = new;
2269 * plpgsql_add_initdatums Make an array of the datum numbers of
2270 * all the simple VAR datums created since the last call
2273 * If varnos is NULL, we just forget any datum entries created since the
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.
2283 plpgsql_add_initdatums(int **varnos)
2288 for (i = datums_last; i < plpgsql_nDatums; i++)
2290 switch (plpgsql_Datums[i]->dtype)
2292 case PLPGSQL_DTYPE_VAR:
2305 *varnos = (int *) palloc(sizeof(int) * n);
2308 for (i = datums_last; i < plpgsql_nDatums; i++)
2310 switch (plpgsql_Datums[i]->dtype)
2312 case PLPGSQL_DTYPE_VAR:
2313 (*varnos)[n++] = plpgsql_Datums[i]->dno;
2324 datums_last = plpgsql_nDatums;
2330 * Compute the hashkey for a given function invocation
2332 * The hashkey is returned into the caller-provided storage at *hashkey.
2335 compute_function_hashkey(FunctionCallInfo fcinfo,
2336 Form_pg_proc procStruct,
2337 PLpgSQL_func_hashkey *hashkey,
2340 /* Make sure any unused bytes of the struct are zero */
2341 MemSet(hashkey, 0, sizeof(PLpgSQL_func_hashkey));
2343 /* get function OID */
2344 hashkey->funcOid = fcinfo->flinfo->fn_oid;
2346 /* get call context */
2347 hashkey->isTrigger = CALLED_AS_TRIGGER(fcinfo);
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.
2354 if (hashkey->isTrigger && !forValidator)
2356 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2358 hashkey->trigrelOid = RelationGetRelid(trigdata->tg_relation);
2361 /* get input collation, if known */
2362 hashkey->inputCollation = fcinfo->fncollation;
2364 if (procStruct->pronargs > 0)
2366 /* get the argument types */
2367 memcpy(hashkey->argtypes, procStruct->proargtypes.values,
2368 procStruct->pronargs * sizeof(Oid));
2370 /* resolve any polymorphic argument types */
2371 plpgsql_resolve_polymorphic_argtypes(procStruct->pronargs,
2374 fcinfo->flinfo->fn_expr,
2376 NameStr(procStruct->proname));
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.
2387 plpgsql_resolve_polymorphic_argtypes(int numargs,
2388 Oid *argtypes, char *argmodes,
2389 Node *call_expr, bool forValidator,
2390 const char *proname)
2396 /* normal case, pass to standard routine */
2397 if (!resolve_polymorphic_argtypes(numargs, argtypes, argmodes,
2400 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2401 errmsg("could not determine actual argument "
2402 "type for polymorphic function \"%s\"",
2407 /* special validation case */
2408 for (i = 0; i < numargs; i++)
2410 switch (argtypes[i])
2413 case ANYNONARRAYOID:
2414 case ANYENUMOID: /* XXX dubious */
2415 argtypes[i] = INT4OID;
2418 argtypes[i] = INT4ARRAYOID;
2428 * delete_function - clean up as much as possible of a stale function cache
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.
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
2442 delete_function(PLpgSQL_function *func)
2444 /* remove function from hash table (might be done already) */
2445 plpgsql_HashTableDelete(func);
2447 /* release the function's storage if safe and not done already */
2448 if (func->use_count == 0)
2449 plpgsql_free_function_memory(func);
2452 /* exported so we can call it from plpgsql_init() */
2454 plpgsql_HashTableInit(void)
2458 /* don't allow double-initialization */
2459 Assert(plpgsql_HashTable == NULL);
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",
2468 HASH_ELEM | HASH_FUNCTION);
2471 static PLpgSQL_function *
2472 plpgsql_HashTableLookup(PLpgSQL_func_hashkey *func_key)
2474 plpgsql_HashEnt *hentry;
2476 hentry = (plpgsql_HashEnt *) hash_search(plpgsql_HashTable,
2481 return hentry->function;
2487 plpgsql_HashTableInsert(PLpgSQL_function *function,
2488 PLpgSQL_func_hashkey *func_key)
2490 plpgsql_HashEnt *hentry;
2493 hentry = (plpgsql_HashEnt *) hash_search(plpgsql_HashTable,
2498 elog(WARNING, "trying to insert a function that already exists");
2500 hentry->function = function;
2501 /* prepare back link from function to hashtable key */
2502 function->fn_hashkey = &hentry->key;
2506 plpgsql_HashTableDelete(PLpgSQL_function *function)
2508 plpgsql_HashEnt *hentry;
2510 /* do nothing if not in table */
2511 if (function->fn_hashkey == NULL)
2514 hentry = (plpgsql_HashEnt *) hash_search(plpgsql_HashTable,
2515 (void *) function->fn_hashkey,
2519 elog(WARNING, "trying to delete function that does not exist");
2521 /* remove back link, which no longer points to allocated storage */
2522 function->fn_hashkey = NULL;