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 55 of file plpy_exec.c.

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

References ReturnSetInfo::allowedModes, MemoryContextCallback::arg, Assert, ErrorContextCallback::callback, PLySRFState::callback, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, error_context_stack, MemoryContextCallback::func, if(), PLyProcedure::is_procedure, PLyProcedure::is_setof, IsA, FunctionCallInfoBaseData::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, FunctionCallInfoBaseData::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 plpython3_call_handler(), and plpython3_inline_handler().

◆ PLy_exec_trigger()

HeapTuple PLy_exec_trigger ( FunctionCallInfo  fcinfo,
PLyProcedure proc 
)

Definition at line 305 of file plpy_exec.c.

306 {
307  HeapTuple rv = NULL;
308  PyObject *volatile plargs = NULL;
309  PyObject *volatile plrv = NULL;
310  TriggerData *tdata;
311  TupleDesc rel_descr;
312 
313  Assert(CALLED_AS_TRIGGER(fcinfo));
314  tdata = (TriggerData *) fcinfo->context;
315 
316  /*
317  * Input/output conversion for trigger tuples. We use the result and
318  * result_in fields to store the tuple conversion info. We do this over
319  * again on each call to cover the possibility that the relation's tupdesc
320  * changed since the trigger was last called. The PLy_xxx_setup_func
321  * calls should only happen once, but PLy_input_setup_tuple and
322  * PLy_output_setup_tuple are responsible for not doing repetitive work.
323  */
324  rel_descr = RelationGetDescr(tdata->tg_relation);
325  if (proc->result.typoid != rel_descr->tdtypeid)
326  PLy_output_setup_func(&proc->result, proc->mcxt,
327  rel_descr->tdtypeid,
328  rel_descr->tdtypmod,
329  proc);
330  if (proc->result_in.typoid != rel_descr->tdtypeid)
331  PLy_input_setup_func(&proc->result_in, proc->mcxt,
332  rel_descr->tdtypeid,
333  rel_descr->tdtypmod,
334  proc);
335  PLy_output_setup_tuple(&proc->result, rel_descr, proc);
336  PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
337 
338  PG_TRY();
339  {
341 
342  rc = SPI_register_trigger_data(tdata);
343  Assert(rc >= 0);
344 
345  plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
346  plrv = PLy_procedure_call(proc, "TD", plargs);
347 
348  Assert(plrv != NULL);
349 
350  /*
351  * Disconnect from SPI manager
352  */
353  if (SPI_finish() != SPI_OK_FINISH)
354  elog(ERROR, "SPI_finish failed");
355 
356  /*
357  * return of None means we're happy with the tuple
358  */
359  if (plrv != Py_None)
360  {
361  char *srv;
362 
363  if (PyUnicode_Check(plrv))
364  srv = PLyUnicode_AsString(plrv);
365  else
366  {
367  ereport(ERROR,
368  (errcode(ERRCODE_DATA_EXCEPTION),
369  errmsg("unexpected return value from trigger procedure"),
370  errdetail("Expected None or a string.")));
371  srv = NULL; /* keep compiler quiet */
372  }
373 
374  if (pg_strcasecmp(srv, "SKIP") == 0)
375  rv = NULL;
376  else if (pg_strcasecmp(srv, "MODIFY") == 0)
377  {
378  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
380  rv = PLy_modify_tuple(proc, plargs, tdata, rv);
381  else
383  (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
384  }
385  else if (pg_strcasecmp(srv, "OK") != 0)
386  {
387  /*
388  * accept "OK" as an alternative to None; otherwise, raise an
389  * error
390  */
391  ereport(ERROR,
392  (errcode(ERRCODE_DATA_EXCEPTION),
393  errmsg("unexpected return value from trigger procedure"),
394  errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
395  }
396  }
397  }
398  PG_FINALLY();
399  {
400  Py_XDECREF(plargs);
401  Py_XDECREF(plrv);
402  }
403  PG_END_TRY();
404 
405  return rv;
406 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:182
#define WARNING
Definition: elog.h:36
#define PG_FINALLY(...)
Definition: elog.h:387
static PyObject * PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
Definition: plpy_exec.c:681
static HeapTuple PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata, HeapTuple otup)
Definition: plpy_exec.c:898
void PLy_output_setup_func(PLyObToDatum *arg, MemoryContext arg_mcxt, Oid typeOid, int32 typmod, PLyProcedure *proc)
Definition: plpy_typeio.c:296
void PLy_input_setup_func(PLyDatumToOb *arg, MemoryContext arg_mcxt, Oid typeOid, int32 typmod, PLyProcedure *proc)
Definition: plpy_typeio.c:418
void PLy_input_setup_tuple(PLyDatumToOb *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:165
void PLy_output_setup_tuple(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:215
char * PLyUnicode_AsString(PyObject *unicode)
Definition: plpy_util.c:83
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define RelationGetDescr(relation)
Definition: rel.h:531
int SPI_register_trigger_data(TriggerData *tdata)
Definition: spi.c:3344
fmNodePtr context
Definition: fmgr.h:88
PLyDatumToOb result_in
MemoryContext mcxt
Relation tg_relation
Definition: trigger.h:35
TriggerEvent tg_event
Definition: trigger.h:34
int32 tdtypmod
Definition: tupdesc.h:83
Oid tdtypeid
Definition: tupdesc.h:82
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:26
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:110
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:116

References Assert, CALLED_AS_TRIGGER, FunctionCallInfoBaseData::context, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, PLyProcedure::mcxt, PG_END_TRY, PG_FINALLY, 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(), TupleDescData::tdtypeid, TupleDescData::tdtypmod, TriggerData::tg_event, TriggerData::tg_relation, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_UPDATE, PLyDatumToOb::typoid, PLyObToDatum::typoid, and WARNING.

Referenced by plpython3_call_handler().