PostgreSQL Source Code  git master
plpy_exec.h File Reference
#include "plpy_procedure.h"
Include dependency graph for plpy_exec.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

Datum PLy_exec_function (FunctionCallInfo fcinfo, PLyProcedure *proc)
 
HeapTuple PLy_exec_trigger (FunctionCallInfo fcinfo, PLyProcedure *proc)
 

Function Documentation

◆ PLy_exec_function()

Datum PLy_exec_function ( FunctionCallInfo  fcinfo,
PLyProcedure proc 
)

Definition at line 58 of file plpy_exec.c.

References ReturnSetInfo::allowedModes, MemoryContextCallback::arg, Assert, PLySRFState::callback, ErrorContextCallback::callback, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, error_context_stack, MemoryContextCallback::func, PLyProcedure::is_procedure, PLyProcedure::is_setof, IsA, FunctionCallInfoData::isnull, PLySRFState::iter, MemoryContextAllocZero(), MemoryContextRegisterResetCallback(), FuncCallContext::multi_call_memory_ctx, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, plpython_return_error_callback(), plpython_srf_cleanup_callback(), PLy_elog, PLy_function_build_args(), PLy_function_drop_args(), PLy_function_restore_args(), PLy_function_save_args(), PLy_global_args_pop(), PLy_global_args_push(), PLy_output_convert(), PLy_procedure_call(), ErrorContextCallback::previous, PLyProcedure::result, FunctionCallInfoData::resultinfo, ReturnSetInfo::returnMode, PLySRFState::savedargs, SFRM_ValuePerCall, SPI_finish(), SPI_OK_FINISH, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, SRF_RETURN_NEXT_NULL, PLyObToDatum::typoid, FuncCallContext::user_fctx, and VOIDOID.

Referenced by plpython_call_handler(), and plpython_inline_handler().

59 {
60  bool is_setof = proc->is_setof;
61  Datum rv;
62  PyObject *volatile plargs = NULL;
63  PyObject *volatile plrv = NULL;
64  FuncCallContext *volatile funcctx = NULL;
65  PLySRFState *volatile srfstate = NULL;
66  ErrorContextCallback plerrcontext;
67 
68  /*
69  * If the function is called recursively, we must push outer-level
70  * arguments into the stack. This must be immediately before the PG_TRY
71  * to ensure that the corresponding pop happens.
72  */
74 
75  PG_TRY();
76  {
77  if (is_setof)
78  {
79  /* First Call setup */
80  if (SRF_IS_FIRSTCALL())
81  {
82  funcctx = SRF_FIRSTCALL_INIT();
83  srfstate = (PLySRFState *)
85  sizeof(PLySRFState));
86  /* Immediately register cleanup callback */
88  srfstate->callback.arg = (void *) srfstate;
90  &srfstate->callback);
91  funcctx->user_fctx = (void *) srfstate;
92  }
93  /* Every call setup */
94  funcctx = SRF_PERCALL_SETUP();
95  Assert(funcctx != NULL);
96  srfstate = (PLySRFState *) funcctx->user_fctx;
97  Assert(srfstate != NULL);
98  }
99 
100  if (srfstate == NULL || srfstate->iter == NULL)
101  {
102  /*
103  * Non-SETOF function or first time for SETOF function: build
104  * args, then actually execute the function.
105  */
106  plargs = PLy_function_build_args(fcinfo, proc);
107  plrv = PLy_procedure_call(proc, "args", plargs);
108  Assert(plrv != NULL);
109  }
110  else
111  {
112  /*
113  * Second or later call for a SETOF function: restore arguments in
114  * globals dict to what they were when we left off. We must do
115  * this in case multiple evaluations of the same SETOF function
116  * are interleaved. It's a bit annoying, since the iterator may
117  * not look at the arguments at all, but we have no way to know
118  * that. Fortunately this isn't terribly expensive.
119  */
120  if (srfstate->savedargs)
121  PLy_function_restore_args(proc, srfstate->savedargs);
122  srfstate->savedargs = NULL; /* deleted by restore_args */
123  }
124 
125  /*
126  * If it returns a set, call the iterator to get the next return item.
127  * We stay in the SPI context while doing this, because PyIter_Next()
128  * calls back into Python code which might contain SPI calls.
129  */
130  if (is_setof)
131  {
132  if (srfstate->iter == NULL)
133  {
134  /* first time -- do checks and setup */
135  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
136 
137  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
138  (rsi->allowedModes & SFRM_ValuePerCall) == 0)
139  {
140  ereport(ERROR,
141  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
142  errmsg("unsupported set function return mode"),
143  errdetail("PL/Python set-returning functions only support returning one value per call.")));
144  }
146 
147  /* Make iterator out of returned object */
148  srfstate->iter = PyObject_GetIter(plrv);
149 
150  Py_DECREF(plrv);
151  plrv = NULL;
152 
153  if (srfstate->iter == NULL)
154  ereport(ERROR,
155  (errcode(ERRCODE_DATATYPE_MISMATCH),
156  errmsg("returned object cannot be iterated"),
157  errdetail("PL/Python set-returning functions must return an iterable object.")));
158  }
159 
160  /* Fetch next from iterator */
161  plrv = PyIter_Next(srfstate->iter);
162  if (plrv == NULL)
163  {
164  /* Iterator is exhausted or error happened */
165  bool has_error = (PyErr_Occurred() != NULL);
166 
167  Py_DECREF(srfstate->iter);
168  srfstate->iter = NULL;
169 
170  if (has_error)
171  PLy_elog(ERROR, "error fetching next item from iterator");
172 
173  /* Pass a null through the data-returning steps below */
174  Py_INCREF(Py_None);
175  plrv = Py_None;
176  }
177  else
178  {
179  /*
180  * This won't be last call, so save argument values. We do
181  * this again each time in case the iterator is changing those
182  * values.
183  */
184  srfstate->savedargs = PLy_function_save_args(proc);
185  }
186  }
187 
188  /*
189  * Disconnect from SPI manager and then create the return values datum
190  * (if the input function does a palloc for it this must not be
191  * allocated in the SPI memory context because SPI_finish would free
192  * it).
193  */
194  if (SPI_finish() != SPI_OK_FINISH)
195  elog(ERROR, "SPI_finish failed");
196 
198  plerrcontext.previous = error_context_stack;
199  error_context_stack = &plerrcontext;
200 
201  /*
202  * For a procedure or function declared to return void, the Python return value
203  * must be None. For void-returning functions, we also treat a None
204  * return value as a special "void datum" rather than NULL (as is the
205  * case for non-void-returning functions).
206  */
207  if (proc->is_procedure)
208  {
209  if (plrv != Py_None)
210  ereport(ERROR,
211  (errcode(ERRCODE_DATATYPE_MISMATCH),
212  errmsg("PL/Python procedure did not return None")));
213  fcinfo->isnull = false;
214  rv = (Datum) 0;
215  }
216  else if (proc->result.typoid == VOIDOID)
217  {
218  if (plrv != Py_None)
219  ereport(ERROR,
220  (errcode(ERRCODE_DATATYPE_MISMATCH),
221  errmsg("PL/Python function with return type \"void\" did not return None")));
222 
223  fcinfo->isnull = false;
224  rv = (Datum) 0;
225  }
226  else if (plrv == Py_None &&
227  srfstate && srfstate->iter == NULL)
228  {
229  /*
230  * In a SETOF function, the iteration-ending null isn't a real
231  * value; don't pass it through the input function, which might
232  * complain.
233  */
234  fcinfo->isnull = true;
235  rv = (Datum) 0;
236  }
237  else
238  {
239  /* Normal conversion of result */
240  rv = PLy_output_convert(&proc->result, plrv,
241  &fcinfo->isnull);
242  }
243  }
244  PG_CATCH();
245  {
246  /* Pop old arguments from the stack if they were pushed above */
247  PLy_global_args_pop(proc);
248 
249  Py_XDECREF(plargs);
250  Py_XDECREF(plrv);
251 
252  /*
253  * If there was an error within a SRF, the iterator might not have
254  * been exhausted yet. Clear it so the next invocation of the
255  * function will start the iteration again. (This code is probably
256  * unnecessary now; plpython_srf_cleanup_callback should take care of
257  * cleanup. But it doesn't hurt anything to do it here.)
258  */
259  if (srfstate)
260  {
261  Py_XDECREF(srfstate->iter);
262  srfstate->iter = NULL;
263  /* And drop any saved args; we won't need them */
264  if (srfstate->savedargs)
266  srfstate->savedargs = NULL;
267  }
268 
269  PG_RE_THROW();
270  }
271  PG_END_TRY();
272 
273  error_context_stack = plerrcontext.previous;
274 
275  /* Pop old arguments from the stack if they were pushed above */
276  PLy_global_args_pop(proc);
277 
278  Py_XDECREF(plargs);
279  Py_DECREF(plrv);
280 
281  if (srfstate)
282  {
283  /* We're in a SRF, exit appropriately */
284  if (srfstate->iter == NULL)
285  {
286  /* Iterator exhausted, so we're done */
287  SRF_RETURN_DONE(funcctx);
288  }
289  else if (fcinfo->isnull)
290  SRF_RETURN_NEXT_NULL(funcctx);
291  else
292  SRF_RETURN_NEXT(funcctx, rv);
293  }
294 
295  /* Plain function, just return the Datum value (possibly null) */
296  return rv;
297 }
MemoryContextCallbackFunction func
Definition: palloc.h:49
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
Datum PLy_output_convert(PLyObToDatum *arg, PyObject *val, bool *isnull)
Definition: plpy_typeio.c:123
static void PLy_global_args_push(PLyProcedure *proc)
Definition: plpy_exec.c:598
static void PLy_global_args_pop(PLyProcedure *proc)
Definition: plpy_exec.c:628
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:293
int SPI_finish(void)
Definition: spi.c:161
int errcode(int sqlerrcode)
Definition: elog.c:575
static void PLy_function_restore_args(PLyProcedure *proc, PLySavedArgs *savedargs)
Definition: plpy_exec.c:537
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:297
static PyObject * PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
Definition: plpy_exec.c:425
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:299
#define VOIDOID
Definition: pg_type.h:690
#define ERROR
Definition: elog.h:43
static void plpython_return_error_callback(void *arg)
Definition: plpy_exec.c:680
static PLySavedArgs * PLy_function_save_args(PLyProcedure *proc)
Definition: plpy_exec.c:498
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define SRF_RETURN_NEXT_NULL(_funcctx)
Definition: funcapi.h:308
fmNodePtr resultinfo
Definition: fmgr.h:81
#define ereport(elevel, rest)
Definition: elog.h:122
static void PLy_function_drop_args(PLySavedArgs *savedargs)
Definition: plpy_exec.c:570
#define PLy_elog
Definition: plpy_elog.h:36
uintptr_t Datum
Definition: postgres.h:365
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:728
int allowedModes
Definition: execnodes.h:282
SetFunctionReturnMode returnMode
Definition: execnodes.h:284
#define PG_CATCH()
Definition: elog.h:293
#define Assert(condition)
Definition: c.h:688
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:110
#define SPI_OK_FINISH
Definition: spi.h:51
#define PG_RE_THROW()
Definition: elog.h:314
PLyObToDatum result
void * user_fctx
Definition: funcapi.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:797
PyObject * iter
Definition: plpy_exec.c:32
void MemoryContextRegisterResetCallback(MemoryContext context, MemoryContextCallback *cb)
Definition: mcxt.c:265
PLySavedArgs * savedargs
Definition: plpy_exec.c:33
MemoryContextCallback callback
Definition: plpy_exec.c:34
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
static PyObject * PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
Definition: plpy_exec.c:1018
#define PG_END_TRY()
Definition: elog.h:300
static void plpython_srf_cleanup_callback(void *arg)
Definition: plpy_exec.c:666
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:317
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:295

◆ PLy_exec_trigger()

HeapTuple PLy_exec_trigger ( FunctionCallInfo  fcinfo,
PLyProcedure proc 
)

Definition at line 310 of file plpy_exec.c.

References Assert, CALLED_AS_TRIGGER, FunctionCallInfoData::context, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, PLyProcedure::mcxt, PG_CATCH, PG_END_TRY, PG_RE_THROW, pg_strcasecmp(), PG_TRY, PG_USED_FOR_ASSERTS_ONLY, PLy_input_setup_func(), PLy_input_setup_tuple(), PLy_modify_tuple(), PLy_output_setup_func(), PLy_output_setup_tuple(), PLy_procedure_call(), PLy_trigger_build_args(), PLyUnicode_AsString(), RelationGetDescr, PLyProcedure::result, PLyProcedure::result_in, SPI_finish(), SPI_OK_FINISH, SPI_register_trigger_data(), tupleDesc::tdtypeid, tupleDesc::tdtypmod, TriggerData::tg_event, TriggerData::tg_relation, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_UPDATE, PLyDatumToOb::typoid, PLyObToDatum::typoid, and WARNING.

Referenced by plpython_call_handler().

311 {
312  HeapTuple rv = NULL;
313  PyObject *volatile plargs = NULL;
314  PyObject *volatile plrv = NULL;
315  TriggerData *tdata;
316  TupleDesc rel_descr;
317 
318  Assert(CALLED_AS_TRIGGER(fcinfo));
319  tdata = (TriggerData *) fcinfo->context;
320 
321  /*
322  * Input/output conversion for trigger tuples. We use the result and
323  * result_in fields to store the tuple conversion info. We do this over
324  * again on each call to cover the possibility that the relation's tupdesc
325  * changed since the trigger was last called. The PLy_xxx_setup_func
326  * calls should only happen once, but PLy_input_setup_tuple and
327  * PLy_output_setup_tuple are responsible for not doing repetitive work.
328  */
329  rel_descr = RelationGetDescr(tdata->tg_relation);
330  if (proc->result.typoid != rel_descr->tdtypeid)
331  PLy_output_setup_func(&proc->result, proc->mcxt,
332  rel_descr->tdtypeid,
333  rel_descr->tdtypmod,
334  proc);
335  if (proc->result_in.typoid != rel_descr->tdtypeid)
336  PLy_input_setup_func(&proc->result_in, proc->mcxt,
337  rel_descr->tdtypeid,
338  rel_descr->tdtypmod,
339  proc);
340  PLy_output_setup_tuple(&proc->result, rel_descr, proc);
341  PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
342 
343  PG_TRY();
344  {
346 
347  rc = SPI_register_trigger_data(tdata);
348  Assert(rc >= 0);
349 
350  plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
351  plrv = PLy_procedure_call(proc, "TD", plargs);
352 
353  Assert(plrv != NULL);
354 
355  /*
356  * Disconnect from SPI manager
357  */
358  if (SPI_finish() != SPI_OK_FINISH)
359  elog(ERROR, "SPI_finish failed");
360 
361  /*
362  * return of None means we're happy with the tuple
363  */
364  if (plrv != Py_None)
365  {
366  char *srv;
367 
368  if (PyString_Check(plrv))
369  srv = PyString_AsString(plrv);
370  else if (PyUnicode_Check(plrv))
371  srv = PLyUnicode_AsString(plrv);
372  else
373  {
374  ereport(ERROR,
375  (errcode(ERRCODE_DATA_EXCEPTION),
376  errmsg("unexpected return value from trigger procedure"),
377  errdetail("Expected None or a string.")));
378  srv = NULL; /* keep compiler quiet */
379  }
380 
381  if (pg_strcasecmp(srv, "SKIP") == 0)
382  rv = NULL;
383  else if (pg_strcasecmp(srv, "MODIFY") == 0)
384  {
385  TriggerData *tdata = (TriggerData *) fcinfo->context;
386 
387  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
389  rv = PLy_modify_tuple(proc, plargs, tdata, rv);
390  else
392  (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
393  }
394  else if (pg_strcasecmp(srv, "OK") != 0)
395  {
396  /*
397  * accept "OK" as an alternative to None; otherwise, raise an
398  * error
399  */
400  ereport(ERROR,
401  (errcode(ERRCODE_DATA_EXCEPTION),
402  errmsg("unexpected return value from trigger procedure"),
403  errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
404  }
405  }
406  }
407  PG_CATCH();
408  {
409  Py_XDECREF(plargs);
410  Py_XDECREF(plrv);
411 
412  PG_RE_THROW();
413  }
414  PG_END_TRY();
415 
416  Py_DECREF(plargs);
417  Py_DECREF(plrv);
418 
419  return rv;
420 }
Oid tdtypeid
Definition: tupdesc.h:80
#define RelationGetDescr(relation)
Definition: rel.h:437
fmNodePtr context
Definition: fmgr.h:80
int SPI_finish(void)
Definition: spi.c:161
int errcode(int sqlerrcode)
Definition: elog.c:575
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
static HeapTuple PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata, HeapTuple otup)
Definition: plpy_exec.c:881
int32 tdtypmod
Definition: tupdesc.h:81
char * PLyUnicode_AsString(PyObject *unicode)
Definition: plpy_util.c:93
#define ERROR
Definition: elog.h:43
MemoryContext mcxt
void PLy_input_setup_tuple(PLyDatumToOb *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:168
int errdetail(const char *fmt,...)
Definition: elog.c:873
void PLy_input_setup_func(PLyDatumToOb *arg, MemoryContext arg_mcxt, Oid typeOid, int32 typmod, PLyProcedure *proc)
Definition: plpy_typeio.c:421
#define ereport(elevel, rest)
Definition: elog.h:122
int SPI_register_trigger_data(TriggerData *tdata)
Definition: spi.c:2844
#define WARNING
Definition: elog.h:40
void PLy_output_setup_tuple(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:218
#define PG_CATCH()
Definition: elog.h:293
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define Assert(condition)
Definition: c.h:688
TriggerEvent tg_event
Definition: trigger.h:33
PLyDatumToOb result_in
#define SPI_OK_FINISH
Definition: spi.h:51
#define PG_RE_THROW()
Definition: elog.h:314
void PLy_output_setup_func(PLyObToDatum *arg, MemoryContext arg_mcxt, Oid typeOid, int32 typmod, PLyProcedure *proc)
Definition: plpy_typeio.c:299
PLyObToDatum result
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:116
static PyObject * PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
Definition: plpy_exec.c:690
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
#define PG_TRY()
Definition: elog.h:284
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
static PyObject * PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
Definition: plpy_exec.c:1018
#define PG_END_TRY()
Definition: elog.h:300
Relation tg_relation
Definition: trigger.h:34