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