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,
514  NULL);
515 
516  /*
517  * Precheck all commands for validity in a function. This should
518  * generally match the restrictions spi.c applies.
519  */
520  if (stmt->commandType == CMD_UTILITY)
521  {
522  if (IsA(stmt->utilityStmt, CopyStmt) &&
523  ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
524  ereport(ERROR,
525  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
526  errmsg("cannot COPY to/from client in a SQL function")));
527 
528  if (IsA(stmt->utilityStmt, TransactionStmt))
529  ereport(ERROR,
530  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
531  /* translator: %s is a SQL statement name */
532  errmsg("%s is not allowed in a SQL function",
533  CreateCommandTag(stmt->utilityStmt))));
534  }
535 
536  if (fcache->readonly_func && !CommandIsReadOnly(stmt))
537  ereport(ERROR,
538  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
539  /* translator: %s is a SQL statement name */
540  errmsg("%s is not allowed in a non-volatile function",
541  CreateCommandTag((Node *) stmt))));
542 
543  /* OK, build the execution_state for this query */
544  newes = (execution_state *) palloc(sizeof(execution_state));
545  if (preves)
546  preves->next = newes;
547  else
548  firstes = newes;
549 
550  newes->next = NULL;
551  newes->status = F_EXEC_START;
552  newes->setsResult = false; /* might change below */
553  newes->lazyEval = false; /* might change below */
554  newes->stmt = stmt;
555  newes->qd = NULL;
556 
557  if (queryTree->canSetTag)
558  lasttages = newes;
559 
560  preves = newes;
561  }
562 
563  eslist = lappend(eslist, firstes);
564  }
565 
566  /*
567  * Mark the last canSetTag query as delivering the function result; then,
568  * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
569  * SELECT we must always run it to completion.
570  *
571  * Note: at some point we might add additional criteria for whether to use
572  * lazy eval. However, we should prefer to use it whenever the function
573  * doesn't return set, since fetching more than one row is useless in that
574  * case.
575  *
576  * Note: don't set setsResult if the function returns VOID, as evidenced
577  * by not having made a junkfilter. This ensures we'll throw away any
578  * output from the last statement in such a function.
579  */
580  if (lasttages && fcache->junkFilter)
581  {
582  lasttages->setsResult = true;
583  if (lazyEvalOK &&
584  lasttages->stmt->commandType == CMD_SELECT &&
585  !lasttages->stmt->hasModifyingCTE)
586  fcache->lazyEval = lasttages->lazyEval = true;
587  }
588 
589  return eslist;
590 }
591 
592 /*
593  * Initialize the SQLFunctionCache for a SQL function
594  */
595 static void
596 init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
597 {
598  FmgrInfo *finfo = fcinfo->flinfo;
599  Oid foid = finfo->fn_oid;
600  MemoryContext fcontext;
601  MemoryContext oldcontext;
602  Oid rettype;
603  TupleDesc rettupdesc;
604  HeapTuple procedureTuple;
605  Form_pg_proc procedureStruct;
606  SQLFunctionCachePtr fcache;
607  List *raw_parsetree_list;
608  List *queryTree_list;
609  List *flat_query_list;
610  List *resulttlist;
611  ListCell *lc;
612  Datum tmp;
613  bool isNull;
614 
615  /*
616  * Create memory context that holds all the SQLFunctionCache data. It
617  * must be a child of whatever context holds the FmgrInfo.
618  */
619  fcontext = AllocSetContextCreate(finfo->fn_mcxt,
620  "SQL function",
622 
623  oldcontext = MemoryContextSwitchTo(fcontext);
624 
625  /*
626  * Create the struct proper, link it to fcontext and fn_extra. Once this
627  * is done, we'll be able to recover the memory after failure, even if the
628  * FmgrInfo is long-lived.
629  */
630  fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
631  fcache->fcontext = fcontext;
632  finfo->fn_extra = (void *) fcache;
633 
634  /*
635  * get the procedure tuple corresponding to the given function Oid
636  */
637  procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
638  if (!HeapTupleIsValid(procedureTuple))
639  elog(ERROR, "cache lookup failed for function %u", foid);
640  procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
641 
642  /*
643  * copy function name immediately for use by error reporting callback, and
644  * for use as memory context identifier
645  */
646  fcache->fname = pstrdup(NameStr(procedureStruct->proname));
647  MemoryContextSetIdentifier(fcontext, fcache->fname);
648 
649  /*
650  * Resolve any polymorphism, obtaining the actual result type, and the
651  * corresponding tupdesc if it's a rowtype.
652  */
653  (void) get_call_result_type(fcinfo, &rettype, &rettupdesc);
654 
655  fcache->rettype = rettype;
656 
657  /* Fetch the typlen and byval info for the result type */
658  get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
659 
660  /* Remember whether we're returning setof something */
661  fcache->returnsSet = procedureStruct->proretset;
662 
663  /* Remember if function is STABLE/IMMUTABLE */
664  fcache->readonly_func =
665  (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
666 
667  /*
668  * We need the actual argument types to pass to the parser. Also make
669  * sure that parameter symbols are considered to have the function's
670  * resolved input collation.
671  */
672  fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
673  finfo->fn_expr,
674  collation);
675 
676  /*
677  * And of course we need the function body text.
678  */
679  tmp = SysCacheGetAttr(PROCOID,
680  procedureTuple,
681  Anum_pg_proc_prosrc,
682  &isNull);
683  if (isNull)
684  elog(ERROR, "null prosrc for function %u", foid);
685  fcache->src = TextDatumGetCString(tmp);
686 
687  /*
688  * Parse and rewrite the queries in the function text. Use sublists to
689  * keep track of the original query boundaries. But we also build a
690  * "flat" list of the rewritten queries to pass to check_sql_fn_retval.
691  * This is because the last canSetTag query determines the result type
692  * independently of query boundaries --- and it might not be in the last
693  * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
694  * (It might not be unreasonable to throw an error in such a case, but
695  * this is the historical behavior and it doesn't seem worth changing.)
696  *
697  * Note: since parsing and planning is done in fcontext, we will generate
698  * a lot of cruft that lives as long as the fcache does. This is annoying
699  * but we'll not worry about it until the module is rewritten to use
700  * plancache.c.
701  */
702  raw_parsetree_list = pg_parse_query(fcache->src);
703 
704  queryTree_list = NIL;
705  flat_query_list = NIL;
706  foreach(lc, raw_parsetree_list)
707  {
708  RawStmt *parsetree = lfirst_node(RawStmt, lc);
709  List *queryTree_sublist;
710 
711  queryTree_sublist = pg_analyze_and_rewrite_params(parsetree,
712  fcache->src,
714  fcache->pinfo,
715  NULL);
716  queryTree_list = lappend(queryTree_list, queryTree_sublist);
717  flat_query_list = list_concat(flat_query_list, queryTree_sublist);
718  }
719 
720  check_sql_fn_statements(flat_query_list);
721 
722  /*
723  * Check that the function returns the type it claims to. Although in
724  * simple cases this was already done when the function was defined, we
725  * have to recheck because database objects used in the function's queries
726  * might have changed type. We'd have to recheck anyway if the function
727  * had any polymorphic arguments. Moreover, check_sql_fn_retval takes
728  * care of injecting any required column type coercions. (But we don't
729  * ask it to insert nulls for dropped columns; the junkfilter handles
730  * that.)
731  *
732  * Note: we set fcache->returnsTuple according to whether we are returning
733  * the whole tuple result or just a single column. In the latter case we
734  * clear returnsTuple because we need not act different from the scalar
735  * result case, even if it's a rowtype column. (However, we have to force
736  * lazy eval mode in that case; otherwise we'd need extra code to expand
737  * the rowtype column into multiple columns, since we have no way to
738  * notify the caller that it should do that.)
739  */
740  fcache->returnsTuple = check_sql_fn_retval(flat_query_list,
741  rettype,
742  rettupdesc,
743  false,
744  &resulttlist);
745 
746  /*
747  * Construct a JunkFilter we can use to coerce the returned rowtype to the
748  * desired form, unless the result type is VOID, in which case there's
749  * nothing to coerce to. (XXX Frequently, the JunkFilter isn't doing
750  * anything very interesting, but much of this module expects it to be
751  * there anyway.)
752  */
753  if (rettype != VOIDOID)
754  {
757 
758  /*
759  * If the result is composite, *and* we are returning the whole tuple
760  * result, we need to insert nulls for any dropped columns. In the
761  * single-column-result case, there might be dropped columns within
762  * the composite column value, but it's not our problem here. There
763  * should be no resjunk entries in resulttlist, so in the second case
764  * the JunkFilter is certainly a no-op.
765  */
766  if (rettupdesc && fcache->returnsTuple)
767  fcache->junkFilter = ExecInitJunkFilterConversion(resulttlist,
768  rettupdesc,
769  slot);
770  else
771  fcache->junkFilter = ExecInitJunkFilter(resulttlist, slot);
772  }
773 
774  if (fcache->returnsTuple)
775  {
776  /* Make sure output rowtype is properly blessed */
778  }
779  else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
780  {
781  /*
782  * Returning rowtype as if it were scalar --- materialize won't work.
783  * Right now it's sufficient to override any caller preference for
784  * materialize mode, but to add more smarts in init_execution_state
785  * about this, we'd probably need a three-way flag instead of bool.
786  */
787  lazyEvalOK = true;
788  }
789 
790  /* Finally, plan the queries */
791  fcache->func_state = init_execution_state(queryTree_list,
792  fcache,
793  lazyEvalOK);
794 
795  /* Mark fcache with time of creation to show it's valid */
796  fcache->lxid = MyProc->lxid;
798 
799  ReleaseSysCache(procedureTuple);
800 
801  MemoryContextSwitchTo(oldcontext);
802 }
803 
804 /* Start up execution of one execution_state node */
805 static void
807 {
809 
810  Assert(es->qd == NULL);
811 
812  /* Caller should have ensured a suitable snapshot is active */
814 
815  /*
816  * If this query produces the function result, send its output to the
817  * tuplestore; else discard any output.
818  */
819  if (es->setsResult)
820  {
821  DR_sqlfunction *myState;
822 
824  /* pass down the needed info to the dest receiver routines */
825  myState = (DR_sqlfunction *) dest;
826  Assert(myState->pub.mydest == DestSQLFunction);
827  myState->tstore = fcache->tstore;
828  myState->cxt = CurrentMemoryContext;
829  myState->filter = fcache->junkFilter;
830  }
831  else
832  dest = None_Receiver;
833 
834  es->qd = CreateQueryDesc(es->stmt,
835  fcache->src,
838  dest,
839  fcache->paramLI,
840  es->qd ? es->qd->queryEnv : NULL,
841  0);
842 
843  /* Utility commands don't need Executor. */
844  if (es->qd->operation != CMD_UTILITY)
845  {
846  /*
847  * In lazyEval mode, do not let the executor set up an AfterTrigger
848  * context. This is necessary not just an optimization, because we
849  * mustn't exit from the function execution with a stacked
850  * AfterTrigger level still active. We are careful not to select
851  * lazyEval mode for any statement that could possibly queue triggers.
852  */
853  int eflags;
854 
855  if (es->lazyEval)
856  eflags = EXEC_FLAG_SKIP_TRIGGERS;
857  else
858  eflags = 0; /* default run-to-completion flags */
859  ExecutorStart(es->qd, eflags);
860  }
861 
862  es->status = F_EXEC_RUN;
863 }
864 
865 /* Run one execution_state; either to completion or to first result row */
866 /* Returns true if we ran to completion */
867 static bool
869 {
870  bool result;
871 
872  if (es->qd->operation == CMD_UTILITY)
873  {
875  fcache->src,
877  es->qd->params,
878  es->qd->queryEnv,
879  es->qd->dest,
880  NULL);
881  result = true; /* never stops early */
882  }
883  else
884  {
885  /* Run regular commands to completion unless lazyEval */
886  uint64 count = (es->lazyEval) ? 1 : 0;
887 
888  ExecutorRun(es->qd, ForwardScanDirection, count, !fcache->returnsSet || !es->lazyEval);
889 
890  /*
891  * If we requested run to completion OR there was no tuple returned,
892  * command must be complete.
893  */
894  result = (count == 0 || es->qd->estate->es_processed == 0);
895  }
896 
897  return result;
898 }
899 
900 /* Shut down execution of one execution_state node */
901 static void
903 {
904  /* mark status done to ensure we don't do ExecutorEnd twice */
905  es->status = F_EXEC_DONE;
906 
907  /* Utility commands don't need Executor. */
908  if (es->qd->operation != CMD_UTILITY)
909  {
910  ExecutorFinish(es->qd);
911  ExecutorEnd(es->qd);
912  }
913 
914  es->qd->dest->rDestroy(es->qd->dest);
915 
916  FreeQueryDesc(es->qd);
917  es->qd = NULL;
918 }
919 
920 /* Build ParamListInfo array representing current arguments */
921 static void
923  FunctionCallInfo fcinfo)
924 {
925  int nargs = fcinfo->nargs;
926 
927  if (nargs > 0)
928  {
929  ParamListInfo paramLI;
930 
931  if (fcache->paramLI == NULL)
932  {
933  paramLI = makeParamList(nargs);
934  fcache->paramLI = paramLI;
935  }
936  else
937  {
938  paramLI = fcache->paramLI;
939  Assert(paramLI->numParams == nargs);
940  }
941 
942  for (int i = 0; i < nargs; i++)
943  {
944  ParamExternData *prm = &paramLI->params[i];
945 
946  prm->value = fcinfo->args[i].value;
947  prm->isnull = fcinfo->args[i].isnull;
948  prm->pflags = 0;
949  prm->ptype = fcache->pinfo->argtypes[i];
950  }
951  }
952  else
953  fcache->paramLI = NULL;
954 }
955 
956 /*
957  * Extract the SQL function's value from a single result row. This is used
958  * both for scalar (non-set) functions and for each row of a lazy-eval set
959  * result.
960  */
961 static Datum
963  FunctionCallInfo fcinfo,
964  SQLFunctionCachePtr fcache,
965  MemoryContext resultcontext)
966 {
967  Datum value;
968  MemoryContext oldcontext;
969 
970  /*
971  * Set up to return the function value. For pass-by-reference datatypes,
972  * be sure to allocate the result in resultcontext, not the current memory
973  * context (which has query lifespan). We can't leave the data in the
974  * TupleTableSlot because we intend to clear the slot before returning.
975  */
976  oldcontext = MemoryContextSwitchTo(resultcontext);
977 
978  if (fcache->returnsTuple)
979  {
980  /* We must return the whole tuple as a Datum. */
981  fcinfo->isnull = false;
982  value = ExecFetchSlotHeapTupleDatum(slot);
983  }
984  else
985  {
986  /*
987  * Returning a scalar, which we have to extract from the first column
988  * of the SELECT result, and then copy into result context if needed.
989  */
990  value = slot_getattr(slot, 1, &(fcinfo->isnull));
991 
992  if (!fcinfo->isnull)
993  value = datumCopy(value, fcache->typbyval, fcache->typlen);
994  }
995 
996  MemoryContextSwitchTo(oldcontext);
997 
998  return value;
999 }
1000 
1001 /*
1002  * fmgr_sql: function call manager for SQL functions
1003  */
1004 Datum
1006 {
1007  SQLFunctionCachePtr fcache;
1008  ErrorContextCallback sqlerrcontext;
1009  MemoryContext oldcontext;
1010  bool randomAccess;
1011  bool lazyEvalOK;
1012  bool is_first;
1013  bool pushed_snapshot;
1014  execution_state *es;
1015  TupleTableSlot *slot;
1016  Datum result;
1017  List *eslist;
1018  ListCell *eslc;
1019 
1020  /*
1021  * Setup error traceback support for ereport()
1022  */
1023  sqlerrcontext.callback = sql_exec_error_callback;
1024  sqlerrcontext.arg = fcinfo->flinfo;
1025  sqlerrcontext.previous = error_context_stack;
1026  error_context_stack = &sqlerrcontext;
1027 
1028  /* Check call context */
1029  if (fcinfo->flinfo->fn_retset)
1030  {
1031  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1032 
1033  /*
1034  * For simplicity, we require callers to support both set eval modes.
1035  * There are cases where we must use one or must use the other, and
1036  * it's not really worthwhile to postpone the check till we know. But
1037  * note we do not require caller to provide an expectedDesc.
1038  */
1039  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1040  (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1041  (rsi->allowedModes & SFRM_Materialize) == 0)
1042  ereport(ERROR,
1043  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1044  errmsg("set-valued function called in context that cannot accept a set")));
1045  randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1046  lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1047  }
1048  else
1049  {
1050  randomAccess = false;
1051  lazyEvalOK = true;
1052  }
1053 
1054  /*
1055  * Initialize fcache (build plans) if first time through; or re-initialize
1056  * if the cache is stale.
1057  */
1058  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1059 
1060  if (fcache != NULL)
1061  {
1062  if (fcache->lxid != MyProc->lxid ||
1063  !SubTransactionIsActive(fcache->subxid))
1064  {
1065  /* It's stale; unlink and delete */
1066  fcinfo->flinfo->fn_extra = NULL;
1067  MemoryContextDelete(fcache->fcontext);
1068  fcache = NULL;
1069  }
1070  }
1071 
1072  if (fcache == NULL)
1073  {
1074  init_sql_fcache(fcinfo, PG_GET_COLLATION(), lazyEvalOK);
1075  fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1076  }
1077 
1078  /*
1079  * Switch to context in which the fcache lives. This ensures that our
1080  * tuplestore etc will have sufficient lifetime. The sub-executor is
1081  * responsible for deleting per-tuple information. (XXX in the case of a
1082  * long-lived FmgrInfo, this policy represents more memory leakage, but
1083  * it's not entirely clear where to keep stuff instead.)
1084  */
1085  oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1086 
1087  /*
1088  * Find first unfinished query in function, and note whether it's the
1089  * first query.
1090  */
1091  eslist = fcache->func_state;
1092  es = NULL;
1093  is_first = true;
1094  foreach(eslc, eslist)
1095  {
1096  es = (execution_state *) lfirst(eslc);
1097 
1098  while (es && es->status == F_EXEC_DONE)
1099  {
1100  is_first = false;
1101  es = es->next;
1102  }
1103 
1104  if (es)
1105  break;
1106  }
1107 
1108  /*
1109  * Convert params to appropriate format if starting a fresh execution. (If
1110  * continuing execution, we can re-use prior params.)
1111  */
1112  if (is_first && es && es->status == F_EXEC_START)
1113  postquel_sub_params(fcache, fcinfo);
1114 
1115  /*
1116  * Build tuplestore to hold results, if we don't have one already. Note
1117  * it's in the query-lifespan context.
1118  */
1119  if (!fcache->tstore)
1120  fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1121 
1122  /*
1123  * Execute each command in the function one after another until we either
1124  * run out of commands or get a result row from a lazily-evaluated SELECT.
1125  *
1126  * Notes about snapshot management:
1127  *
1128  * In a read-only function, we just use the surrounding query's snapshot.
1129  *
1130  * In a non-read-only function, we rely on the fact that we'll never
1131  * suspend execution between queries of the function: the only reason to
1132  * suspend execution before completion is if we are returning a row from a
1133  * lazily-evaluated SELECT. So, when first entering this loop, we'll
1134  * either start a new query (and push a fresh snapshot) or re-establish
1135  * the active snapshot from the existing query descriptor. If we need to
1136  * start a new query in a subsequent execution of the loop, either we need
1137  * a fresh snapshot (and pushed_snapshot is false) or the existing
1138  * snapshot is on the active stack and we can just bump its command ID.
1139  */
1140  pushed_snapshot = false;
1141  while (es)
1142  {
1143  bool completed;
1144 
1145  if (es->status == F_EXEC_START)
1146  {
1147  /*
1148  * If not read-only, be sure to advance the command counter for
1149  * each command, so that all work to date in this transaction is
1150  * visible. Take a new snapshot if we don't have one yet,
1151  * otherwise just bump the command ID in the existing snapshot.
1152  */
1153  if (!fcache->readonly_func)
1154  {
1156  if (!pushed_snapshot)
1157  {
1159  pushed_snapshot = true;
1160  }
1161  else
1163  }
1164 
1165  postquel_start(es, fcache);
1166  }
1167  else if (!fcache->readonly_func && !pushed_snapshot)
1168  {
1169  /* Re-establish active snapshot when re-entering function */
1171  pushed_snapshot = true;
1172  }
1173 
1174  completed = postquel_getnext(es, fcache);
1175 
1176  /*
1177  * If we ran the command to completion, we can shut it down now. Any
1178  * row(s) we need to return are safely stashed in the tuplestore, and
1179  * we want to be sure that, for example, AFTER triggers get fired
1180  * before we return anything. Also, if the function doesn't return
1181  * set, we can shut it down anyway because it must be a SELECT and we
1182  * don't care about fetching any more result rows.
1183  */
1184  if (completed || !fcache->returnsSet)
1185  postquel_end(es);
1186 
1187  /*
1188  * Break from loop if we didn't shut down (implying we got a
1189  * lazily-evaluated row). Otherwise we'll press on till the whole
1190  * function is done, relying on the tuplestore to keep hold of the
1191  * data to eventually be returned. This is necessary since an
1192  * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1193  * followed by additional rule-inserted commands, and we want to
1194  * finish doing all those commands before we return anything.
1195  */
1196  if (es->status != F_EXEC_DONE)
1197  break;
1198 
1199  /*
1200  * Advance to next execution_state, which might be in the next list.
1201  */
1202  es = es->next;
1203  while (!es)
1204  {
1205  eslc = lnext(eslist, eslc);
1206  if (!eslc)
1207  break; /* end of function */
1208 
1209  es = (execution_state *) lfirst(eslc);
1210 
1211  /*
1212  * Flush the current snapshot so that we will take a new one for
1213  * the new query list. This ensures that new snaps are taken at
1214  * original-query boundaries, matching the behavior of interactive
1215  * execution.
1216  */
1217  if (pushed_snapshot)
1218  {
1220  pushed_snapshot = false;
1221  }
1222  }
1223  }
1224 
1225  /*
1226  * The tuplestore now contains whatever row(s) we are supposed to return.
1227  */
1228  if (fcache->returnsSet)
1229  {
1230  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1231 
1232  if (es)
1233  {
1234  /*
1235  * If we stopped short of being done, we must have a lazy-eval
1236  * row.
1237  */
1238  Assert(es->lazyEval);
1239  /* Re-use the junkfilter's output slot to fetch back the tuple */
1240  Assert(fcache->junkFilter);
1241  slot = fcache->junkFilter->jf_resultSlot;
1242  if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1243  elog(ERROR, "failed to fetch lazy-eval tuple");
1244  /* Extract the result as a datum, and copy out from the slot */
1245  result = postquel_get_single_result(slot, fcinfo,
1246  fcache, oldcontext);
1247  /* Clear the tuplestore, but keep it for next time */
1248  /* NB: this might delete the slot's content, but we don't care */
1249  tuplestore_clear(fcache->tstore);
1250 
1251  /*
1252  * Let caller know we're not finished.
1253  */
1254  rsi->isDone = ExprMultipleResult;
1255 
1256  /*
1257  * Ensure we will get shut down cleanly if the exprcontext is not
1258  * run to completion.
1259  */
1260  if (!fcache->shutdown_reg)
1261  {
1264  PointerGetDatum(fcache));
1265  fcache->shutdown_reg = true;
1266  }
1267  }
1268  else if (fcache->lazyEval)
1269  {
1270  /*
1271  * We are done with a lazy evaluation. Clean up.
1272  */
1273  tuplestore_clear(fcache->tstore);
1274 
1275  /*
1276  * Let caller know we're finished.
1277  */
1278  rsi->isDone = ExprEndResult;
1279 
1280  fcinfo->isnull = true;
1281  result = (Datum) 0;
1282 
1283  /* Deregister shutdown callback, if we made one */
1284  if (fcache->shutdown_reg)
1285  {
1288  PointerGetDatum(fcache));
1289  fcache->shutdown_reg = false;
1290  }
1291  }
1292  else
1293  {
1294  /*
1295  * We are done with a non-lazy evaluation. Return whatever is in
1296  * the tuplestore. (It is now caller's responsibility to free the
1297  * tuplestore when done.)
1298  */
1300  rsi->setResult = fcache->tstore;
1301  fcache->tstore = NULL;
1302  /* must copy desc because execSRF.c will free it */
1303  if (fcache->junkFilter)
1305 
1306  fcinfo->isnull = true;
1307  result = (Datum) 0;
1308 
1309  /* Deregister shutdown callback, if we made one */
1310  if (fcache->shutdown_reg)
1311  {
1314  PointerGetDatum(fcache));
1315  fcache->shutdown_reg = false;
1316  }
1317  }
1318  }
1319  else
1320  {
1321  /*
1322  * Non-set function. If we got a row, return it; else return NULL.
1323  */
1324  if (fcache->junkFilter)
1325  {
1326  /* Re-use the junkfilter's output slot to fetch back the tuple */
1327  slot = fcache->junkFilter->jf_resultSlot;
1328  if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1329  result = postquel_get_single_result(slot, fcinfo,
1330  fcache, oldcontext);
1331  else
1332  {
1333  fcinfo->isnull = true;
1334  result = (Datum) 0;
1335  }
1336  }
1337  else
1338  {
1339  /* Should only get here for VOID functions and procedures */
1340  Assert(fcache->rettype == VOIDOID);
1341  fcinfo->isnull = true;
1342  result = (Datum) 0;
1343  }
1344 
1345  /* Clear the tuplestore, but keep it for next time */
1346  tuplestore_clear(fcache->tstore);
1347  }
1348 
1349  /* Pop snapshot if we have pushed one */
1350  if (pushed_snapshot)
1352 
1353  /*
1354  * If we've gone through every command in the function, we are done. Reset
1355  * the execution states to start over again on next call.
1356  */
1357  if (es == NULL)
1358  {
1359  foreach(eslc, fcache->func_state)
1360  {
1361  es = (execution_state *) lfirst(eslc);
1362  while (es)
1363  {
1364  es->status = F_EXEC_START;
1365  es = es->next;
1366  }
1367  }
1368  }
1369 
1370  error_context_stack = sqlerrcontext.previous;
1371 
1372  MemoryContextSwitchTo(oldcontext);
1373 
1374  return result;
1375 }
1376 
1377 
1378 /*
1379  * error context callback to let us supply a call-stack traceback
1380  */
1381 static void
1383 {
1384  FmgrInfo *flinfo = (FmgrInfo *) arg;
1386  int syntaxerrposition;
1387 
1388  /*
1389  * We can do nothing useful if init_sql_fcache() didn't get as far as
1390  * saving the function name
1391  */
1392  if (fcache == NULL || fcache->fname == NULL)
1393  return;
1394 
1395  /*
1396  * If there is a syntax error position, convert to internal syntax error
1397  */
1398  syntaxerrposition = geterrposition();
1399  if (syntaxerrposition > 0 && fcache->src != NULL)
1400  {
1401  errposition(0);
1402  internalerrposition(syntaxerrposition);
1403  internalerrquery(fcache->src);
1404  }
1405 
1406  /*
1407  * Try to determine where in the function we failed. If there is a query
1408  * with non-null QueryDesc, finger it. (We check this rather than looking
1409  * for F_EXEC_RUN state, so that errors during ExecutorStart or
1410  * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1411  * postquel_end.)
1412  */
1413  if (fcache->func_state)
1414  {
1415  execution_state *es;
1416  int query_num;
1417  ListCell *lc;
1418 
1419  es = NULL;
1420  query_num = 1;
1421  foreach(lc, fcache->func_state)
1422  {
1423  es = (execution_state *) lfirst(lc);
1424  while (es)
1425  {
1426  if (es->qd)
1427  {
1428  errcontext("SQL function \"%s\" statement %d",
1429  fcache->fname, query_num);
1430  break;
1431  }
1432  es = es->next;
1433  }
1434  if (es)
1435  break;
1436  query_num++;
1437  }
1438  if (es == NULL)
1439  {
1440  /*
1441  * couldn't identify a running query; might be function entry,
1442  * function exit, or between queries.
1443  */
1444  errcontext("SQL function \"%s\"", fcache->fname);
1445  }
1446  }
1447  else
1448  {
1449  /*
1450  * Assume we failed during init_sql_fcache(). (It's possible that the
1451  * function actually has an empty body, but in that case we may as
1452  * well report all errors as being "during startup".)
1453  */
1454  errcontext("SQL function \"%s\" during startup", fcache->fname);
1455  }
1456 }
1457 
1458 
1459 /*
1460  * callback function in case a function-returning-set needs to be shut down
1461  * before it has been run to completion
1462  */
1463 static void
1465 {
1467  execution_state *es;
1468  ListCell *lc;
1469 
1470  foreach(lc, fcache->func_state)
1471  {
1472  es = (execution_state *) lfirst(lc);
1473  while (es)
1474  {
1475  /* Shut down anything still running */
1476  if (es->status == F_EXEC_RUN)
1477  {
1478  /* Re-establish active snapshot for any called functions */
1479  if (!fcache->readonly_func)
1481 
1482  postquel_end(es);
1483 
1484  if (!fcache->readonly_func)
1486  }
1487 
1488  /* Reset states to START in case we're called again */
1489  es->status = F_EXEC_START;
1490  es = es->next;
1491  }
1492  }
1493 
1494  /* Release tuplestore if we have one */
1495  if (fcache->tstore)
1496  tuplestore_end(fcache->tstore);
1497  fcache->tstore = NULL;
1498 
1499  /* execUtils will deregister the callback... */
1500  fcache->shutdown_reg = false;
1501 }
1502 
1503 /*
1504  * check_sql_fn_statements
1505  *
1506  * Check statements in an SQL function. Error out if there is anything that
1507  * is not acceptable.
1508  */
1509 void
1511 {
1512  ListCell *lc;
1513 
1514  foreach(lc, queryTreeList)
1515  {
1516  Query *query = lfirst_node(Query, lc);
1517 
1518  /*
1519  * Disallow procedures with output arguments. The current
1520  * implementation would just throw the output values away, unless the
1521  * statement is the last one. Per SQL standard, we should assign the
1522  * output values by name. By disallowing this here, we preserve an
1523  * opportunity for future improvement.
1524  */
1525  if (query->commandType == CMD_UTILITY &&
1526  IsA(query->utilityStmt, CallStmt))
1527  {
1529  HeapTuple tuple;
1530  int numargs;
1531  Oid *argtypes;
1532  char **argnames;
1533  char *argmodes;
1534  int i;
1535 
1537  if (!HeapTupleIsValid(tuple))
1538  elog(ERROR, "cache lookup failed for function %u", stmt->funcexpr->funcid);
1539  numargs = get_func_arg_info(tuple, &argtypes, &argnames, &argmodes);
1540  ReleaseSysCache(tuple);
1541 
1542  for (i = 0; i < numargs; i++)
1543  {
1544  if (argmodes && (argmodes[i] == PROARGMODE_INOUT || argmodes[i] == PROARGMODE_OUT))
1545  ereport(ERROR,
1546  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1547  errmsg("calling procedures with output arguments is not supported in SQL functions")));
1548  }
1549  }
1550  }
1551 }
1552 
1553 /*
1554  * check_sql_fn_retval() -- check return value of a list of sql parse trees.
1555  *
1556  * The return value of a sql function is the value returned by the last
1557  * canSetTag query in the function. We do some ad-hoc type checking and
1558  * coercion here to ensure that the function returns what it's supposed to.
1559  * Note that we may actually modify the last query to make it match!
1560  *
1561  * This function returns true if the sql function returns the entire tuple
1562  * result of its final statement, or false if it returns just the first column
1563  * result of that statement. It throws an error if the final statement doesn't
1564  * return the right type at all.
1565  *
1566  * Note that because we allow "SELECT rowtype_expression", the result can be
1567  * false even when the declared function return type is a rowtype.
1568  *
1569  * For a polymorphic function the passed rettype must be the actual resolved
1570  * output type of the function; we should never see a polymorphic pseudotype
1571  * such as ANYELEMENT as rettype. (This means we can't check the type during
1572  * function definition of a polymorphic function.) If the function returns
1573  * composite, the passed rettupdesc should describe the expected output.
1574  * If rettupdesc is NULL, we can't verify that the output matches; that
1575  * should only happen in fmgr_sql_validator(), or when the function returns
1576  * RECORD and the caller doesn't actually care which composite type it is.
1577  * (Typically, rettype and rettupdesc are computed by get_call_result_type
1578  * or a sibling function.)
1579  *
1580  * In addition to coercing individual output columns, we can modify the
1581  * output to include dummy NULL columns for any dropped columns appearing
1582  * in rettupdesc. This is done only if the caller asks for it.
1583  *
1584  * If resultTargetList isn't NULL, then *resultTargetList is set to the
1585  * targetlist that defines the final statement's result. Exception: if the
1586  * function is defined to return VOID then *resultTargetList is set to NIL.
1587  */
1588 bool
1589 check_sql_fn_retval(List *queryTreeList,
1590  Oid rettype, TupleDesc rettupdesc,
1591  bool insertDroppedCols,
1592  List **resultTargetList)
1593 {
1594  bool is_tuple_result = false;
1595  Query *parse;
1596  ListCell *parse_cell;
1597  List *tlist;
1598  int tlistlen;
1599  bool tlist_is_modifiable;
1600  char fn_typtype;
1601  List *upper_tlist = NIL;
1602  bool upper_tlist_nontrivial = false;
1603  ListCell *lc;
1604 
1605  /* Caller must have resolved any polymorphism */
1606  AssertArg(!IsPolymorphicType(rettype));
1607 
1608  if (resultTargetList)
1609  *resultTargetList = NIL; /* initialize in case of VOID result */
1610 
1611  /*
1612  * If it's declared to return VOID, we don't care what's in the function.
1613  * (This takes care of the procedure case, as well.)
1614  */
1615  if (rettype == VOIDOID)
1616  return false;
1617 
1618  /*
1619  * Find the last canSetTag query in the list. This isn't necessarily the
1620  * last parsetree, because rule rewriting can insert queries after what
1621  * the user wrote.
1622  */
1623  parse = NULL;
1624  parse_cell = NULL;
1625  foreach(lc, queryTreeList)
1626  {
1627  Query *q = lfirst_node(Query, lc);
1628 
1629  if (q->canSetTag)
1630  {
1631  parse = q;
1632  parse_cell = lc;
1633  }
1634  }
1635 
1636  /*
1637  * If it's a plain SELECT, it returns whatever the targetlist says.
1638  * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1639  * that. Otherwise, the function return type must be VOID.
1640  *
1641  * Note: eventually replace this test with QueryReturnsTuples? We'd need
1642  * a more general method of determining the output type, though. Also, it
1643  * seems too dangerous to consider FETCH or EXECUTE as returning a
1644  * determinable rowtype, since they depend on relatively short-lived
1645  * entities.
1646  */
1647  if (parse &&
1648  parse->commandType == CMD_SELECT)
1649  {
1650  tlist = parse->targetList;
1651  /* tlist is modifiable unless it's a dummy in a setop query */
1652  tlist_is_modifiable = (parse->setOperations == NULL);
1653  }
1654  else if (parse &&
1655  (parse->commandType == CMD_INSERT ||
1656  parse->commandType == CMD_UPDATE ||
1657  parse->commandType == CMD_DELETE) &&
1658  parse->returningList)
1659  {
1660  tlist = parse->returningList;
1661  /* returningList can always be modified */
1662  tlist_is_modifiable = true;
1663  }
1664  else
1665  {
1666  /* Empty function body, or last statement is a utility command */
1667  ereport(ERROR,
1668  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1669  errmsg("return type mismatch in function declared to return %s",
1670  format_type_be(rettype)),
1671  errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1672  return false; /* keep compiler quiet */
1673  }
1674 
1675  /*
1676  * OK, check that the targetlist returns something matching the declared
1677  * type, and modify it if necessary. If possible, we insert any coercion
1678  * steps right into the final statement's targetlist. However, that might
1679  * risk changes in the statement's semantics --- we can't safely change
1680  * the output type of a grouping column, for instance. In such cases we
1681  * handle coercions by inserting an extra level of Query that effectively
1682  * just does a projection.
1683  */
1684 
1685  /*
1686  * Count the non-junk entries in the result targetlist.
1687  */
1688  tlistlen = ExecCleanTargetListLength(tlist);
1689 
1690  fn_typtype = get_typtype(rettype);
1691 
1692  if (fn_typtype == TYPTYPE_BASE ||
1693  fn_typtype == TYPTYPE_DOMAIN ||
1694  fn_typtype == TYPTYPE_ENUM ||
1695  fn_typtype == TYPTYPE_RANGE)
1696  {
1697  /*
1698  * For scalar-type returns, the target list must have exactly one
1699  * non-junk entry, and its type must be coercible to rettype.
1700  */
1701  TargetEntry *tle;
1702 
1703  if (tlistlen != 1)
1704  ereport(ERROR,
1705  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1706  errmsg("return type mismatch in function declared to return %s",
1707  format_type_be(rettype)),
1708  errdetail("Final statement must return exactly one column.")));
1709 
1710  /* We assume here that non-junk TLEs must come first in tlists */
1711  tle = (TargetEntry *) linitial(tlist);
1712  Assert(!tle->resjunk);
1713 
1714  if (!coerce_fn_result_column(tle, rettype, -1,
1715  tlist_is_modifiable,
1716  &upper_tlist,
1717  &upper_tlist_nontrivial))
1718  ereport(ERROR,
1719  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1720  errmsg("return type mismatch in function declared to return %s",
1721  format_type_be(rettype)),
1722  errdetail("Actual return type is %s.",
1723  format_type_be(exprType((Node *) tle->expr)))));
1724  }
1725  else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1726  {
1727  /*
1728  * Returns a rowtype.
1729  *
1730  * Note that we will not consider a domain over composite to be a
1731  * "rowtype" return type; it goes through the scalar case above. This
1732  * is because we only provide column-by-column implicit casting, and
1733  * will not cast the complete record result. So the only way to
1734  * produce a domain-over-composite result is to compute it as an
1735  * explicit single-column result. The single-composite-column code
1736  * path just below could handle such cases, but it won't be reached.
1737  */
1738  int tupnatts; /* physical number of columns in tuple */
1739  int tuplogcols; /* # of nondeleted columns in tuple */
1740  int colindex; /* physical column index */
1741 
1742  /*
1743  * If the target list has one non-junk entry, and that expression has
1744  * or can be coerced to the declared return type, take it as the
1745  * result. This allows, for example, 'SELECT func2()', where func2
1746  * has the same composite return type as the function that's calling
1747  * it. This provision creates some ambiguity --- maybe the expression
1748  * was meant to be the lone field of the composite result --- but it
1749  * works well enough as long as we don't get too enthusiastic about
1750  * inventing coercions from scalar to composite types.
1751  *
1752  * XXX Note that if rettype is RECORD and the expression is of a named
1753  * composite type, or vice versa, this coercion will succeed, whether
1754  * or not the record type really matches. For the moment we rely on
1755  * runtime type checking to catch any discrepancy, but it'd be nice to
1756  * do better at parse time.
1757  */
1758  if (tlistlen == 1)
1759  {
1760  TargetEntry *tle = (TargetEntry *) linitial(tlist);
1761 
1762  Assert(!tle->resjunk);
1763  if (coerce_fn_result_column(tle, rettype, -1,
1764  tlist_is_modifiable,
1765  &upper_tlist,
1766  &upper_tlist_nontrivial))
1767  {
1768  /* Note that we're NOT setting is_tuple_result */
1769  goto tlist_coercion_finished;
1770  }
1771  }
1772 
1773  /*
1774  * If the caller didn't provide an expected tupdesc, we can't do any
1775  * further checking. Assume we're returning the whole tuple.
1776  */
1777  if (rettupdesc == NULL)
1778  {
1779  /* Return tlist if requested */
1780  if (resultTargetList)
1781  *resultTargetList = tlist;
1782  return true;
1783  }
1784 
1785  /*
1786  * Verify that the targetlist matches the return tuple type. We scan
1787  * the non-resjunk columns, and coerce them if necessary to match the
1788  * datatypes of the non-deleted attributes. For deleted attributes,
1789  * insert NULL result columns if the caller asked for that.
1790  */
1791  tupnatts = rettupdesc->natts;
1792  tuplogcols = 0; /* we'll count nondeleted cols as we go */
1793  colindex = 0;
1794 
1795  foreach(lc, tlist)
1796  {
1797  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1798  Form_pg_attribute attr;
1799 
1800  /* resjunk columns can simply be ignored */
1801  if (tle->resjunk)
1802  continue;
1803 
1804  do
1805  {
1806  colindex++;
1807  if (colindex > tupnatts)
1808  ereport(ERROR,
1809  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1810  errmsg("return type mismatch in function declared to return %s",
1811  format_type_be(rettype)),
1812  errdetail("Final statement returns too many columns.")));
1813  attr = TupleDescAttr(rettupdesc, colindex - 1);
1814  if (attr->attisdropped && insertDroppedCols)
1815  {
1816  Expr *null_expr;
1817 
1818  /* The type of the null we insert isn't important */
1819  null_expr = (Expr *) makeConst(INT4OID,
1820  -1,
1821  InvalidOid,
1822  sizeof(int32),
1823  (Datum) 0,
1824  true, /* isnull */
1825  true /* byval */ );
1826  upper_tlist = lappend(upper_tlist,
1827  makeTargetEntry(null_expr,
1828  list_length(upper_tlist) + 1,
1829  NULL,
1830  false));
1831  upper_tlist_nontrivial = true;
1832  }
1833  } while (attr->attisdropped);
1834  tuplogcols++;
1835 
1836  if (!coerce_fn_result_column(tle,
1837  attr->atttypid, attr->atttypmod,
1838  tlist_is_modifiable,
1839  &upper_tlist,
1840  &upper_tlist_nontrivial))
1841  ereport(ERROR,
1842  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1843  errmsg("return type mismatch in function declared to return %s",
1844  format_type_be(rettype)),
1845  errdetail("Final statement returns %s instead of %s at column %d.",
1846  format_type_be(exprType((Node *) tle->expr)),
1847  format_type_be(attr->atttypid),
1848  tuplogcols)));
1849  }
1850 
1851  /* remaining columns in rettupdesc had better all be dropped */
1852  for (colindex++; colindex <= tupnatts; colindex++)
1853  {
1854  if (!TupleDescAttr(rettupdesc, colindex - 1)->attisdropped)
1855  ereport(ERROR,
1856  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1857  errmsg("return type mismatch in function declared to return %s",
1858  format_type_be(rettype)),
1859  errdetail("Final statement returns too few columns.")));
1860  if (insertDroppedCols)
1861  {
1862  Expr *null_expr;
1863 
1864  /* The type of the null we insert isn't important */
1865  null_expr = (Expr *) makeConst(INT4OID,
1866  -1,
1867  InvalidOid,
1868  sizeof(int32),
1869  (Datum) 0,
1870  true, /* isnull */
1871  true /* byval */ );
1872  upper_tlist = lappend(upper_tlist,
1873  makeTargetEntry(null_expr,
1874  list_length(upper_tlist) + 1,
1875  NULL,
1876  false));
1877  upper_tlist_nontrivial = true;
1878  }
1879  }
1880 
1881  /* Report that we are returning entire tuple result */
1882  is_tuple_result = true;
1883  }
1884  else
1885  ereport(ERROR,
1886  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1887  errmsg("return type %s is not supported for SQL functions",
1888  format_type_be(rettype))));
1889 
1890 tlist_coercion_finished:
1891 
1892  /*
1893  * If necessary, modify the final Query by injecting an extra Query level
1894  * that just performs a projection. (It'd be dubious to do this to a
1895  * non-SELECT query, but we never have to; RETURNING lists can always be
1896  * modified in-place.)
1897  */
1898  if (upper_tlist_nontrivial)
1899  {
1900  Query *newquery;
1901  List *colnames;
1902  RangeTblEntry *rte;
1903  RangeTblRef *rtr;
1904 
1905  Assert(parse->commandType == CMD_SELECT);
1906 
1907  /* Most of the upper Query struct can be left as zeroes/nulls */
1908  newquery = makeNode(Query);
1909  newquery->commandType = CMD_SELECT;
1910  newquery->querySource = parse->querySource;
1911  newquery->canSetTag = true;
1912  newquery->targetList = upper_tlist;
1913 
1914  /* We need a moderately realistic colnames list for the subquery RTE */
1915  colnames = NIL;
1916  foreach(lc, parse->targetList)
1917  {
1918  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1919 
1920  if (tle->resjunk)
1921  continue;
1922  colnames = lappend(colnames,
1923  makeString(tle->resname ? tle->resname : ""));
1924  }
1925 
1926  /* Build a suitable RTE for the subquery */
1927  rte = makeNode(RangeTblEntry);
1928  rte->rtekind = RTE_SUBQUERY;
1929  rte->subquery = parse;
1930  rte->eref = rte->alias = makeAlias("*SELECT*", colnames);
1931  rte->lateral = false;
1932  rte->inh = false;
1933  rte->inFromCl = true;
1934  newquery->rtable = list_make1(rte);
1935 
1936  rtr = makeNode(RangeTblRef);
1937  rtr->rtindex = 1;
1938  newquery->jointree = makeFromExpr(list_make1(rtr), NULL);
1939 
1940  /* Replace original query in the correct element of the query list */
1941  lfirst(parse_cell) = newquery;
1942  }
1943 
1944  /* Return tlist (possibly modified) if requested */
1945  if (resultTargetList)
1946  *resultTargetList = upper_tlist;
1947 
1948  return is_tuple_result;
1949 }
1950 
1951 /*
1952  * Process one function result column for check_sql_fn_retval
1953  *
1954  * Coerce the output value to the required type/typmod, and add a column
1955  * to *upper_tlist for it. Set *upper_tlist_nontrivial to true if we
1956  * add an upper tlist item that's not just a Var.
1957  *
1958  * Returns true if OK, false if could not coerce to required type
1959  * (in which case, no changes have been made)
1960  */
1961 static bool
1963  Oid res_type,
1964  int32 res_typmod,
1965  bool tlist_is_modifiable,
1966  List **upper_tlist,
1967  bool *upper_tlist_nontrivial)
1968 {
1969  TargetEntry *new_tle;
1970  Expr *new_tle_expr;
1971  Node *cast_result;
1972 
1973  /*
1974  * If the TLE has a sortgroupref marking, don't change it, as it probably
1975  * is referenced by ORDER BY, DISTINCT, etc, and changing its type would
1976  * break query semantics. Otherwise, it's safe to modify in-place unless
1977  * the query as a whole has issues with that.
1978  */
1979  if (tlist_is_modifiable && src_tle->ressortgroupref == 0)
1980  {
1981  /* OK to modify src_tle in place, if necessary */
1982  cast_result = coerce_to_target_type(NULL,
1983  (Node *) src_tle->expr,
1984  exprType((Node *) src_tle->expr),
1985  res_type, res_typmod,
1988  -1);
1989  if (cast_result == NULL)
1990  return false;
1991  src_tle->expr = (Expr *) cast_result;
1992  /* Make a Var referencing the possibly-modified TLE */
1993  new_tle_expr = (Expr *) makeVarFromTargetEntry(1, src_tle);
1994  }
1995  else
1996  {
1997  /* Any casting must happen in the upper tlist */
1998  Var *var = makeVarFromTargetEntry(1, src_tle);
1999 
2000  cast_result = coerce_to_target_type(NULL,
2001  (Node *) var,
2002  var->vartype,
2003  res_type, res_typmod,
2006  -1);
2007  if (cast_result == NULL)
2008  return false;
2009  /* Did the coercion actually do anything? */
2010  if (cast_result != (Node *) var)
2011  *upper_tlist_nontrivial = true;
2012  new_tle_expr = (Expr *) cast_result;
2013  }
2014  new_tle = makeTargetEntry(new_tle_expr,
2015  list_length(*upper_tlist) + 1,
2016  src_tle->resname, false);
2017  *upper_tlist = lappend(*upper_tlist, new_tle);
2018  return true;
2019 }
2020 
2021 
2022 /*
2023  * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
2024  */
2025 DestReceiver *
2027 {
2028  DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2029 
2030  self->pub.receiveSlot = sqlfunction_receive;
2031  self->pub.rStartup = sqlfunction_startup;
2032  self->pub.rShutdown = sqlfunction_shutdown;
2033  self->pub.rDestroy = sqlfunction_destroy;
2034  self->pub.mydest = DestSQLFunction;
2035 
2036  /* private fields will be set by postquel_start */
2037 
2038  return (DestReceiver *) self;
2039 }
2040 
2041 /*
2042  * sqlfunction_startup --- executor startup
2043  */
2044 static void
2045 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2046 {
2047  /* no-op */
2048 }
2049 
2050 /*
2051  * sqlfunction_receive --- receive one tuple
2052  */
2053 static bool
2055 {
2056  DR_sqlfunction *myState = (DR_sqlfunction *) self;
2057 
2058  /* Filter tuple as needed */
2059  slot = ExecFilterJunk(myState->filter, slot);
2060 
2061  /* Store the filtered tuple into the tuplestore */
2062  tuplestore_puttupleslot(myState->tstore, slot);
2063 
2064  return true;
2065 }
2066 
2067 /*
2068  * sqlfunction_shutdown --- executor end
2069  */
2070 static void
2072 {
2073  /* no-op */
2074 }
2075 
2076 /*
2077  * sqlfunction_destroy --- release DestReceiver object
2078  */
2079 static void
2081 {
2082  pfree(self);
2083 }
Value * makeString(char *str)
Definition: value.c:53
bool SubTransactionIsActive(SubTransactionId subxid)
Definition: xact.c:721
signed short int16
Definition: c.h:346
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition: tuplestore.c:708
#define NIL
Definition: pg_list.h:65
Datum value
Definition: params.h:92
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:100
Definition: fmgr.h:56
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:576
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:196
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:1112
FuncExpr * funcexpr
Definition: parsenodes.h:2895
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:2080
MemoryContext fcontext
Definition: functions.c:121
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
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
CommandDest mydest
Definition: dest.h:128
void check_sql_fn_statements(List *queryTreeList)
Definition: functions.c:1510
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:1589
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:863
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
static struct @145 value
ParamKind paramkind
Definition: primnodes.h:262
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
ExecStatus status
Definition: functions.c:66
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag)
Definition: utility.c:504
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
int errcode(int sqlerrcode)
Definition: elog.c:608
TupleTableSlot * jf_resultSlot
Definition: execnodes.h:369
char get_typtype(Oid typid)
Definition: lsyscache.c:2407
static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: functions.c:2045
JunkFilter * junkFilter
Definition: functions.c:111
Oid get_call_expr_argtype(Node *expr, int argnum)
Definition: fmgr.c:1821
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
Definition: functions.c:806
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:518
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:256
struct ErrorContextCallback * previous
Definition: elog.h:255
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define OidIsValid(objectId)
Definition: c.h:645
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:347
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:91
static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: functions.c:2054
#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:1382
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:78
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:902
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:367
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
int errdetail(const char *fmt,...)
Definition: elog.c:955
ParamListInfo params
Definition: execdesc.h:42
Node * utilityStmt
Definition: plannodes.h:92
int geterrposition(void)
Definition: elog.c:1339
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:1464
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
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:516
Datum fmgr_sql(PG_FUNCTION_ARGS)
Definition: functions.c:1005
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2433
List * returningList
Definition: parsenodes.h:146
#define ereport(elevel, rest)
Definition: elog.h:141
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:236
Datum value
Definition: postgres.h:378
#define AssertArg(condition)
Definition: c.h:741
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2252
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:2026
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:1005
#define TextDatumGetCString(d)
Definition: builtins.h:84
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:2071
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
Oid fn_oid
Definition: fmgr.h:59
Oid get_typcollation(Oid typid)
Definition: lsyscache.c:2823
int allowedModes
Definition: execnodes.h:302
int internalerrquery(const char *query)
Definition: elog.c:1243
CmdType commandType
Definition: parsenodes.h:112
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
int32 paramtypmod
Definition: primnodes.h:265
int location
Definition: parsenodes.h:246
SetFunctionReturnMode returnMode
Definition: execnodes.h:304
static Datum postquel_get_single_result(TupleTableSlot *slot, FunctionCallInfo fcinfo, SQLFunctionCachePtr fcache, MemoryContext resultcontext)
Definition: functions.c:962
#define makeNode(_type_)
Definition: nodes.h:573
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:739
#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:553
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:1962
bool canSetTag
Definition: parsenodes.h:118
static void init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
Definition: functions.c:596
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:2029
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:307
#define DatumGetPointer(X)
Definition: postgres.h:549
RTEKind rtekind
Definition: parsenodes.h:974
DestReceiver * dest
Definition: execdesc.h:41
ExprContext * econtext
Definition: execnodes.h:300
Node * setOperations
Definition: parsenodes.h:165
JunkFilter * filter
Definition: functions.c:46
Query * subquery
Definition: parsenodes.h:1009
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2712
SQLFunctionCache * SQLFunctionCachePtr
Definition: functions.c:128
TupleDesc setDesc
Definition: execnodes.h:308
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
int i
#define errcontext
Definition: elog.h:183
#define NameStr(name)
Definition: c.h:616
Index ressortgroupref
Definition: primnodes.h:1410
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:305
Alias * eref
Definition: parsenodes.h:1113
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:868
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:922
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:1207
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:1223
Tuplestorestate * tstore
Definition: functions.c:44
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857