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