PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 53 of file plpy_exec.c.

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

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

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