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, and FuncCallContext::user_fctx.

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
203  * return value must be None. For void-returning functions, we also
204  * treat a None return value as a special "void datum" rather than
205  * NULL (as is the case for non-void-returning functions).
206  */
207  if (proc->result.typoid == VOIDOID)
208  {
209  if (plrv != Py_None)
210  {
211  if (proc->is_procedure)
212  ereport(ERROR,
213  (errcode(ERRCODE_DATATYPE_MISMATCH),
214  errmsg("PL/Python procedure did not return None")));
215  else
216  ereport(ERROR,
217  (errcode(ERRCODE_DATATYPE_MISMATCH),
218  errmsg("PL/Python function with return type \"void\" did not return None")));
219  }
220 
221  fcinfo->isnull = false;
222  rv = (Datum) 0;
223  }
224  else if (plrv == Py_None &&
225  srfstate && srfstate->iter == NULL)
226  {
227  /*
228  * In a SETOF function, the iteration-ending null isn't a real
229  * value; don't pass it through the input function, which might
230  * complain.
231  */
232  fcinfo->isnull = true;
233  rv = (Datum) 0;
234  }
235  else
236  {
237  /* Normal conversion of result */
238  rv = PLy_output_convert(&proc->result, plrv,
239  &fcinfo->isnull);
240  }
241  }
242  PG_CATCH();
243  {
244  /* Pop old arguments from the stack if they were pushed above */
245  PLy_global_args_pop(proc);
246 
247  Py_XDECREF(plargs);
248  Py_XDECREF(plrv);
249 
250  /*
251  * If there was an error within a SRF, the iterator might not have
252  * been exhausted yet. Clear it so the next invocation of the
253  * function will start the iteration again. (This code is probably
254  * unnecessary now; plpython_srf_cleanup_callback should take care of
255  * cleanup. But it doesn't hurt anything to do it here.)
256  */
257  if (srfstate)
258  {
259  Py_XDECREF(srfstate->iter);
260  srfstate->iter = NULL;
261  /* And drop any saved args; we won't need them */
262  if (srfstate->savedargs)
264  srfstate->savedargs = NULL;
265  }
266 
267  PG_RE_THROW();
268  }
269  PG_END_TRY();
270 
271  error_context_stack = plerrcontext.previous;
272 
273  /* Pop old arguments from the stack if they were pushed above */
274  PLy_global_args_pop(proc);
275 
276  Py_XDECREF(plargs);
277  Py_DECREF(plrv);
278 
279  if (srfstate)
280  {
281  /* We're in a SRF, exit appropriately */
282  if (srfstate->iter == NULL)
283  {
284  /* Iterator exhausted, so we're done */
285  SRF_RETURN_DONE(funcctx);
286  }
287  else if (fcinfo->isnull)
288  SRF_RETURN_NEXT_NULL(funcctx);
289  else
290  SRF_RETURN_NEXT(funcctx, rv);
291  }
292 
293  /* Plain function, just return the Datum value (possibly null) */
294  return rv;
295 }
MemoryContextCallbackFunction func
Definition: palloc.h:49
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
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:596
static void PLy_global_args_pop(PLyProcedure *proc)
Definition: plpy_exec.c:626
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:294
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:535
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:298
static PyObject * PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
Definition: plpy_exec.c:423
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:300
#define ERROR
Definition: elog.h:43
static void plpython_return_error_callback(void *arg)
Definition: plpy_exec.c:678
#define PLy_elog
static PLySavedArgs * PLy_function_save_args(PLyProcedure *proc)
Definition: plpy_exec.c:496
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define SRF_RETURN_NEXT_NULL(_funcctx)
Definition: funcapi.h:309
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:568
uintptr_t Datum
Definition: postgres.h:367
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:814
int allowedModes
Definition: execnodes.h:297
SetFunctionReturnMode returnMode
Definition: execnodes.h:299
#define PG_CATCH()
Definition: elog.h:293
#define Assert(condition)
Definition: c.h:699
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:285
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:1016
#define PG_END_TRY()
Definition: elog.h:300
static void plpython_srf_cleanup_callback(void *arg)
Definition: plpy_exec.c:664
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:318
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:296

◆ PLy_exec_trigger()

HeapTuple PLy_exec_trigger ( FunctionCallInfo  fcinfo,
PLyProcedure proc 
)

Definition at line 308 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().

309 {
310  HeapTuple rv = NULL;
311  PyObject *volatile plargs = NULL;
312  PyObject *volatile plrv = NULL;
313  TriggerData *tdata;
314  TupleDesc rel_descr;
315 
316  Assert(CALLED_AS_TRIGGER(fcinfo));
317  tdata = (TriggerData *) fcinfo->context;
318 
319  /*
320  * Input/output conversion for trigger tuples. We use the result and
321  * result_in fields to store the tuple conversion info. We do this over
322  * again on each call to cover the possibility that the relation's tupdesc
323  * changed since the trigger was last called. The PLy_xxx_setup_func
324  * calls should only happen once, but PLy_input_setup_tuple and
325  * PLy_output_setup_tuple are responsible for not doing repetitive work.
326  */
327  rel_descr = RelationGetDescr(tdata->tg_relation);
328  if (proc->result.typoid != rel_descr->tdtypeid)
329  PLy_output_setup_func(&proc->result, proc->mcxt,
330  rel_descr->tdtypeid,
331  rel_descr->tdtypmod,
332  proc);
333  if (proc->result_in.typoid != rel_descr->tdtypeid)
334  PLy_input_setup_func(&proc->result_in, proc->mcxt,
335  rel_descr->tdtypeid,
336  rel_descr->tdtypmod,
337  proc);
338  PLy_output_setup_tuple(&proc->result, rel_descr, proc);
339  PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
340 
341  PG_TRY();
342  {
344 
345  rc = SPI_register_trigger_data(tdata);
346  Assert(rc >= 0);
347 
348  plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
349  plrv = PLy_procedure_call(proc, "TD", plargs);
350 
351  Assert(plrv != NULL);
352 
353  /*
354  * Disconnect from SPI manager
355  */
356  if (SPI_finish() != SPI_OK_FINISH)
357  elog(ERROR, "SPI_finish failed");
358 
359  /*
360  * return of None means we're happy with the tuple
361  */
362  if (plrv != Py_None)
363  {
364  char *srv;
365 
366  if (PyString_Check(plrv))
367  srv = PyString_AsString(plrv);
368  else if (PyUnicode_Check(plrv))
369  srv = PLyUnicode_AsString(plrv);
370  else
371  {
372  ereport(ERROR,
373  (errcode(ERRCODE_DATA_EXCEPTION),
374  errmsg("unexpected return value from trigger procedure"),
375  errdetail("Expected None or a string.")));
376  srv = NULL; /* keep compiler quiet */
377  }
378 
379  if (pg_strcasecmp(srv, "SKIP") == 0)
380  rv = NULL;
381  else if (pg_strcasecmp(srv, "MODIFY") == 0)
382  {
383  TriggerData *tdata = (TriggerData *) fcinfo->context;
384 
385  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
387  rv = PLy_modify_tuple(proc, plargs, tdata, rv);
388  else
390  (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
391  }
392  else if (pg_strcasecmp(srv, "OK") != 0)
393  {
394  /*
395  * accept "OK" as an alternative to None; otherwise, raise an
396  * error
397  */
398  ereport(ERROR,
399  (errcode(ERRCODE_DATA_EXCEPTION),
400  errmsg("unexpected return value from trigger procedure"),
401  errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
402  }
403  }
404  }
405  PG_CATCH();
406  {
407  Py_XDECREF(plargs);
408  Py_XDECREF(plrv);
409 
410  PG_RE_THROW();
411  }
412  PG_END_TRY();
413 
414  Py_DECREF(plargs);
415  Py_DECREF(plrv);
416 
417  return rv;
418 }
Oid tdtypeid
Definition: tupdesc.h:83
#define RelationGetDescr(relation)
Definition: rel.h:433
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:879
int32 tdtypmod
Definition: tupdesc.h:84
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:2856
#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:699
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:688
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:1016
#define PG_END_TRY()
Definition: elog.h:300
Relation tg_relation
Definition: trigger.h:34