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