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