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