PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
functions.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * functions.c
4  * Execution of SQL-language functions
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/executor/functions.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "executor/functions.h"
22 #include "funcapi.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_func.h"
28 #include "storage/proc.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/datum.h"
32 #include "utils/lsyscache.h"
33 #include "utils/memutils.h"
34 #include "utils/snapmgr.h"
35 #include "utils/syscache.h"
36 
37 
38 /*
39  * Specialized DestReceiver for collecting query output in a SQL function
40  */
41 typedef struct
42 {
43  DestReceiver pub; /* publicly-known function pointers */
44  Tuplestorestate *tstore; /* where to put result tuples */
45  MemoryContext cxt; /* context containing tstore */
46  JunkFilter *filter; /* filter to convert tuple type */
48 
49 /*
50  * We have an execution_state record for each query in a function. Each
51  * record contains a plantree for its query. If the query is currently in
52  * F_EXEC_RUN state then there's a QueryDesc too.
53  *
54  * The "next" fields chain together all the execution_state records generated
55  * from a single original parsetree. (There will only be more than one in
56  * case of rule expansion of the original parsetree.)
57  */
58 typedef enum
59 {
61 } ExecStatus;
62 
63 typedef struct execution_state
64 {
67  bool setsResult; /* true if this query produces func's result */
68  bool lazyEval; /* true if should fetch one row at a time */
69  PlannedStmt *stmt; /* plan for this query */
70  QueryDesc *qd; /* null unless status == RUN */
72 
73 
74 /*
75  * An SQLFunctionCache record is built during the first call,
76  * and linked to from the fn_extra field of the FmgrInfo struct.
77  *
78  * Note that currently this has only the lifespan of the calling query.
79  * Someday we should rewrite this code to use plancache.c to save parse/plan
80  * results for longer than that.
81  *
82  * Physically, though, the data has the lifespan of the FmgrInfo that's used
83  * to call the function, and there are cases (particularly with indexes)
84  * where the FmgrInfo might survive across transactions. We cannot assume
85  * that the parse/plan trees are good for longer than the (sub)transaction in
86  * which parsing was done, so we must mark the record with the LXID/subxid of
87  * its creation time, and regenerate everything if that's obsolete. To avoid
88  * memory leakage when we do have to regenerate things, all the data is kept
89  * in a sub-context of the FmgrInfo's fn_mcxt.
90  */
91 typedef struct
92 {
93  char *fname; /* function name (for error msgs) */
94  char *src; /* function body text (for error msgs) */
95 
96  SQLFunctionParseInfoPtr pinfo; /* data for parser callback hooks */
97 
98  Oid rettype; /* actual return type */
99  int16 typlen; /* length of the return type */
100  bool typbyval; /* true if return type is pass by value */
101  bool returnsSet; /* true if returning multiple rows */
102  bool returnsTuple; /* true if returning whole tuple result */
103  bool shutdown_reg; /* true if registered shutdown callback */
104  bool readonly_func; /* true to run in "read only" mode */
105  bool lazyEval; /* true if using lazyEval for result query */
106 
107  ParamListInfo paramLI; /* Param list representing current args */
108 
109  Tuplestorestate *tstore; /* where we accumulate result tuples */
110 
111  JunkFilter *junkFilter; /* will be NULL if function returns VOID */
112 
113  /*
114  * func_state is a List of execution_state records, each of which is the
115  * first for its original parsetree, with any additional records chained
116  * to it via the "next" fields. This sublist structure is needed to keep
117  * track of where the original query boundaries are.
118  */
120 
121  MemoryContext fcontext; /* memory context holding this struct and all
122  * subsidiary data */
123 
124  LocalTransactionId lxid; /* lxid in which cache was made */
125  SubTransactionId subxid; /* subxid in which cache was made */
127 
129 
130 /*
131  * Data structure needed by the parser callback hooks to resolve parameter
132  * references during parsing of a SQL function's body. This is separate from
133  * SQLFunctionCache since we sometimes do parsing separately from execution.
134  */
135 typedef struct SQLFunctionParseInfo
136 {
137  char *fname; /* function's name */
138  int nargs; /* number of input arguments */
139  Oid *argtypes; /* resolved types of input arguments */
140  char **argnames; /* names of input arguments; NULL if none */
141  /* Note that argnames[i] can be NULL, if some args are unnamed */
142  Oid collation; /* function's input collation, if known */
144 
145 
146 /* non-export function prototypes */
147 static Node *sql_fn_param_ref(ParseState *pstate, ParamRef *pref);
148 static Node *sql_fn_post_column_ref(ParseState *pstate,
149  ColumnRef *cref, Node *var);
151  int paramno, int location);
153  const char *paramname, int location);
154 static List *init_execution_state(List *queryTree_list,
155  SQLFunctionCachePtr fcache,
156  bool lazyEvalOK);
157 static void init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK);
158 static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache);
159 static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache);
160 static void postquel_end(execution_state *es);
161 static void postquel_sub_params(SQLFunctionCachePtr fcache,
162  FunctionCallInfo fcinfo);
164  FunctionCallInfo fcinfo,
165  SQLFunctionCachePtr fcache,
166  MemoryContext resultcontext);
167 static void sql_exec_error_callback(void *arg);
168 static void ShutdownSQLFunction(Datum arg);
169 static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
170 static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self);
171 static void sqlfunction_shutdown(DestReceiver *self);
172 static void sqlfunction_destroy(DestReceiver *self);
173 
174 
175 /*
176  * Prepare the SQLFunctionParseInfo struct for parsing a SQL function body
177  *
178  * This includes resolving actual types of polymorphic arguments.
179  *
180  * call_expr can be passed as NULL, but then we will fail if there are any
181  * polymorphic arguments.
182  */
185  Node *call_expr,
186  Oid inputCollation)
187 {
189  Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
190  int nargs;
191 
193 
194  /* Function's name (only) can be used to qualify argument names */
195  pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
196 
197  /* Save the function's input collation */
198  pinfo->collation = inputCollation;
199 
200  /*
201  * Copy input argument types from the pg_proc entry, then resolve any
202  * polymorphic types.
203  */
204  pinfo->nargs = nargs = procedureStruct->pronargs;
205  if (nargs > 0)
206  {
207  Oid *argOidVect;
208  int argnum;
209 
210  argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
211  memcpy(argOidVect,
212  procedureStruct->proargtypes.values,
213  nargs * sizeof(Oid));
214 
215  for (argnum = 0; argnum < nargs; argnum++)
216  {
217  Oid argtype = argOidVect[argnum];
218 
219  if (IsPolymorphicType(argtype))
220  {
221  argtype = get_call_expr_argtype(call_expr, argnum);
222  if (argtype == InvalidOid)
223  ereport(ERROR,
224  (errcode(ERRCODE_DATATYPE_MISMATCH),
225  errmsg("could not determine actual type of argument declared %s",
226  format_type_be(argOidVect[argnum]))));
227  argOidVect[argnum] = argtype;
228  }
229  }
230 
231  pinfo->argtypes = argOidVect;
232  }
233 
234  /*
235  * Collect names of arguments, too, if any
236  */
237  if (nargs > 0)
238  {
239  Datum proargnames;
240  Datum proargmodes;
241  int n_arg_names;
242  bool isNull;
243 
244  proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
246  &isNull);
247  if (isNull)
248  proargnames = PointerGetDatum(NULL); /* just to be sure */
249 
250  proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
252  &isNull);
253  if (isNull)
254  proargmodes = PointerGetDatum(NULL); /* just to be sure */
255 
256  n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
257  &pinfo->argnames);
258 
259  /* Paranoia: ignore the result if too few array entries */
260  if (n_arg_names < nargs)
261  pinfo->argnames = NULL;
262  }
263  else
264  pinfo->argnames = NULL;
265 
266  return pinfo;
267 }
268 
269 /*
270  * Parser setup hook for parsing a SQL function body.
271  */
272 void
274 {
275  pstate->p_pre_columnref_hook = NULL;
278  /* no need to use p_coerce_param_hook */
279  pstate->p_ref_hook_state = (void *) pinfo;
280 }
281 
282 /*
283  * sql_fn_post_column_ref parser callback for ColumnRefs
284  */
285 static Node *
287 {
289  int nnames;
290  Node *field1;
291  Node *subfield = NULL;
292  const char *name1;
293  const char *name2 = NULL;
294  Node *param;
295 
296  /*
297  * Never override a table-column reference. This corresponds to
298  * considering the parameter names to appear in a scope outside the
299  * individual SQL commands, which is what we want.
300  */
301  if (var != NULL)
302  return NULL;
303 
304  /*----------
305  * The allowed syntaxes are:
306  *
307  * A A = parameter name
308  * A.B A = function name, B = parameter name
309  * OR: A = record-typed parameter name, B = field name
310  * (the first possibility takes precedence)
311  * A.B.C A = function name, B = record-typed parameter name,
312  * C = field name
313  * A.* Whole-row reference to composite parameter A.
314  * A.B.* Same, with A = function name, B = parameter name
315  *
316  * Here, it's sufficient to ignore the "*" in the last two cases --- the
317  * main parser will take care of expanding the whole-row reference.
318  *----------
319  */
320  nnames = list_length(cref->fields);
321 
322  if (nnames > 3)
323  return NULL;
324 
325  if (IsA(llast(cref->fields), A_Star))
326  nnames--;
327 
328  field1 = (Node *) linitial(cref->fields);
329  Assert(IsA(field1, String));
330  name1 = strVal(field1);
331  if (nnames > 1)
332  {
333  subfield = (Node *) lsecond(cref->fields);
334  Assert(IsA(subfield, String));
335  name2 = strVal(subfield);
336  }
337 
338  if (nnames == 3)
339  {
340  /*
341  * Three-part name: if the first part doesn't match the function name,
342  * we can fail immediately. Otherwise, look up the second part, and
343  * take the third part to be a field reference.
344  */
345  if (strcmp(name1, pinfo->fname) != 0)
346  return NULL;
347 
348  param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
349 
350  subfield = (Node *) lthird(cref->fields);
351  Assert(IsA(subfield, String));
352  }
353  else if (nnames == 2 && strcmp(name1, pinfo->fname) == 0)
354  {
355  /*
356  * Two-part name with first part matching function name: first see if
357  * second part matches any parameter name.
358  */
359  param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
360 
361  if (param)
362  {
363  /* Yes, so this is a parameter reference, no subfield */
364  subfield = NULL;
365  }
366  else
367  {
368  /* No, so try to match as parameter name and subfield */
369  param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
370  }
371  }
372  else
373  {
374  /* Single name, or parameter name followed by subfield */
375  param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
376  }
377 
378  if (!param)
379  return NULL; /* No match */
380 
381  if (subfield)
382  {
383  /*
384  * Must be a reference to a field of a composite parameter; otherwise
385  * ParseFuncOrColumn will return NULL, and we'll fail back at the
386  * caller.
387  */
388  param = ParseFuncOrColumn(pstate,
389  list_make1(subfield),
390  list_make1(param),
391  NULL,
392  cref->location);
393  }
394 
395  return param;
396 }
397 
398 /*
399  * sql_fn_param_ref parser callback for ParamRefs ($n symbols)
400  */
401 static Node *
403 {
405  int paramno = pref->number;
406 
407  /* Check parameter number is valid */
408  if (paramno <= 0 || paramno > pinfo->nargs)
409  return NULL; /* unknown parameter number */
410 
411  return sql_fn_make_param(pinfo, paramno, pref->location);
412 }
413 
414 /*
415  * sql_fn_make_param construct a Param node for the given paramno
416  */
417 static Node *
419  int paramno, int location)
420 {
421  Param *param;
422 
423  param = makeNode(Param);
424  param->paramkind = PARAM_EXTERN;
425  param->paramid = paramno;
426  param->paramtype = pinfo->argtypes[paramno - 1];
427  param->paramtypmod = -1;
428  param->paramcollid = get_typcollation(param->paramtype);
429  param->location = location;
430 
431  /*
432  * If we have a function input collation, allow it to override the
433  * type-derived collation for parameter symbols. (XXX perhaps this should
434  * not happen if the type collation is not default?)
435  */
436  if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
437  param->paramcollid = pinfo->collation;
438 
439  return (Node *) param;
440 }
441 
442 /*
443  * Search for a function parameter of the given name; if there is one,
444  * construct and return a Param node for it. If not, return NULL.
445  * Helper function for sql_fn_post_column_ref.
446  */
447 static Node *
449  const char *paramname, int location)
450 {
451  int i;
452 
453  if (pinfo->argnames == NULL)
454  return NULL;
455 
456  for (i = 0; i < pinfo->nargs; i++)
457  {
458  if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
459  return sql_fn_make_param(pinfo, i + 1, location);
460  }
461 
462  return NULL;
463 }
464 
465 /*
466  * Set up the per-query execution_state records for a SQL function.
467  *
468  * The input is a List of Lists of parsed and rewritten, but not planned,
469  * querytrees. The sublist structure denotes the original query boundaries.
470  */
471 static List *
472 init_execution_state(List *queryTree_list,
473  SQLFunctionCachePtr fcache,
474  bool lazyEvalOK)
475 {
476  List *eslist = NIL;
477  execution_state *lasttages = NULL;
478  ListCell *lc1;
479 
480  foreach(lc1, queryTree_list)
481  {
482  List *qtlist = lfirst_node(List, lc1);
483  execution_state *firstes = NULL;
484  execution_state *preves = NULL;
485  ListCell *lc2;
486 
487  foreach(lc2, qtlist)
488  {
489  Query *queryTree = lfirst_node(Query, lc2);
490  PlannedStmt *stmt;
491  execution_state *newes;
492 
493  /* Plan the query if needed */
494  if (queryTree->commandType == CMD_UTILITY)
495  {
496  /* Utility commands require no planning. */
497  stmt = makeNode(PlannedStmt);
498  stmt->commandType = CMD_UTILITY;
499  stmt->canSetTag = queryTree->canSetTag;
500  stmt->utilityStmt = queryTree->utilityStmt;
501  stmt->stmt_location = queryTree->stmt_location;
502  stmt->stmt_len = queryTree->stmt_len;
503  }
504  else
505  stmt = pg_plan_query(queryTree,
507  NULL);
508 
509  /*
510  * Precheck all commands for validity in a function. This should
511  * generally match the restrictions spi.c applies.
512  */
513  if (stmt->commandType == CMD_UTILITY)
514  {
515  if (IsA(stmt->utilityStmt, CopyStmt) &&
516  ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
517  ereport(ERROR,
518  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
519  errmsg("cannot COPY to/from client in a SQL function")));
520 
521  if (IsA(stmt->utilityStmt, TransactionStmt))
522  ereport(ERROR,
523  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
524  /* translator: %s is a SQL statement name */
525  errmsg("%s is not allowed in a SQL function",
526  CreateCommandTag(stmt->utilityStmt))));
527  }
528 
529  if (fcache->readonly_func && !CommandIsReadOnly(stmt))
530  ereport(ERROR,
531  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
532  /* translator: %s is a SQL statement name */
533  errmsg("%s is not allowed in a non-volatile function",
534  CreateCommandTag((Node *) stmt))));
535 
536  if (IsInParallelMode() && !CommandIsReadOnly(stmt))
538 
539  /* OK, build the execution_state for this query */
540  newes = (execution_state *) palloc(sizeof(execution_state));
541  if (preves)
542  preves->next = newes;
543  else
544  firstes = newes;
545 
546  newes->next = NULL;
547  newes->status = F_EXEC_START;
548  newes->setsResult = false; /* might change below */
549  newes->lazyEval = false; /* might change below */
550  newes->stmt = stmt;
551  newes->qd = NULL;
552 
553  if (queryTree->canSetTag)
554  lasttages = newes;
555 
556  preves = newes;
557  }
558 
559  eslist = lappend(eslist, firstes);
560  }
561 
562  /*
563  * Mark the last canSetTag query as delivering the function result; then,
564  * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
565  * SELECT we must always run it to completion.
566  *
567  * Note: at some point we might add additional criteria for whether to use
568  * lazy eval. However, we should prefer to use it whenever the function
569  * doesn't return set, since fetching more than one row is useless in that
570  * case.
571  *
572  * Note: don't set setsResult if the function returns VOID, as evidenced
573  * by not having made a junkfilter. This ensures we'll throw away any
574  * output from a utility statement that check_sql_fn_retval deemed to not
575  * have output.
576  */
577  if (lasttages && fcache->junkFilter)
578  {
579  lasttages->setsResult = true;
580  if (lazyEvalOK &&
581  lasttages->stmt->commandType == CMD_SELECT &&
582  !lasttages->stmt->hasModifyingCTE)
583  fcache->lazyEval = lasttages->lazyEval = true;
584  }
585 
586  return eslist;
587 }
588 
589 /*
590  * Initialize the SQLFunctionCache for a SQL function
591  */
592 static void
593 init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
594 {
595  Oid foid = finfo->fn_oid;
596  MemoryContext fcontext;
597  MemoryContext oldcontext;
598  Oid rettype;
599  HeapTuple procedureTuple;
600  Form_pg_proc procedureStruct;
601  SQLFunctionCachePtr fcache;
602  List *raw_parsetree_list;
603  List *queryTree_list;
604  List *flat_query_list;
605  ListCell *lc;
606  Datum tmp;
607  bool isNull;
608 
609  /*
610  * Create memory context that holds all the SQLFunctionCache data. It
611  * must be a child of whatever context holds the FmgrInfo.
612  */
613  fcontext = AllocSetContextCreate(finfo->fn_mcxt,
614  "SQL function data",
616 
617  oldcontext = MemoryContextSwitchTo(fcontext);
618 
619  /*
620  * Create the struct proper, link it to fcontext and fn_extra. Once this
621  * is done, we'll be able to recover the memory after failure, even if the
622  * FmgrInfo is long-lived.
623  */
624  fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
625  fcache->fcontext = fcontext;
626  finfo->fn_extra = (void *) fcache;
627 
628  /*
629  * get the procedure tuple corresponding to the given function Oid
630  */
631  procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
632  if (!HeapTupleIsValid(procedureTuple))
633  elog(ERROR, "cache lookup failed for function %u", foid);
634  procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
635 
636  /*
637  * copy function name immediately for use by error reporting callback
638  */
639  fcache->fname = pstrdup(NameStr(procedureStruct->proname));
640 
641  /*
642  * get the result type from the procedure tuple, and check for polymorphic
643  * result type; if so, find out the actual result type.
644  */
645  rettype = procedureStruct->prorettype;
646 
647  if (IsPolymorphicType(rettype))
648  {
649  rettype = get_fn_expr_rettype(finfo);
650  if (rettype == InvalidOid) /* this probably should not happen */
651  ereport(ERROR,
652  (errcode(ERRCODE_DATATYPE_MISMATCH),
653  errmsg("could not determine actual result type for function declared to return type %s",
654  format_type_be(procedureStruct->prorettype))));
655  }
656 
657  fcache->rettype = rettype;
658 
659  /* Fetch the typlen and byval info for the result type */
660  get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
661 
662  /* Remember whether we're returning setof something */
663  fcache->returnsSet = procedureStruct->proretset;
664 
665  /* Remember if function is STABLE/IMMUTABLE */
666  fcache->readonly_func =
667  (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
668 
669  /*
670  * We need the actual argument types to pass to the parser. Also make
671  * sure that parameter symbols are considered to have the function's
672  * resolved input collation.
673  */
674  fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
675  finfo->fn_expr,
676  collation);
677 
678  /*
679  * And of course we need the function body text.
680  */
681  tmp = SysCacheGetAttr(PROCOID,
682  procedureTuple,
684  &isNull);
685  if (isNull)
686  elog(ERROR, "null prosrc for function %u", foid);
687  fcache->src = TextDatumGetCString(tmp);
688 
689  /*
690  * Parse and rewrite the queries in the function text. Use sublists to
691  * keep track of the original query boundaries. But we also build a
692  * "flat" list of the rewritten queries to pass to check_sql_fn_retval.
693  * This is because the last canSetTag query determines the result type
694  * independently of query boundaries --- and it might not be in the last
695  * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
696  * (It might not be unreasonable to throw an error in such a case, but
697  * this is the historical behavior and it doesn't seem worth changing.)
698  *
699  * Note: since parsing and planning is done in fcontext, we will generate
700  * a lot of cruft that lives as long as the fcache does. This is annoying
701  * but we'll not worry about it until the module is rewritten to use
702  * plancache.c.
703  */
704  raw_parsetree_list = pg_parse_query(fcache->src);
705 
706  queryTree_list = NIL;
707  flat_query_list = NIL;
708  foreach(lc, raw_parsetree_list)
709  {
710  RawStmt *parsetree = lfirst_node(RawStmt, lc);
711  List *queryTree_sublist;
712 
713  queryTree_sublist = pg_analyze_and_rewrite_params(parsetree,
714  fcache->src,
716  fcache->pinfo,
717  NULL);
718  queryTree_list = lappend(queryTree_list, queryTree_sublist);
719  flat_query_list = list_concat(flat_query_list,
720  list_copy(queryTree_sublist));
721  }
722 
723  /*
724  * Check that the function returns the type it claims to. Although in
725  * simple cases this was already done when the function was defined, we
726  * have to recheck because database objects used in the function's queries
727  * might have changed type. We'd have to do it anyway if the function had
728  * any polymorphic arguments.
729  *
730  * Note: we set fcache->returnsTuple according to whether we are returning
731  * the whole tuple result or just a single column. In the latter case we
732  * clear returnsTuple because we need not act different from the scalar
733  * result case, even if it's a rowtype column. (However, we have to force
734  * lazy eval mode in that case; otherwise we'd need extra code to expand
735  * the rowtype column into multiple columns, since we have no way to
736  * notify the caller that it should do that.)
737  *
738  * check_sql_fn_retval will also construct a JunkFilter we can use to
739  * coerce the returned rowtype to the desired form (unless the result type
740  * is VOID, in which case there's nothing to coerce to).
741  */
742  fcache->returnsTuple = check_sql_fn_retval(foid,
743  rettype,
744  flat_query_list,
745  NULL,
746  &fcache->junkFilter);
747 
748  if (fcache->returnsTuple)
749  {
750  /* Make sure output rowtype is properly blessed */
752  }
753  else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
754  {
755  /*
756  * Returning rowtype as if it were scalar --- materialize won't work.
757  * Right now it's sufficient to override any caller preference for
758  * materialize mode, but to add more smarts in init_execution_state
759  * about this, we'd probably need a three-way flag instead of bool.
760  */
761  lazyEvalOK = true;
762  }
763 
764  /* Finally, plan the queries */
765  fcache->func_state = init_execution_state(queryTree_list,
766  fcache,
767  lazyEvalOK);
768 
769  /* Mark fcache with time of creation to show it's valid */
770  fcache->lxid = MyProc->lxid;
772 
773  ReleaseSysCache(procedureTuple);
774 
775  MemoryContextSwitchTo(oldcontext);
776 }
777 
778 /* Start up execution of one execution_state node */
779 static void
781 {
782  DestReceiver *dest;
783 
784  Assert(es->qd == NULL);
785 
786  /* Caller should have ensured a suitable snapshot is active */
788 
789  /*
790  * If this query produces the function result, send its output to the
791  * tuplestore; else discard any output.
792  */
793  if (es->setsResult)
794  {
795  DR_sqlfunction *myState;
796 
798  /* pass down the needed info to the dest receiver routines */
799  myState = (DR_sqlfunction *) dest;
800  Assert(myState->pub.mydest == DestSQLFunction);
801  myState->tstore = fcache->tstore;
802  myState->cxt = CurrentMemoryContext;
803  myState->filter = fcache->junkFilter;
804  }
805  else
806  dest = None_Receiver;
807 
808  es->qd = CreateQueryDesc(es->stmt,
809  fcache->src,
812  dest,
813  fcache->paramLI,
814  es->qd ? es->qd->queryEnv : NULL,
815  0);
816 
817  /* Utility commands don't need Executor. */
818  if (es->qd->operation != CMD_UTILITY)
819  {
820  /*
821  * In lazyEval mode, do not let the executor set up an AfterTrigger
822  * context. This is necessary not just an optimization, because we
823  * mustn't exit from the function execution with a stacked
824  * AfterTrigger level still active. We are careful not to select
825  * lazyEval mode for any statement that could possibly queue triggers.
826  */
827  int eflags;
828 
829  if (es->lazyEval)
830  eflags = EXEC_FLAG_SKIP_TRIGGERS;
831  else
832  eflags = 0; /* default run-to-completion flags */
833  ExecutorStart(es->qd, eflags);
834  }
835 
836  es->status = F_EXEC_RUN;
837 }
838 
839 /* Run one execution_state; either to completion or to first result row */
840 /* Returns true if we ran to completion */
841 static bool
843 {
844  bool result;
845 
846  if (es->qd->operation == CMD_UTILITY)
847  {
849  fcache->src,
851  es->qd->params,
852  es->qd->queryEnv,
853  es->qd->dest,
854  NULL);
855  result = true; /* never stops early */
856  }
857  else
858  {
859  /* Run regular commands to completion unless lazyEval */
860  uint64 count = (es->lazyEval) ? 1 : 0;
861 
862  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
863 
864  /*
865  * If we requested run to completion OR there was no tuple returned,
866  * command must be complete.
867  */
868  result = (count == 0 || es->qd->estate->es_processed == 0);
869  }
870 
871  return result;
872 }
873 
874 /* Shut down execution of one execution_state node */
875 static void
877 {
878  /* mark status done to ensure we don't do ExecutorEnd twice */
879  es->status = F_EXEC_DONE;
880 
881  /* Utility commands don't need Executor. */
882  if (es->qd->operation != CMD_UTILITY)
883  {
884  ExecutorFinish(es->qd);
885  ExecutorEnd(es->qd);
886  }
887 
888  (*es->qd->dest->rDestroy) (es->qd->dest);
889 
890  FreeQueryDesc(es->qd);
891  es->qd = NULL;
892 }
893 
894 /* Build ParamListInfo array representing current arguments */
895 static void
897  FunctionCallInfo fcinfo)
898 {
899  int nargs = fcinfo->nargs;
900 
901  if (nargs > 0)
902  {
903  ParamListInfo paramLI;
904  int i;
905 
906  if (fcache->paramLI == NULL)
907  {
908  paramLI = (ParamListInfo)
910  nargs * sizeof(ParamExternData));
911  /* we have static list of params, so no hooks needed */
912  paramLI->paramFetch = NULL;
913  paramLI->paramFetchArg = NULL;
914  paramLI->parserSetup = NULL;
915  paramLI->parserSetupArg = NULL;
916  paramLI->numParams = nargs;
917  paramLI->paramMask = NULL;
918  fcache->paramLI = paramLI;
919  }
920  else
921  {
922  paramLI = fcache->paramLI;
923  Assert(paramLI->numParams == nargs);
924  }
925 
926  for (i = 0; i < nargs; i++)
927  {
928  ParamExternData *prm = &paramLI->params[i];
929 
930  prm->value = fcinfo->arg[i];
931  prm->isnull = fcinfo->argnull[i];
932  prm->pflags = 0;
933  prm->ptype = fcache->pinfo->argtypes[i];
934  }
935  }
936  else
937  fcache->paramLI = NULL;
938 }
939 
940 /*
941  * Extract the SQL function's value from a single result row. This is used
942  * both for scalar (non-set) functions and for each row of a lazy-eval set
943  * result.
944  */
945 static Datum
947  FunctionCallInfo fcinfo,
948  SQLFunctionCachePtr fcache,
949  MemoryContext resultcontext)
950 {
951  Datum value;
952  MemoryContext oldcontext;
953 
954  /*
955  * Set up to return the function value. For pass-by-reference datatypes,
956  * be sure to allocate the result in resultcontext, not the current memory
957  * context (which has query lifespan). We can't leave the data in the
958  * TupleTableSlot because we intend to clear the slot before returning.
959  */
960  oldcontext = MemoryContextSwitchTo(resultcontext);
961 
962  if (fcache->returnsTuple)
963  {
964  /* We must return the whole tuple as a Datum. */
965  fcinfo->isnull = false;
966  value = ExecFetchSlotTupleDatum(slot);
967  }
968  else
969  {
970  /*
971  * Returning a scalar, which we have to extract from the first column
972  * of the SELECT result, and then copy into result context if needed.
973  */
974  value = slot_getattr(slot, 1, &(fcinfo->isnull));
975 
976  if (!fcinfo->isnull)
977  value = datumCopy(value, fcache->typbyval, fcache->typlen);
978  }
979 
980  MemoryContextSwitchTo(oldcontext);
981 
982  return value;
983 }
984 
985 /*
986  * fmgr_sql: function call manager for SQL functions
987  */
988 Datum
990 {
991  SQLFunctionCachePtr fcache;
992  ErrorContextCallback sqlerrcontext;
993  MemoryContext oldcontext;
994  bool randomAccess;
995  bool lazyEvalOK;
996  bool is_first;
997  bool pushed_snapshot;
998  execution_state *es;
999  TupleTableSlot *slot;
1000  Datum result;
1001  List *eslist;
1002  ListCell *eslc;
1003 
1004  /*
1005  * Setup error traceback support for ereport()
1006  */
1007  sqlerrcontext.callback = sql_exec_error_callback;
1008  sqlerrcontext.arg = fcinfo->flinfo;
1009  sqlerrcontext.previous = error_context_stack;
1010  error_context_stack = &sqlerrcontext;
1011 
1012  /* Check call context */
1013  if (fcinfo->flinfo->fn_retset)
1014  {
1015  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1016 
1017  /*
1018  * For simplicity, we require callers to support both set eval modes.
1019  * There are cases where we must use one or must use the other, and
1020  * it's not really worthwhile to postpone the check till we know. But
1021  * note we do not require caller to provide an expectedDesc.
1022  */
1023  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1024  (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1025  (rsi->allowedModes & SFRM_Materialize) == 0)
1026  ereport(ERROR,
1027  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1028  errmsg("set-valued function called in context that cannot accept a set")));
1029  randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1030  lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1031  }
1032  else
1033  {
1034  randomAccess = false;
1035  lazyEvalOK = true;
1036  }
1037 
1038  /*
1039  * Initialize fcache (build plans) if first time through; or re-initialize
1040  * if the cache is stale.
1041  */
1042  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1043 
1044  if (fcache != NULL)
1045  {
1046  if (fcache->lxid != MyProc->lxid ||
1047  !SubTransactionIsActive(fcache->subxid))
1048  {
1049  /* It's stale; unlink and delete */
1050  fcinfo->flinfo->fn_extra = NULL;
1051  MemoryContextDelete(fcache->fcontext);
1052  fcache = NULL;
1053  }
1054  }
1055 
1056  if (fcache == NULL)
1057  {
1058  init_sql_fcache(fcinfo->flinfo, PG_GET_COLLATION(), lazyEvalOK);
1059  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1060  }
1061 
1062  /*
1063  * Switch to context in which the fcache lives. This ensures that our
1064  * tuplestore etc will have sufficient lifetime. The sub-executor is
1065  * responsible for deleting per-tuple information. (XXX in the case of a
1066  * long-lived FmgrInfo, this policy represents more memory leakage, but
1067  * it's not entirely clear where to keep stuff instead.)
1068  */
1069  oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1070 
1071  /*
1072  * Find first unfinished query in function, and note whether it's the
1073  * first query.
1074  */
1075  eslist = fcache->func_state;
1076  es = NULL;
1077  is_first = true;
1078  foreach(eslc, eslist)
1079  {
1080  es = (execution_state *) lfirst(eslc);
1081 
1082  while (es && es->status == F_EXEC_DONE)
1083  {
1084  is_first = false;
1085  es = es->next;
1086  }
1087 
1088  if (es)
1089  break;
1090  }
1091 
1092  /*
1093  * Convert params to appropriate format if starting a fresh execution. (If
1094  * continuing execution, we can re-use prior params.)
1095  */
1096  if (is_first && es && es->status == F_EXEC_START)
1097  postquel_sub_params(fcache, fcinfo);
1098 
1099  /*
1100  * Build tuplestore to hold results, if we don't have one already. Note
1101  * it's in the query-lifespan context.
1102  */
1103  if (!fcache->tstore)
1104  fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1105 
1106  /*
1107  * Execute each command in the function one after another until we either
1108  * run out of commands or get a result row from a lazily-evaluated SELECT.
1109  *
1110  * Notes about snapshot management:
1111  *
1112  * In a read-only function, we just use the surrounding query's snapshot.
1113  *
1114  * In a non-read-only function, we rely on the fact that we'll never
1115  * suspend execution between queries of the function: the only reason to
1116  * suspend execution before completion is if we are returning a row from a
1117  * lazily-evaluated SELECT. So, when first entering this loop, we'll
1118  * either start a new query (and push a fresh snapshot) or re-establish
1119  * the active snapshot from the existing query descriptor. If we need to
1120  * start a new query in a subsequent execution of the loop, either we need
1121  * a fresh snapshot (and pushed_snapshot is false) or the existing
1122  * snapshot is on the active stack and we can just bump its command ID.
1123  */
1124  pushed_snapshot = false;
1125  while (es)
1126  {
1127  bool completed;
1128 
1129  if (es->status == F_EXEC_START)
1130  {
1131  /*
1132  * If not read-only, be sure to advance the command counter for
1133  * each command, so that all work to date in this transaction is
1134  * visible. Take a new snapshot if we don't have one yet,
1135  * otherwise just bump the command ID in the existing snapshot.
1136  */
1137  if (!fcache->readonly_func)
1138  {
1140  if (!pushed_snapshot)
1141  {
1143  pushed_snapshot = true;
1144  }
1145  else
1147  }
1148 
1149  postquel_start(es, fcache);
1150  }
1151  else if (!fcache->readonly_func && !pushed_snapshot)
1152  {
1153  /* Re-establish active snapshot when re-entering function */
1155  pushed_snapshot = true;
1156  }
1157 
1158  completed = postquel_getnext(es, fcache);
1159 
1160  /*
1161  * If we ran the command to completion, we can shut it down now. Any
1162  * row(s) we need to return are safely stashed in the tuplestore, and
1163  * we want to be sure that, for example, AFTER triggers get fired
1164  * before we return anything. Also, if the function doesn't return
1165  * set, we can shut it down anyway because it must be a SELECT and we
1166  * don't care about fetching any more result rows.
1167  */
1168  if (completed || !fcache->returnsSet)
1169  postquel_end(es);
1170 
1171  /*
1172  * Break from loop if we didn't shut down (implying we got a
1173  * lazily-evaluated row). Otherwise we'll press on till the whole
1174  * function is done, relying on the tuplestore to keep hold of the
1175  * data to eventually be returned. This is necessary since an
1176  * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1177  * followed by additional rule-inserted commands, and we want to
1178  * finish doing all those commands before we return anything.
1179  */
1180  if (es->status != F_EXEC_DONE)
1181  break;
1182 
1183  /*
1184  * Advance to next execution_state, which might be in the next list.
1185  */
1186  es = es->next;
1187  while (!es)
1188  {
1189  eslc = lnext(eslc);
1190  if (!eslc)
1191  break; /* end of function */
1192 
1193  es = (execution_state *) lfirst(eslc);
1194 
1195  /*
1196  * Flush the current snapshot so that we will take a new one for
1197  * the new query list. This ensures that new snaps are taken at
1198  * original-query boundaries, matching the behavior of interactive
1199  * execution.
1200  */
1201  if (pushed_snapshot)
1202  {
1204  pushed_snapshot = false;
1205  }
1206  }
1207  }
1208 
1209  /*
1210  * The tuplestore now contains whatever row(s) we are supposed to return.
1211  */
1212  if (fcache->returnsSet)
1213  {
1214  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1215 
1216  if (es)
1217  {
1218  /*
1219  * If we stopped short of being done, we must have a lazy-eval
1220  * row.
1221  */
1222  Assert(es->lazyEval);
1223  /* Re-use the junkfilter's output slot to fetch back the tuple */
1224  Assert(fcache->junkFilter);
1225  slot = fcache->junkFilter->jf_resultSlot;
1226  if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1227  elog(ERROR, "failed to fetch lazy-eval tuple");
1228  /* Extract the result as a datum, and copy out from the slot */
1229  result = postquel_get_single_result(slot, fcinfo,
1230  fcache, oldcontext);
1231  /* Clear the tuplestore, but keep it for next time */
1232  /* NB: this might delete the slot's content, but we don't care */
1233  tuplestore_clear(fcache->tstore);
1234 
1235  /*
1236  * Let caller know we're not finished.
1237  */
1238  rsi->isDone = ExprMultipleResult;
1239 
1240  /*
1241  * Ensure we will get shut down cleanly if the exprcontext is not
1242  * run to completion.
1243  */
1244  if (!fcache->shutdown_reg)
1245  {
1248  PointerGetDatum(fcache));
1249  fcache->shutdown_reg = true;
1250  }
1251  }
1252  else if (fcache->lazyEval)
1253  {
1254  /*
1255  * We are done with a lazy evaluation. Clean up.
1256  */
1257  tuplestore_clear(fcache->tstore);
1258 
1259  /*
1260  * Let caller know we're finished.
1261  */
1262  rsi->isDone = ExprEndResult;
1263 
1264  fcinfo->isnull = true;
1265  result = (Datum) 0;
1266 
1267  /* Deregister shutdown callback, if we made one */
1268  if (fcache->shutdown_reg)
1269  {
1272  PointerGetDatum(fcache));
1273  fcache->shutdown_reg = false;
1274  }
1275  }
1276  else
1277  {
1278  /*
1279  * We are done with a non-lazy evaluation. Return whatever is in
1280  * the tuplestore. (It is now caller's responsibility to free the
1281  * tuplestore when done.)
1282  */
1284  rsi->setResult = fcache->tstore;
1285  fcache->tstore = NULL;
1286  /* must copy desc because execSRF.c will free it */
1287  if (fcache->junkFilter)
1289 
1290  fcinfo->isnull = true;
1291  result = (Datum) 0;
1292 
1293  /* Deregister shutdown callback, if we made one */
1294  if (fcache->shutdown_reg)
1295  {
1298  PointerGetDatum(fcache));
1299  fcache->shutdown_reg = false;
1300  }
1301  }
1302  }
1303  else
1304  {
1305  /*
1306  * Non-set function. If we got a row, return it; else return NULL.
1307  */
1308  if (fcache->junkFilter)
1309  {
1310  /* Re-use the junkfilter's output slot to fetch back the tuple */
1311  slot = fcache->junkFilter->jf_resultSlot;
1312  if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1313  result = postquel_get_single_result(slot, fcinfo,
1314  fcache, oldcontext);
1315  else
1316  {
1317  fcinfo->isnull = true;
1318  result = (Datum) 0;
1319  }
1320  }
1321  else
1322  {
1323  /* Should only get here for VOID functions */
1324  Assert(fcache->rettype == VOIDOID);
1325  fcinfo->isnull = true;
1326  result = (Datum) 0;
1327  }
1328 
1329  /* Clear the tuplestore, but keep it for next time */
1330  tuplestore_clear(fcache->tstore);
1331  }
1332 
1333  /* Pop snapshot if we have pushed one */
1334  if (pushed_snapshot)
1336 
1337  /*
1338  * If we've gone through every command in the function, we are done. Reset
1339  * the execution states to start over again on next call.
1340  */
1341  if (es == NULL)
1342  {
1343  foreach(eslc, fcache->func_state)
1344  {
1345  es = (execution_state *) lfirst(eslc);
1346  while (es)
1347  {
1348  es->status = F_EXEC_START;
1349  es = es->next;
1350  }
1351  }
1352  }
1353 
1354  error_context_stack = sqlerrcontext.previous;
1355 
1356  MemoryContextSwitchTo(oldcontext);
1357 
1358  return result;
1359 }
1360 
1361 
1362 /*
1363  * error context callback to let us supply a call-stack traceback
1364  */
1365 static void
1367 {
1368  FmgrInfo *flinfo = (FmgrInfo *) arg;
1370  int syntaxerrposition;
1371 
1372  /*
1373  * We can do nothing useful if init_sql_fcache() didn't get as far as
1374  * saving the function name
1375  */
1376  if (fcache == NULL || fcache->fname == NULL)
1377  return;
1378 
1379  /*
1380  * If there is a syntax error position, convert to internal syntax error
1381  */
1382  syntaxerrposition = geterrposition();
1383  if (syntaxerrposition > 0 && fcache->src != NULL)
1384  {
1385  errposition(0);
1386  internalerrposition(syntaxerrposition);
1387  internalerrquery(fcache->src);
1388  }
1389 
1390  /*
1391  * Try to determine where in the function we failed. If there is a query
1392  * with non-null QueryDesc, finger it. (We check this rather than looking
1393  * for F_EXEC_RUN state, so that errors during ExecutorStart or
1394  * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1395  * postquel_end.)
1396  */
1397  if (fcache->func_state)
1398  {
1399  execution_state *es;
1400  int query_num;
1401  ListCell *lc;
1402 
1403  es = NULL;
1404  query_num = 1;
1405  foreach(lc, fcache->func_state)
1406  {
1407  es = (execution_state *) lfirst(lc);
1408  while (es)
1409  {
1410  if (es->qd)
1411  {
1412  errcontext("SQL function \"%s\" statement %d",
1413  fcache->fname, query_num);
1414  break;
1415  }
1416  es = es->next;
1417  }
1418  if (es)
1419  break;
1420  query_num++;
1421  }
1422  if (es == NULL)
1423  {
1424  /*
1425  * couldn't identify a running query; might be function entry,
1426  * function exit, or between queries.
1427  */
1428  errcontext("SQL function \"%s\"", fcache->fname);
1429  }
1430  }
1431  else
1432  {
1433  /*
1434  * Assume we failed during init_sql_fcache(). (It's possible that the
1435  * function actually has an empty body, but in that case we may as
1436  * well report all errors as being "during startup".)
1437  */
1438  errcontext("SQL function \"%s\" during startup", fcache->fname);
1439  }
1440 }
1441 
1442 
1443 /*
1444  * callback function in case a function-returning-set needs to be shut down
1445  * before it has been run to completion
1446  */
1447 static void
1449 {
1451  execution_state *es;
1452  ListCell *lc;
1453 
1454  foreach(lc, fcache->func_state)
1455  {
1456  es = (execution_state *) lfirst(lc);
1457  while (es)
1458  {
1459  /* Shut down anything still running */
1460  if (es->status == F_EXEC_RUN)
1461  {
1462  /* Re-establish active snapshot for any called functions */
1463  if (!fcache->readonly_func)
1465 
1466  postquel_end(es);
1467 
1468  if (!fcache->readonly_func)
1470  }
1471 
1472  /* Reset states to START in case we're called again */
1473  es->status = F_EXEC_START;
1474  es = es->next;
1475  }
1476  }
1477 
1478  /* Release tuplestore if we have one */
1479  if (fcache->tstore)
1480  tuplestore_end(fcache->tstore);
1481  fcache->tstore = NULL;
1482 
1483  /* execUtils will deregister the callback... */
1484  fcache->shutdown_reg = false;
1485 }
1486 
1487 
1488 /*
1489  * check_sql_fn_retval() -- check return value of a list of sql parse trees.
1490  *
1491  * The return value of a sql function is the value returned by the last
1492  * canSetTag query in the function. We do some ad-hoc type checking here
1493  * to be sure that the user is returning the type he claims. There are
1494  * also a couple of strange-looking features to assist callers in dealing
1495  * with allowed special cases, such as binary-compatible result types.
1496  *
1497  * For a polymorphic function the passed rettype must be the actual resolved
1498  * output type of the function; we should never see a polymorphic pseudotype
1499  * such as ANYELEMENT as rettype. (This means we can't check the type during
1500  * function definition of a polymorphic function.)
1501  *
1502  * This function returns true if the sql function returns the entire tuple
1503  * result of its final statement, or false if it returns just the first column
1504  * result of that statement. It throws an error if the final statement doesn't
1505  * return the right type at all.
1506  *
1507  * Note that because we allow "SELECT rowtype_expression", the result can be
1508  * false even when the declared function return type is a rowtype.
1509  *
1510  * If modifyTargetList isn't NULL, the function will modify the final
1511  * statement's targetlist in two cases:
1512  * (1) if the tlist returns values that are binary-coercible to the expected
1513  * type rather than being exactly the expected type. RelabelType nodes will
1514  * be inserted to make the result types match exactly.
1515  * (2) if there are dropped columns in the declared result rowtype. NULL
1516  * output columns will be inserted in the tlist to match them.
1517  * (Obviously the caller must pass a parsetree that is okay to modify when
1518  * using this flag.) Note that this flag does not affect whether the tlist is
1519  * considered to be a legal match to the result type, only how we react to
1520  * allowed not-exact-match cases. *modifyTargetList will be set true iff
1521  * we had to make any "dangerous" changes that could modify the semantics of
1522  * the statement. If it is set true, the caller should not use the modified
1523  * statement, but for simplicity we apply the changes anyway.
1524  *
1525  * If junkFilter isn't NULL, then *junkFilter is set to a JunkFilter defined
1526  * to convert the function's tuple result to the correct output tuple type.
1527  * Exception: if the function is defined to return VOID then *junkFilter is
1528  * set to NULL.
1529  */
1530 bool
1531 check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
1532  bool *modifyTargetList,
1533  JunkFilter **junkFilter)
1534 {
1535  Query *parse;
1536  List **tlist_ptr;
1537  List *tlist;
1538  int tlistlen;
1539  char fn_typtype;
1540  Oid restype;
1541  ListCell *lc;
1542 
1543  AssertArg(!IsPolymorphicType(rettype));
1544 
1545  if (modifyTargetList)
1546  *modifyTargetList = false; /* initialize for no change */
1547  if (junkFilter)
1548  *junkFilter = NULL; /* initialize in case of VOID result */
1549 
1550  /*
1551  * Find the last canSetTag query in the list. This isn't necessarily the
1552  * last parsetree, because rule rewriting can insert queries after what
1553  * the user wrote.
1554  */
1555  parse = NULL;
1556  foreach(lc, queryTreeList)
1557  {
1558  Query *q = lfirst_node(Query, lc);
1559 
1560  if (q->canSetTag)
1561  parse = q;
1562  }
1563 
1564  /*
1565  * If it's a plain SELECT, it returns whatever the targetlist says.
1566  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1567  * that. Otherwise, the function return type must be VOID.
1568  *
1569  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1570  * a more general method of determining the output type, though. Also, it
1571  * seems too dangerous to consider FETCH or EXECUTE as returning a
1572  * determinable rowtype, since they depend on relatively short-lived
1573  * entities.
1574  */
1575  if (parse &&
1576  parse->commandType == CMD_SELECT)
1577  {
1578  tlist_ptr = &parse->targetList;
1579  tlist = parse->targetList;
1580  }
1581  else if (parse &&
1582  (parse->commandType == CMD_INSERT ||
1583  parse->commandType == CMD_UPDATE ||
1584  parse->commandType == CMD_DELETE) &&
1585  parse->returningList)
1586  {
1587  tlist_ptr = &parse->returningList;
1588  tlist = parse->returningList;
1589  }
1590  else
1591  {
1592  /* Empty function body, or last statement is a utility command */
1593  if (rettype != VOIDOID)
1594  ereport(ERROR,
1595  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1596  errmsg("return type mismatch in function declared to return %s",
1597  format_type_be(rettype)),
1598  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1599  return false;
1600  }
1601 
1602  /*
1603  * OK, check that the targetlist returns something matching the declared
1604  * type. (We used to insist that the declared type not be VOID in this
1605  * case, but that makes it hard to write a void function that exits after
1606  * calling another void function. Instead, we insist that the tlist
1607  * return void ... so void is treated as if it were a scalar type below.)
1608  */
1609 
1610  /*
1611  * Count the non-junk entries in the result targetlist.
1612  */
1613  tlistlen = ExecCleanTargetListLength(tlist);
1614 
1615  fn_typtype = get_typtype(rettype);
1616 
1617  if (fn_typtype == TYPTYPE_BASE ||
1618  fn_typtype == TYPTYPE_DOMAIN ||
1619  fn_typtype == TYPTYPE_ENUM ||
1620  fn_typtype == TYPTYPE_RANGE ||
1621  rettype == VOIDOID)
1622  {
1623  /*
1624  * For scalar-type returns, the target list must have exactly one
1625  * non-junk entry, and its type must agree with what the user
1626  * declared; except we allow binary-compatible types too.
1627  */
1628  TargetEntry *tle;
1629 
1630  if (tlistlen != 1)
1631  ereport(ERROR,
1632  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1633  errmsg("return type mismatch in function declared to return %s",
1634  format_type_be(rettype)),
1635  errdetail("Final statement must return exactly one column.")));
1636 
1637  /* We assume here that non-junk TLEs must come first in tlists */
1638  tle = (TargetEntry *) linitial(tlist);
1639  Assert(!tle->resjunk);
1640 
1641  restype = exprType((Node *) tle->expr);
1642  if (!IsBinaryCoercible(restype, rettype))
1643  ereport(ERROR,
1644  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1645  errmsg("return type mismatch in function declared to return %s",
1646  format_type_be(rettype)),
1647  errdetail("Actual return type is %s.",
1648  format_type_be(restype))));
1649  if (modifyTargetList && restype != rettype)
1650  {
1651  tle->expr = (Expr *) makeRelabelType(tle->expr,
1652  rettype,
1653  -1,
1654  get_typcollation(rettype),
1656  /* Relabel is dangerous if TLE is a sort/group or setop column */
1657  if (tle->ressortgroupref != 0 || parse->setOperations)
1658  *modifyTargetList = true;
1659  }
1660 
1661  /* Set up junk filter if needed */
1662  if (junkFilter)
1663  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1664  }
1665  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1666  {
1667  /* Returns a rowtype */
1668  TupleDesc tupdesc;
1669  int tupnatts; /* physical number of columns in tuple */
1670  int tuplogcols; /* # of nondeleted columns in tuple */
1671  int colindex; /* physical column index */
1672  List *newtlist; /* new non-junk tlist entries */
1673  List *junkattrs; /* new junk tlist entries */
1674 
1675  /*
1676  * If the target list is of length 1, and the type of the varnode in
1677  * the target list matches the declared return type, this is okay.
1678  * This can happen, for example, where the body of the function is
1679  * 'SELECT func2()', where func2 has the same composite return type as
1680  * the function that's calling it.
1681  *
1682  * XXX Note that if rettype is RECORD, the IsBinaryCoercible check
1683  * will succeed for any composite restype. For the moment we rely on
1684  * runtime type checking to catch any discrepancy, but it'd be nice to
1685  * do better at parse time.
1686  */
1687  if (tlistlen == 1)
1688  {
1689  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1690 
1691  Assert(!tle->resjunk);
1692  restype = exprType((Node *) tle->expr);
1693  if (IsBinaryCoercible(restype, rettype))
1694  {
1695  if (modifyTargetList && restype != rettype)
1696  {
1697  tle->expr = (Expr *) makeRelabelType(tle->expr,
1698  rettype,
1699  -1,
1700  get_typcollation(rettype),
1702  /* Relabel is dangerous if sort/group or setop column */
1703  if (tle->ressortgroupref != 0 || parse->setOperations)
1704  *modifyTargetList = true;
1705  }
1706  /* Set up junk filter if needed */
1707  if (junkFilter)
1708  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1709  return false; /* NOT returning whole tuple */
1710  }
1711  }
1712 
1713  /* Is the rowtype fixed, or determined only at runtime? */
1714  if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1715  {
1716  /*
1717  * Assume we are returning the whole tuple. Crosschecking against
1718  * what the caller expects will happen at runtime.
1719  */
1720  if (junkFilter)
1721  *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1722  return true;
1723  }
1724  Assert(tupdesc);
1725 
1726  /*
1727  * Verify that the targetlist matches the return tuple type. We scan
1728  * the non-deleted attributes to ensure that they match the datatypes
1729  * of the non-resjunk columns. For deleted attributes, insert NULL
1730  * result columns if the caller asked for that.
1731  */
1732  tupnatts = tupdesc->natts;
1733  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1734  colindex = 0;
1735  newtlist = NIL; /* these are only used if modifyTargetList */
1736  junkattrs = NIL;
1737 
1738  foreach(lc, tlist)
1739  {
1740  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1741  Form_pg_attribute attr;
1742  Oid tletype;
1743  Oid atttype;
1744 
1745  if (tle->resjunk)
1746  {
1747  if (modifyTargetList)
1748  junkattrs = lappend(junkattrs, tle);
1749  continue;
1750  }
1751 
1752  do
1753  {
1754  colindex++;
1755  if (colindex > tupnatts)
1756  ereport(ERROR,
1757  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1758  errmsg("return type mismatch in function declared to return %s",
1759  format_type_be(rettype)),
1760  errdetail("Final statement returns too many columns.")));
1761  attr = tupdesc->attrs[colindex - 1];
1762  if (attr->attisdropped && modifyTargetList)
1763  {
1764  Expr *null_expr;
1765 
1766  /* The type of the null we insert isn't important */
1767  null_expr = (Expr *) makeConst(INT4OID,
1768  -1,
1769  InvalidOid,
1770  sizeof(int32),
1771  (Datum) 0,
1772  true, /* isnull */
1773  true /* byval */ );
1774  newtlist = lappend(newtlist,
1775  makeTargetEntry(null_expr,
1776  colindex,
1777  NULL,
1778  false));
1779  /* NULL insertion is dangerous in a setop */
1780  if (parse->setOperations)
1781  *modifyTargetList = true;
1782  }
1783  } while (attr->attisdropped);
1784  tuplogcols++;
1785 
1786  tletype = exprType((Node *) tle->expr);
1787  atttype = attr->atttypid;
1788  if (!IsBinaryCoercible(tletype, atttype))
1789  ereport(ERROR,
1790  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1791  errmsg("return type mismatch in function declared to return %s",
1792  format_type_be(rettype)),
1793  errdetail("Final statement returns %s instead of %s at column %d.",
1794  format_type_be(tletype),
1795  format_type_be(atttype),
1796  tuplogcols)));
1797  if (modifyTargetList)
1798  {
1799  if (tletype != atttype)
1800  {
1801  tle->expr = (Expr *) makeRelabelType(tle->expr,
1802  atttype,
1803  -1,
1804  get_typcollation(atttype),
1806  /* Relabel is dangerous if sort/group or setop column */
1807  if (tle->ressortgroupref != 0 || parse->setOperations)
1808  *modifyTargetList = true;
1809  }
1810  tle->resno = colindex;
1811  newtlist = lappend(newtlist, tle);
1812  }
1813  }
1814 
1815  /* remaining columns in tupdesc had better all be dropped */
1816  for (colindex++; colindex <= tupnatts; colindex++)
1817  {
1818  if (!tupdesc->attrs[colindex - 1]->attisdropped)
1819  ereport(ERROR,
1820  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1821  errmsg("return type mismatch in function declared to return %s",
1822  format_type_be(rettype)),
1823  errdetail("Final statement returns too few columns.")));
1824  if (modifyTargetList)
1825  {
1826  Expr *null_expr;
1827 
1828  /* The type of the null we insert isn't important */
1829  null_expr = (Expr *) makeConst(INT4OID,
1830  -1,
1831  InvalidOid,
1832  sizeof(int32),
1833  (Datum) 0,
1834  true, /* isnull */
1835  true /* byval */ );
1836  newtlist = lappend(newtlist,
1837  makeTargetEntry(null_expr,
1838  colindex,
1839  NULL,
1840  false));
1841  /* NULL insertion is dangerous in a setop */
1842  if (parse->setOperations)
1843  *modifyTargetList = true;
1844  }
1845  }
1846 
1847  if (modifyTargetList)
1848  {
1849  /* ensure resjunk columns are numbered correctly */
1850  foreach(lc, junkattrs)
1851  {
1852  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1853 
1854  tle->resno = colindex++;
1855  }
1856  /* replace the tlist with the modified one */
1857  *tlist_ptr = list_concat(newtlist, junkattrs);
1858  }
1859 
1860  /* Set up junk filter if needed */
1861  if (junkFilter)
1862  *junkFilter = ExecInitJunkFilterConversion(tlist,
1863  CreateTupleDescCopy(tupdesc),
1864  NULL);
1865 
1866  /* Report that we are returning entire tuple result */
1867  return true;
1868  }
1869  else
1870  ereport(ERROR,
1871  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1872  errmsg("return type %s is not supported for SQL functions",
1873  format_type_be(rettype))));
1874 
1875  return false;
1876 }
1877 
1878 
1879 /*
1880  * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
1881  */
1882 DestReceiver *
1884 {
1885  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1886 
1887  self->pub.receiveSlot = sqlfunction_receive;
1888  self->pub.rStartup = sqlfunction_startup;
1889  self->pub.rShutdown = sqlfunction_shutdown;
1890  self->pub.rDestroy = sqlfunction_destroy;
1891  self->pub.mydest = DestSQLFunction;
1892 
1893  /* private fields will be set by postquel_start */
1894 
1895  return (DestReceiver *) self;
1896 }
1897 
1898 /*
1899  * sqlfunction_startup --- executor startup
1900  */
1901 static void
1902 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1903 {
1904  /* no-op */
1905 }
1906 
1907 /*
1908  * sqlfunction_receive --- receive one tuple
1909  */
1910 static bool
1912 {
1913  DR_sqlfunction *myState = (DR_sqlfunction *) self;
1914 
1915  /* Filter tuple as needed */
1916  slot = ExecFilterJunk(myState->filter, slot);
1917 
1918  /* Store the filtered tuple into the tuplestore */
1919  tuplestore_puttupleslot(myState->tstore, slot);
1920 
1921  return true;
1922 }
1923 
1924 /*
1925  * sqlfunction_shutdown --- executor end
1926  */
1927 static void
1929 {
1930  /* no-op */
1931 }
1932 
1933 /*
1934  * sqlfunction_destroy --- release DestReceiver object
1935  */
1936 static void
1938 {
1939  pfree(self);
1940 }
bool SubTransactionIsActive(SubTransactionId subxid)
Definition: xact.c:663
signed short int16
Definition: c.h:255
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition: tuplestore.c:708
#define NIL
Definition: pg_list.h:69
Datum value
Definition: params.h:56
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:97
#define TYPTYPE_DOMAIN
Definition: pg_type.h:722
Definition: fmgr.h:56
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:141
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:776
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
int stmt_location
Definition: parsenodes.h:180
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void * parserSetupArg
Definition: params.h:73
EState * estate
Definition: execdesc.h:48
MemoryContext fn_mcxt
Definition: fmgr.h:65
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
#define TYPTYPE_BASE
Definition: pg_type.h:720
static void sqlfunction_destroy(DestReceiver *self)
Definition: functions.c:1937
MemoryContext fcontext
Definition: functions.c:121
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:106
DestReceiver pub
Definition: functions.c:43
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
PGPROC * MyProc
Definition: proc.c:67
void UnregisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:758
#define PointerGetDatum(X)
Definition: postgres.h:562
CommandDest mydest
Definition: dest.h:128
char * pstrdup(const char *in)
Definition: mcxt.c:1077
JunkFilter * ExecInitJunkFilterConversion(List *targetList, TupleDesc cleanTupType, TupleTableSlot *slot)
Definition: execJunk.c:136
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition: functions.c:273
struct SQLFunctionParseInfo * SQLFunctionParseInfoPtr
Definition: functions.h:21
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:144
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define llast(l)
Definition: pg_list.h:131
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:834
#define INT4OID
Definition: pg_type.h:316
struct execution_state execution_state
ParamKind paramkind
Definition: primnodes.h:244
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:509
#define strVal(v)
Definition: value.h:54
ExecStatus status
Definition: functions.c:66
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag)
Definition: utility.c:335
int errcode(int sqlerrcode)
Definition: elog.c:575
TupleTableSlot * jf_resultSlot
Definition: execnodes.h:335
bool check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList, bool *modifyTargetList, JunkFilter **junkFilter)
Definition: functions.c:1531
char get_typtype(Oid typid)
Definition: lsyscache.c:2379
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:1902
JunkFilter * junkFilter
Definition: functions.c:111
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1928
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:780
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1632
static Node * sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo, const char *paramname, int location)
Definition: functions.c:448
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, FuncCall *fn, int location)
Definition: parse_func.c:69
uint32 SubTransactionId
Definition: c.h:401
ParserSetupHook parserSetup
Definition: params.h:72
Tuplestorestate * tstore
Definition: functions.c:109
struct ParamListInfoData * ParamListInfo
Definition: params.h:62
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:118
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:296
DestReceiver * None_Receiver
Definition: dest.c:91
struct ErrorContextCallback * previous
Definition: elog.h:238
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
int natts
Definition: tupdesc.h:73
int stmt_len
Definition: plannodes.h:98
#define PG_GET_COLLATION()
Definition: fmgr.h:163
#define lsecond(l)
Definition: pg_list.h:116
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
PostParseColumnRefHook p_post_columnref_hook
Definition: parse_node.h:207
signed int int32
Definition: c.h:256
List * targetList
Definition: parsenodes.h:138
Snapshot snapshot
Definition: execdesc.h:39
int location
Definition: parsenodes.h:236
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:1911
#define list_make1(x1)
Definition: pg_list.h:139
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:458
void * paramFetchArg
Definition: params.h:71
QueryEnvironment * queryEnv
Definition: execdesc.h:43
ParamFetchHook paramFetch
Definition: params.h:70
void pfree(void *pointer)
Definition: mcxt.c:950
bool IsInParallelMode(void)
Definition: xact.c:913
bool resjunk
Definition: primnodes.h:1374
#define linitial(l)
Definition: pg_list.h:111
#define VOIDOID
Definition: pg_type.h:690
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
static void sql_exec_error_callback(void *arg)
Definition: functions.c:1366
Oid paramcollid
Definition: primnodes.h:248
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:296
int location
Definition: primnodes.h:249
List * pg_parse_query(const char *query_string)
Definition: postgres.c:602
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
void tuplestore_clear(Tuplestorestate *state)
Definition: tuplestore.c:418
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
#define lfirst_node(type, lc)
Definition: pg_list.h:109
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:1031
static void postquel_end(execution_state *es)
Definition: functions.c:876
int stmt_location
Definition: plannodes.h:97
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:208
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
List * func_state
Definition: functions.c:119
struct SQLFunctionParseInfo SQLFunctionParseInfo
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:399
LocalTransactionId lxid
Definition: functions.c:124
TupleDesc jf_cleanTupType
Definition: execnodes.h:333
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
JunkFilter * ExecInitJunkFilter(List *targetList, bool hasoid, TupleTableSlot *slot)
Definition: execJunk.c:61
int errdetail(const char *fmt,...)
Definition: elog.c:873
AttrNumber resno
Definition: primnodes.h:1368
ParamListInfo params
Definition: execdesc.h:42
Node * utilityStmt
Definition: plannodes.h:94
int geterrposition(void)
Definition: elog.c:1257
static Node * sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
Definition: functions.c:286
static void ShutdownSQLFunction(Datum arg)
Definition: functions.c:1448
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:66
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:846
static List * init_execution_state(List *queryTree_list, SQLFunctionCachePtr fcache, bool lazyEvalOK)
Definition: functions.c:472
struct Bitmapset * paramMask
Definition: params.h:75
#define Anum_pg_proc_proargmodes
Definition: pg_proc.h:111
#define RECORDOID
Definition: pg_type.h:680
bool argnull[FUNC_MAX_ARGS]
Definition: fmgr.h:86
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
uint32 LocalTransactionId
Definition: c.h:399
Datum fmgr_sql(PG_FUNCTION_ARGS)
Definition: functions.c:989
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2404
List * returningList
Definition: parsenodes.h:144
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
#define AssertArg(condition)
Definition: c.h:677
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2035
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:398
SQLFunctionParseInfoPtr pinfo
Definition: functions.c:96
bool IsBinaryCoercible(Oid srctype, Oid targettype)
struct ParamExternData ParamExternData
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5485
List * lappend(List *list, void *datum)
Definition: list.c:128
int ExecCleanTargetListLength(List *targetlist)
Definition: execUtils.c:1007
TypeFuncClass get_func_result_type(Oid functionId, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:269
#define Anum_pg_proc_proargnames
Definition: pg_proc.h:112
#define TYPTYPE_RANGE
Definition: pg_type.h:725
DestReceiver * CreateSQLFunctionDestReceiver(void)
Definition: functions.c:1883
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:25
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
int get_func_input_arg_names(Datum proargnames, Datum proargmodes, char ***arg_names)
Definition: funcapi.c:933
#define TextDatumGetCString(d)
Definition: builtins.h:92
bool canSetTag
Definition: plannodes.h:53
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:878
ExecStatus
Definition: functions.c:58
uintptr_t Datum
Definition: postgres.h:372
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
void CommandCounterIncrement(void)
Definition: xact.c:922
CmdType commandType
Definition: plannodes.h:45
Oid get_fn_expr_rettype(FmgrInfo *flinfo)
Definition: fmgr.c:1887
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
static void sqlfunction_shutdown(DestReceiver *self)
Definition: functions.c:1928
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
int number
Definition: parsenodes.h:245
int work_mem
Definition: globals.c:112
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
QueryDesc * qd
Definition: functions.c:70
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2781
int allowedModes
Definition: execnodes.h:268
int internalerrquery(const char *query)
Definition: elog.c:1161
Datum arg[FUNC_MAX_ARGS]
Definition: fmgr.h:85
CmdType commandType
Definition: parsenodes.h:110
int32 paramtypmod
Definition: primnodes.h:247
int location
Definition: parsenodes.h:246
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
static Datum postquel_get_single_result(TupleTableSlot *slot, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache, MemoryContext resultcontext)
Definition: functions.c:946
#define makeNode(_type_)
Definition: nodes.h:557
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
void RegisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:732
void * p_ref_hook_state
Definition: parse_node.h:210
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:649
fmNodePtr fn_expr
Definition: fmgr.h:66
bool hasModifyingCTE
Definition: plannodes.h:51
ParamListInfo paramLI
Definition: functions.c:107
Expr * expr
Definition: primnodes.h:1367
int paramid
Definition: primnodes.h:245
uint64 es_processed
Definition: execnodes.h:454
bool canSetTag
Definition: parsenodes.h:116
uint16 pflags
Definition: params.h:58
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2001
static Node * sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
Definition: functions.c:402
MemoryContext cxt
Definition: functions.c:45
void * fn_extra
Definition: fmgr.h:64
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:681
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:62
Tuplestorestate * setResult
Definition: execnodes.h:273
#define DatumGetPointer(X)
Definition: postgres.h:555
DestReceiver * dest
Definition: execdesc.h:41
ExprContext * econtext
Definition: execnodes.h:266
Node * setOperations
Definition: parsenodes.h:163
JunkFilter * filter
Definition: functions.c:46
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2603
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:128
TupleDesc setDesc
Definition: execnodes.h:274
void(* callback)(void *arg)
Definition: elog.h:239
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: heaptuple.c:1141
#define errcontext
Definition: elog.h:164
#define NameStr(name)
Definition: c.h:499
#define TYPTYPE_ENUM
Definition: pg_type.h:723
Index ressortgroupref
Definition: primnodes.h:1370
void * arg
#define lthird(l)
Definition: pg_list.h:121
static Node * sql_fn_make_param(SQLFunctionParseInfoPtr pinfo, int paramno, int location)
Definition: functions.c:418
#define PG_FUNCTION_ARGS
Definition: fmgr.h:158
#define elog
Definition: elog.h:219
PreParseColumnRefHook p_pre_columnref_hook
Definition: parse_node.h:206
ExprDoneCond isDone
Definition: execnodes.h:271
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition: functions.c:184
SubTransactionId subxid
Definition: functions.c:125
static struct @121 value
PlannedStmt * plannedstmt
Definition: execdesc.h:37
Datum ExecFetchSlotTupleDatum(TupleTableSlot *slot)
Definition: execTuples.c:698
struct execution_state * next
Definition: functions.c:65
PlannedStmt * stmt
Definition: functions.c:69
static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:842
Definition: pg_list.h:45
bool isnull
Definition: params.h:57
int stmt_len
Definition: parsenodes.h:181
static void postquel_sub_params(SQLFunctionCachePtr fcache, FunctionCallInfo fcinfo)
Definition: functions.c:896
Oid paramtype
Definition: primnodes.h:246
#define offsetof(type, field)
Definition: c.h:555
int errposition(int cursorpos)
Definition: elog.c:1125
List * fields
Definition: parsenodes.h:235
static void init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
Definition: functions.c:593
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
LocalTransactionId lxid
Definition: proc.h:105
int internalerrposition(int cursorpos)
Definition: elog.c:1141
Tuplestorestate * tstore
Definition: functions.c:44
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:785