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  /*
235  * Normal conversion of result. However, if the result is of type
236  * RECORD, we have to set up for that each time through, since it
237  * might be different from last time.
238  */
239  if (proc->result.typoid == RECORDOID)
240  {
241  TupleDesc desc;
242 
243  if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
244  ereport(ERROR,
245  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
246  errmsg("function returning record called in context "
247  "that cannot accept type record")));
248  PLy_output_setup_record(&proc->result, desc, proc);
249  }
250 
251  rv = PLy_output_convert(&proc->result, plrv,
252  &fcinfo->isnull);
253  }
254  }
255  PG_CATCH();
256  {
257  /* Pop old arguments from the stack if they were pushed above */
258  PLy_global_args_pop(proc);
259 
260  Py_XDECREF(plargs);
261  Py_XDECREF(plrv);
262 
263  /*
264  * If there was an error within a SRF, the iterator might not have
265  * been exhausted yet. Clear it so the next invocation of the
266  * function will start the iteration again. (This code is probably
267  * unnecessary now; plpython_srf_cleanup_callback should take care of
268  * cleanup. But it doesn't hurt anything to do it here.)
269  */
270  if (srfstate)
271  {
272  Py_XDECREF(srfstate->iter);
273  srfstate->iter = NULL;
274  /* And drop any saved args; we won't need them */
275  if (srfstate->savedargs)
277  srfstate->savedargs = NULL;
278  }
279 
280  PG_RE_THROW();
281  }
282  PG_END_TRY();
283 
284  error_context_stack = plerrcontext.previous;
285 
286  /* Pop old arguments from the stack if they were pushed above */
287  PLy_global_args_pop(proc);
288 
289  Py_XDECREF(plargs);
290  Py_DECREF(plrv);
291 
292  if (srfstate)
293  {
294  /* We're in a SRF, exit appropriately */
295  if (srfstate->iter == NULL)
296  {
297  /* Iterator exhausted, so we're done */
298  SRF_RETURN_DONE(funcctx);
299  }
300  else if (fcinfo->isnull)
301  SRF_RETURN_NEXT_NULL(funcctx);
302  else
303  SRF_RETURN_NEXT(funcctx, rv);
304  }
305 
306  /* Plain function, just return the Datum value (possibly null) */
307  return rv;
308 }
#define Assert(condition)
Definition: c.h:849
int errdetail(const char *fmt,...)
Definition: elog.c:1203
ErrorContextCallback * error_context_stack
Definition: elog.c:94
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define PG_RE_THROW()
Definition: elog.h:412
#define PG_TRY(...)
Definition: elog.h:371
#define PG_END_TRY(...)
Definition: elog.h:396
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:381
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
@ SFRM_ValuePerCall
Definition: execnodes.h:319
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
#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
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
#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:1215
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
static void PLy_function_drop_args(PLySavedArgs *savedargs)
Definition: plpy_exec.c:584
static void PLy_global_args_push(PLyProcedure *proc)
Definition: plpy_exec.c:613
static PyObject * PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
Definition: plpy_exec.c:435
static void PLy_function_restore_args(PLyProcedure *proc, PLySavedArgs *savedargs)
Definition: plpy_exec.c:544
static PyObject * PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
Definition: plpy_exec.c:1062
static void PLy_global_args_pop(PLyProcedure *proc)
Definition: plpy_exec.c:643
static void plpython_srf_cleanup_callback(void *arg)
Definition: plpy_exec.c:681
static PLySavedArgs * PLy_function_save_args(PLyProcedure *proc)
Definition: plpy_exec.c:498
static void plpython_return_error_callback(void *arg)
Definition: plpy_exec.c:695
void PLy_output_setup_record(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:261
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:296
void(* callback)(void *arg)
Definition: elog.h:297
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:339
int allowedModes
Definition: execnodes.h:337

References ReturnSetInfo::allowedModes, MemoryContextCallback::arg, Assert, ErrorContextCallback::callback, PLySRFState::callback, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, error_context_stack, MemoryContextCallback::func, get_call_result_type(), 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_output_setup_record(), 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, TYPEFUNC_COMPOSITE, 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 321 of file plpy_exec.c.

322 {
323  HeapTuple rv = NULL;
324  PyObject *volatile plargs = NULL;
325  PyObject *volatile plrv = NULL;
326  TriggerData *tdata;
327  TupleDesc rel_descr;
328 
329  Assert(CALLED_AS_TRIGGER(fcinfo));
330  tdata = (TriggerData *) fcinfo->context;
331 
332  /*
333  * Input/output conversion for trigger tuples. We use the result and
334  * result_in fields to store the tuple conversion info. We do this over
335  * again on each call to cover the possibility that the relation's tupdesc
336  * changed since the trigger was last called. The PLy_xxx_setup_func
337  * calls should only happen once, but PLy_input_setup_tuple and
338  * PLy_output_setup_tuple are responsible for not doing repetitive work.
339  */
340  rel_descr = RelationGetDescr(tdata->tg_relation);
341  if (proc->result.typoid != rel_descr->tdtypeid)
342  PLy_output_setup_func(&proc->result, proc->mcxt,
343  rel_descr->tdtypeid,
344  rel_descr->tdtypmod,
345  proc);
346  if (proc->result_in.typoid != rel_descr->tdtypeid)
347  PLy_input_setup_func(&proc->result_in, proc->mcxt,
348  rel_descr->tdtypeid,
349  rel_descr->tdtypmod,
350  proc);
351  PLy_output_setup_tuple(&proc->result, rel_descr, proc);
352  PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
353 
354  /*
355  * If the trigger is called recursively, we must push outer-level
356  * arguments into the stack. This must be immediately before the PG_TRY
357  * to ensure that the corresponding pop happens.
358  */
359  PLy_global_args_push(proc);
360 
361  PG_TRY();
362  {
364 
365  rc = SPI_register_trigger_data(tdata);
366  Assert(rc >= 0);
367 
368  plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
369  plrv = PLy_procedure_call(proc, "TD", plargs);
370 
371  Assert(plrv != NULL);
372 
373  /*
374  * Disconnect from SPI manager
375  */
376  if (SPI_finish() != SPI_OK_FINISH)
377  elog(ERROR, "SPI_finish failed");
378 
379  /*
380  * return of None means we're happy with the tuple
381  */
382  if (plrv != Py_None)
383  {
384  char *srv;
385 
386  if (PyUnicode_Check(plrv))
387  srv = PLyUnicode_AsString(plrv);
388  else
389  {
390  ereport(ERROR,
391  (errcode(ERRCODE_DATA_EXCEPTION),
392  errmsg("unexpected return value from trigger procedure"),
393  errdetail("Expected None or a string.")));
394  srv = NULL; /* keep compiler quiet */
395  }
396 
397  if (pg_strcasecmp(srv, "SKIP") == 0)
398  rv = NULL;
399  else if (pg_strcasecmp(srv, "MODIFY") == 0)
400  {
401  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
403  rv = PLy_modify_tuple(proc, plargs, tdata, rv);
404  else
406  (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
407  }
408  else if (pg_strcasecmp(srv, "OK") != 0)
409  {
410  /*
411  * accept "OK" as an alternative to None; otherwise, raise an
412  * error
413  */
414  ereport(ERROR,
415  (errcode(ERRCODE_DATA_EXCEPTION),
416  errmsg("unexpected return value from trigger procedure"),
417  errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
418  }
419  }
420  }
421  PG_FINALLY();
422  {
423  PLy_global_args_pop(proc);
424  Py_XDECREF(plargs);
425  Py_XDECREF(plrv);
426  }
427  PG_END_TRY();
428 
429  return rv;
430 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:185
#define WARNING
Definition: elog.h:36
#define PG_FINALLY(...)
Definition: elog.h:388
static PyObject * PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
Definition: plpy_exec.c:705
static HeapTuple PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata, HeapTuple otup)
Definition: plpy_exec.c:922
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:3364
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_global_args_pop(), PLy_global_args_push(), 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().