Line data Source code
1 : /*
2 : * executing Python code
3 : *
4 : * src/pl/plpython/plpy_exec.c
5 : */
6 :
7 : #include "postgres.h"
8 :
9 : #include "access/htup_details.h"
10 : #include "access/xact.h"
11 : #include "catalog/pg_type.h"
12 : #include "commands/event_trigger.h"
13 : #include "commands/trigger.h"
14 : #include "executor/spi.h"
15 : #include "funcapi.h"
16 : #include "plpy_elog.h"
17 : #include "plpy_exec.h"
18 : #include "plpy_main.h"
19 : #include "plpy_procedure.h"
20 : #include "plpy_subxactobject.h"
21 : #include "plpy_util.h"
22 : #include "utils/fmgrprotos.h"
23 : #include "utils/rel.h"
24 :
25 : /* saved state for a set-returning function */
26 : typedef struct PLySRFState
27 : {
28 : PyObject *iter; /* Python iterator producing results */
29 : PLySavedArgs *savedargs; /* function argument values */
30 : MemoryContextCallback callback; /* for releasing refcounts when done */
31 : } PLySRFState;
32 :
33 : static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc);
34 : static PLySavedArgs *PLy_function_save_args(PLyProcedure *proc);
35 : static void PLy_function_restore_args(PLyProcedure *proc, PLySavedArgs *savedargs);
36 : static void PLy_function_drop_args(PLySavedArgs *savedargs);
37 : static void PLy_global_args_push(PLyProcedure *proc);
38 : static void PLy_global_args_pop(PLyProcedure *proc);
39 : static void plpython_srf_cleanup_callback(void *arg);
40 : static void plpython_return_error_callback(void *arg);
41 :
42 : static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc,
43 : HeapTuple *rv);
44 : static HeapTuple PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd,
45 : TriggerData *tdata, HeapTuple otup);
46 : static void plpython_trigger_error_callback(void *arg);
47 :
48 : static PyObject *PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs);
49 : static void PLy_abort_open_subtransactions(int save_subxact_level);
50 :
51 :
52 : /* function subhandler */
53 : Datum
54 1320 : PLy_exec_function(FunctionCallInfo fcinfo, PLyProcedure *proc)
55 : {
56 1320 : bool is_setof = proc->is_setof;
57 : Datum rv;
58 1320 : PyObject *volatile plargs = NULL;
59 1320 : PyObject *volatile plrv = NULL;
60 1320 : FuncCallContext *volatile funcctx = NULL;
61 1320 : PLySRFState *volatile srfstate = NULL;
62 : ErrorContextCallback plerrcontext;
63 :
64 : /*
65 : * If the function is called recursively, we must push outer-level
66 : * arguments into the stack. This must be immediately before the PG_TRY
67 : * to ensure that the corresponding pop happens.
68 : */
69 1320 : PLy_global_args_push(proc);
70 :
71 1320 : PG_TRY();
72 : {
73 1320 : if (is_setof)
74 : {
75 : /* First Call setup */
76 400 : if (SRF_IS_FIRSTCALL())
77 : {
78 106 : funcctx = SRF_FIRSTCALL_INIT();
79 106 : srfstate = (PLySRFState *)
80 106 : MemoryContextAllocZero(funcctx->multi_call_memory_ctx,
81 : sizeof(PLySRFState));
82 : /* Immediately register cleanup callback */
83 106 : srfstate->callback.func = plpython_srf_cleanup_callback;
84 106 : srfstate->callback.arg = srfstate;
85 106 : MemoryContextRegisterResetCallback(funcctx->multi_call_memory_ctx,
86 106 : &srfstate->callback);
87 106 : funcctx->user_fctx = srfstate;
88 : }
89 : /* Every call setup */
90 400 : funcctx = SRF_PERCALL_SETUP();
91 : Assert(funcctx != NULL);
92 400 : srfstate = (PLySRFState *) funcctx->user_fctx;
93 : Assert(srfstate != NULL);
94 : }
95 :
96 1320 : if (srfstate == NULL || srfstate->iter == NULL)
97 : {
98 : /*
99 : * Non-SETOF function or first time for SETOF function: build
100 : * args, then actually execute the function.
101 : */
102 1026 : plargs = PLy_function_build_args(fcinfo, proc);
103 1026 : plrv = PLy_procedure_call(proc, "args", plargs);
104 918 : Assert(plrv != NULL);
105 : }
106 : else
107 : {
108 : /*
109 : * Second or later call for a SETOF function: restore arguments in
110 : * globals dict to what they were when we left off. We must do
111 : * this in case multiple evaluations of the same SETOF function
112 : * are interleaved. It's a bit annoying, since the iterator may
113 : * not look at the arguments at all, but we have no way to know
114 : * that. Fortunately this isn't terribly expensive.
115 : */
116 294 : if (srfstate->savedargs)
117 294 : PLy_function_restore_args(proc, srfstate->savedargs);
118 294 : srfstate->savedargs = NULL; /* deleted by restore_args */
119 : }
120 :
121 : /*
122 : * If it returns a set, call the iterator to get the next return item.
123 : * We stay in the SPI context while doing this, because PyIter_Next()
124 : * calls back into Python code which might contain SPI calls.
125 : */
126 1212 : if (is_setof)
127 : {
128 398 : if (srfstate->iter == NULL)
129 : {
130 : /* first time -- do checks and setup */
131 104 : ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
132 :
133 104 : if (!rsi || !IsA(rsi, ReturnSetInfo) ||
134 104 : (rsi->allowedModes & SFRM_ValuePerCall) == 0)
135 : {
136 0 : ereport(ERROR,
137 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
138 : errmsg("unsupported set function return mode"),
139 : errdetail("PL/Python set-returning functions only support returning one value per call.")));
140 : }
141 104 : rsi->returnMode = SFRM_ValuePerCall;
142 :
143 : /* Make iterator out of returned object */
144 104 : srfstate->iter = PyObject_GetIter(plrv);
145 :
146 104 : Py_DECREF(plrv);
147 104 : plrv = NULL;
148 :
149 104 : if (srfstate->iter == NULL)
150 2 : ereport(ERROR,
151 : (errcode(ERRCODE_DATATYPE_MISMATCH),
152 : errmsg("returned object cannot be iterated"),
153 : errdetail("PL/Python set-returning functions must return an iterable object.")));
154 : }
155 :
156 : /* Fetch next from iterator */
157 396 : plrv = PyIter_Next(srfstate->iter);
158 396 : if (plrv == NULL)
159 : {
160 : /* Iterator is exhausted or error happened */
161 98 : bool has_error = (PyErr_Occurred() != NULL);
162 :
163 98 : Py_DECREF(srfstate->iter);
164 98 : srfstate->iter = NULL;
165 :
166 98 : if (has_error)
167 2 : PLy_elog(ERROR, "error fetching next item from iterator");
168 :
169 : /* Pass a null through the data-returning steps below */
170 96 : Py_INCREF(Py_None);
171 96 : plrv = Py_None;
172 : }
173 : else
174 : {
175 : /*
176 : * This won't be last call, so save argument values. We do
177 : * this again each time in case the iterator is changing those
178 : * values.
179 : */
180 298 : srfstate->savedargs = PLy_function_save_args(proc);
181 : }
182 : }
183 :
184 : /*
185 : * Disconnect from SPI manager and then create the return values datum
186 : * (if the input function does a palloc for it this must not be
187 : * allocated in the SPI memory context because SPI_finish would free
188 : * it).
189 : */
190 1208 : if (SPI_finish() != SPI_OK_FINISH)
191 0 : elog(ERROR, "SPI_finish failed");
192 :
193 1208 : plerrcontext.callback = plpython_return_error_callback;
194 1208 : plerrcontext.previous = error_context_stack;
195 1208 : error_context_stack = &plerrcontext;
196 :
197 : /*
198 : * For a procedure or function declared to return void, the Python
199 : * return value must be None. For void-returning functions, we also
200 : * treat a None return value as a special "void datum" rather than
201 : * NULL (as is the case for non-void-returning functions).
202 : */
203 1208 : if (proc->result.typoid == VOIDOID)
204 : {
205 58 : if (plrv != Py_None)
206 : {
207 4 : if (proc->is_procedure)
208 2 : ereport(ERROR,
209 : (errcode(ERRCODE_DATATYPE_MISMATCH),
210 : errmsg("PL/Python procedure did not return None")));
211 : else
212 2 : ereport(ERROR,
213 : (errcode(ERRCODE_DATATYPE_MISMATCH),
214 : errmsg("PL/Python function with return type \"void\" did not return None")));
215 : }
216 :
217 54 : fcinfo->isnull = false;
218 54 : rv = (Datum) 0;
219 : }
220 1150 : else if (plrv == Py_None &&
221 110 : srfstate && srfstate->iter == NULL)
222 : {
223 : /*
224 : * In a SETOF function, the iteration-ending null isn't a real
225 : * value; don't pass it through the input function, which might
226 : * complain.
227 : */
228 96 : fcinfo->isnull = true;
229 96 : rv = (Datum) 0;
230 : }
231 : else
232 : {
233 : /*
234 : * Normal conversion of result. However, if the result is of type
235 : * RECORD, we have to set up for that each time through, since it
236 : * might be different from last time.
237 : */
238 1054 : if (proc->result.typoid == RECORDOID)
239 : {
240 : TupleDesc desc;
241 :
242 268 : if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
243 0 : ereport(ERROR,
244 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
245 : errmsg("function returning record called in context "
246 : "that cannot accept type record")));
247 268 : PLy_output_setup_record(&proc->result, desc, proc);
248 : }
249 :
250 1054 : rv = PLy_output_convert(&proc->result, plrv,
251 : &fcinfo->isnull);
252 : }
253 : }
254 184 : PG_CATCH();
255 : {
256 : /* Pop old arguments from the stack if they were pushed above */
257 184 : PLy_global_args_pop(proc);
258 :
259 184 : Py_XDECREF(plargs);
260 184 : Py_XDECREF(plrv);
261 :
262 : /*
263 : * If there was an error within a SRF, the iterator might not have
264 : * been exhausted yet. Clear it so the next invocation of the
265 : * function will start the iteration again. (This code is probably
266 : * unnecessary now; plpython_srf_cleanup_callback should take care of
267 : * cleanup. But it doesn't hurt anything to do it here.)
268 : */
269 184 : if (srfstate)
270 : {
271 10 : Py_XDECREF(srfstate->iter);
272 10 : srfstate->iter = NULL;
273 : /* And drop any saved args; we won't need them */
274 10 : if (srfstate->savedargs)
275 4 : PLy_function_drop_args(srfstate->savedargs);
276 10 : srfstate->savedargs = NULL;
277 : }
278 :
279 184 : PG_RE_THROW();
280 : }
281 1136 : PG_END_TRY();
282 :
283 1136 : error_context_stack = plerrcontext.previous;
284 :
285 : /* Pop old arguments from the stack if they were pushed above */
286 1136 : PLy_global_args_pop(proc);
287 :
288 1136 : Py_XDECREF(plargs);
289 1136 : Py_DECREF(plrv);
290 :
291 1136 : if (srfstate)
292 : {
293 : /* We're in a SRF, exit appropriately */
294 390 : if (srfstate->iter == NULL)
295 : {
296 : /* Iterator exhausted, so we're done */
297 96 : SRF_RETURN_DONE(funcctx);
298 : }
299 294 : else if (fcinfo->isnull)
300 14 : SRF_RETURN_NEXT_NULL(funcctx);
301 : else
302 280 : SRF_RETURN_NEXT(funcctx, rv);
303 : }
304 :
305 : /* Plain function, just return the Datum value (possibly null) */
306 746 : return rv;
307 : }
308 :
309 : /* trigger subhandler
310 : *
311 : * the python function is expected to return Py_None if the tuple is
312 : * acceptable and unmodified. Otherwise it should return a PyUnicode
313 : * object who's value is SKIP, or MODIFY. SKIP means don't perform
314 : * this action. MODIFY means the tuple has been modified, so update
315 : * tuple and perform action. SKIP and MODIFY assume the trigger fires
316 : * BEFORE the event and is ROW level. postgres expects the function
317 : * to take no arguments and return an argument of type trigger.
318 : */
319 : HeapTuple
320 98 : PLy_exec_trigger(FunctionCallInfo fcinfo, PLyProcedure *proc)
321 : {
322 98 : HeapTuple rv = NULL;
323 98 : PyObject *volatile plargs = NULL;
324 98 : PyObject *volatile plrv = NULL;
325 : TriggerData *tdata;
326 : TupleDesc rel_descr;
327 :
328 : Assert(CALLED_AS_TRIGGER(fcinfo));
329 98 : tdata = (TriggerData *) fcinfo->context;
330 :
331 : /*
332 : * Input/output conversion for trigger tuples. We use the result and
333 : * result_in fields to store the tuple conversion info. We do this over
334 : * again on each call to cover the possibility that the relation's tupdesc
335 : * changed since the trigger was last called. The PLy_xxx_setup_func
336 : * calls should only happen once, but PLy_input_setup_tuple and
337 : * PLy_output_setup_tuple are responsible for not doing repetitive work.
338 : */
339 98 : rel_descr = RelationGetDescr(tdata->tg_relation);
340 98 : if (proc->result.typoid != rel_descr->tdtypeid)
341 52 : PLy_output_setup_func(&proc->result, proc->mcxt,
342 : rel_descr->tdtypeid,
343 : rel_descr->tdtypmod,
344 : proc);
345 98 : if (proc->result_in.typoid != rel_descr->tdtypeid)
346 52 : PLy_input_setup_func(&proc->result_in, proc->mcxt,
347 : rel_descr->tdtypeid,
348 : rel_descr->tdtypmod,
349 : proc);
350 98 : PLy_output_setup_tuple(&proc->result, rel_descr, proc);
351 98 : PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
352 :
353 : /*
354 : * If the trigger is called recursively, we must push outer-level
355 : * arguments into the stack. This must be immediately before the PG_TRY
356 : * to ensure that the corresponding pop happens.
357 : */
358 98 : PLy_global_args_push(proc);
359 :
360 98 : PG_TRY();
361 : {
362 : int rc PG_USED_FOR_ASSERTS_ONLY;
363 :
364 98 : rc = SPI_register_trigger_data(tdata);
365 : Assert(rc >= 0);
366 :
367 98 : plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
368 98 : plrv = PLy_procedure_call(proc, "TD", plargs);
369 :
370 : Assert(plrv != NULL);
371 :
372 : /*
373 : * Disconnect from SPI manager
374 : */
375 98 : if (SPI_finish() != SPI_OK_FINISH)
376 0 : elog(ERROR, "SPI_finish failed");
377 :
378 : /*
379 : * return of None means we're happy with the tuple
380 : */
381 98 : if (plrv != Py_None)
382 : {
383 : char *srv;
384 :
385 50 : if (PyUnicode_Check(plrv))
386 48 : srv = PLyUnicode_AsString(plrv);
387 : else
388 : {
389 2 : ereport(ERROR,
390 : (errcode(ERRCODE_DATA_EXCEPTION),
391 : errmsg("unexpected return value from trigger procedure"),
392 : errdetail("Expected None or a string.")));
393 : srv = NULL; /* keep compiler quiet */
394 : }
395 :
396 48 : if (pg_strcasecmp(srv, "SKIP") == 0)
397 2 : rv = NULL;
398 46 : else if (pg_strcasecmp(srv, "MODIFY") == 0)
399 : {
400 42 : if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
401 18 : TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
402 40 : rv = PLy_modify_tuple(proc, plargs, tdata, rv);
403 : else
404 2 : ereport(WARNING,
405 : (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
406 : }
407 4 : else if (pg_strcasecmp(srv, "OK") != 0)
408 : {
409 : /*
410 : * accept "OK" as an alternative to None; otherwise, raise an
411 : * error
412 : */
413 4 : ereport(ERROR,
414 : (errcode(ERRCODE_DATA_EXCEPTION),
415 : errmsg("unexpected return value from trigger procedure"),
416 : errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
417 : }
418 : }
419 : }
420 18 : PG_FINALLY();
421 : {
422 98 : PLy_global_args_pop(proc);
423 98 : Py_XDECREF(plargs);
424 98 : Py_XDECREF(plrv);
425 : }
426 98 : PG_END_TRY();
427 :
428 80 : return rv;
429 : }
430 :
431 : /*
432 : * event trigger subhandler
433 : */
434 : void
435 20 : PLy_exec_event_trigger(FunctionCallInfo fcinfo, PLyProcedure *proc)
436 : {
437 : EventTriggerData *tdata;
438 20 : PyObject *volatile pltdata = NULL;
439 :
440 : Assert(CALLED_AS_EVENT_TRIGGER(fcinfo));
441 20 : tdata = (EventTriggerData *) fcinfo->context;
442 :
443 20 : PG_TRY();
444 : {
445 : PyObject *pltevent,
446 : *plttag;
447 :
448 20 : pltdata = PyDict_New();
449 20 : if (!pltdata)
450 0 : PLy_elog(ERROR, NULL);
451 :
452 20 : pltevent = PLyUnicode_FromString(tdata->event);
453 20 : PyDict_SetItemString(pltdata, "event", pltevent);
454 20 : Py_DECREF(pltevent);
455 :
456 20 : plttag = PLyUnicode_FromString(GetCommandTagName(tdata->tag));
457 20 : PyDict_SetItemString(pltdata, "tag", plttag);
458 20 : Py_DECREF(plttag);
459 :
460 20 : PLy_procedure_call(proc, "TD", pltdata);
461 :
462 20 : if (SPI_finish() != SPI_OK_FINISH)
463 0 : elog(ERROR, "SPI_finish() failed");
464 : }
465 0 : PG_FINALLY();
466 : {
467 20 : Py_XDECREF(pltdata);
468 : }
469 20 : PG_END_TRY();
470 20 : }
471 :
472 : /* helper functions for Python code execution */
473 :
474 : static PyObject *
475 1026 : PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
476 : {
477 1026 : PyObject *volatile arg = NULL;
478 : PyObject *args;
479 : int i;
480 :
481 : /*
482 : * Make any Py*_New() calls before the PG_TRY block so that we can quickly
483 : * return NULL on failure. We can't return within the PG_TRY block, else
484 : * we'd miss unwinding the exception stack.
485 : */
486 1026 : args = PyList_New(proc->nargs);
487 1026 : if (!args)
488 0 : return NULL;
489 :
490 1026 : PG_TRY();
491 : {
492 2456 : for (i = 0; i < proc->nargs; i++)
493 : {
494 1430 : PLyDatumToOb *arginfo = &proc->args[i];
495 :
496 1430 : if (fcinfo->args[i].isnull)
497 242 : arg = NULL;
498 : else
499 1188 : arg = PLy_input_convert(arginfo, fcinfo->args[i].value);
500 :
501 1430 : if (arg == NULL)
502 : {
503 242 : Py_INCREF(Py_None);
504 242 : arg = Py_None;
505 : }
506 :
507 1430 : if (PyList_SetItem(args, i, arg) == -1)
508 0 : PLy_elog(ERROR, "PyList_SetItem() failed, while setting up arguments");
509 :
510 1430 : if (proc->argnames && proc->argnames[i] &&
511 1424 : PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1)
512 0 : PLy_elog(ERROR, "PyDict_SetItemString() failed, while setting up arguments");
513 1430 : arg = NULL;
514 : }
515 : }
516 0 : PG_CATCH();
517 : {
518 0 : Py_XDECREF(arg);
519 0 : Py_XDECREF(args);
520 :
521 0 : PG_RE_THROW();
522 : }
523 1026 : PG_END_TRY();
524 :
525 1026 : return args;
526 : }
527 :
528 : /*
529 : * Construct a PLySavedArgs struct representing the current values of the
530 : * procedure's arguments in its globals dict. This can be used to restore
531 : * those values when exiting a recursive call level or returning control to a
532 : * set-returning function.
533 : *
534 : * This would not be necessary except for an ancient decision to make args
535 : * available via the proc's globals :-( ... but we're stuck with that now.
536 : */
537 : static PLySavedArgs *
538 320 : PLy_function_save_args(PLyProcedure *proc)
539 : {
540 : PLySavedArgs *result;
541 :
542 : /* saved args are always allocated in procedure's context */
543 : result = (PLySavedArgs *)
544 320 : MemoryContextAllocZero(proc->mcxt,
545 320 : offsetof(PLySavedArgs, namedargs) +
546 320 : proc->nargs * sizeof(PyObject *));
547 320 : result->nargs = proc->nargs;
548 :
549 : /* Fetch the "args" list */
550 320 : result->args = PyDict_GetItemString(proc->globals, "args");
551 320 : Py_XINCREF(result->args);
552 :
553 : /* If it's a trigger, also save "TD" */
554 320 : if (proc->is_trigger == PLPY_TRIGGER)
555 : {
556 2 : result->td = PyDict_GetItemString(proc->globals, "TD");
557 2 : Py_XINCREF(result->td);
558 : }
559 :
560 : /* Fetch all the named arguments */
561 320 : if (proc->argnames)
562 : {
563 : int i;
564 :
565 626 : for (i = 0; i < result->nargs; i++)
566 : {
567 432 : if (proc->argnames[i])
568 : {
569 864 : result->namedargs[i] = PyDict_GetItemString(proc->globals,
570 432 : proc->argnames[i]);
571 432 : Py_XINCREF(result->namedargs[i]);
572 : }
573 : }
574 : }
575 :
576 320 : return result;
577 : }
578 :
579 : /*
580 : * Restore procedure's arguments from a PLySavedArgs struct,
581 : * then free the struct.
582 : */
583 : static void
584 316 : PLy_function_restore_args(PLyProcedure *proc, PLySavedArgs *savedargs)
585 : {
586 : /* Restore named arguments into their slots in the globals dict */
587 316 : if (proc->argnames)
588 : {
589 : int i;
590 :
591 626 : for (i = 0; i < savedargs->nargs; i++)
592 : {
593 432 : if (proc->argnames[i] && savedargs->namedargs[i])
594 : {
595 432 : PyDict_SetItemString(proc->globals, proc->argnames[i],
596 : savedargs->namedargs[i]);
597 432 : Py_DECREF(savedargs->namedargs[i]);
598 : }
599 : }
600 : }
601 :
602 : /* Restore the "args" object, too */
603 316 : if (savedargs->args)
604 : {
605 314 : PyDict_SetItemString(proc->globals, "args", savedargs->args);
606 314 : Py_DECREF(savedargs->args);
607 : }
608 :
609 : /* Restore the "TD" object, too */
610 316 : if (savedargs->td)
611 : {
612 2 : PyDict_SetItemString(proc->globals, "TD", savedargs->td);
613 2 : Py_DECREF(savedargs->td);
614 : }
615 :
616 : /* And free the PLySavedArgs struct */
617 316 : pfree(savedargs);
618 316 : }
619 :
620 : /*
621 : * Free a PLySavedArgs struct without restoring the values.
622 : */
623 : static void
624 4 : PLy_function_drop_args(PLySavedArgs *savedargs)
625 : {
626 : int i;
627 :
628 : /* Drop references for named args */
629 4 : for (i = 0; i < savedargs->nargs; i++)
630 : {
631 0 : Py_XDECREF(savedargs->namedargs[i]);
632 : }
633 :
634 : /* Drop refs to the "args" and "TD" objects, too */
635 4 : Py_XDECREF(savedargs->args);
636 4 : Py_XDECREF(savedargs->td);
637 :
638 : /* And free the PLySavedArgs struct */
639 4 : pfree(savedargs);
640 4 : }
641 :
642 : /*
643 : * Save away any existing arguments for the given procedure, so that we can
644 : * install new values for a recursive call. This should be invoked before
645 : * doing PLy_function_build_args() or PLy_trigger_build_args().
646 : *
647 : * NB: callers must ensure that PLy_global_args_pop gets invoked once, and
648 : * only once, per successful completion of PLy_global_args_push. Otherwise
649 : * we'll end up out-of-sync between the actual call stack and the contents
650 : * of proc->argstack.
651 : */
652 : static void
653 1418 : PLy_global_args_push(PLyProcedure *proc)
654 : {
655 : /* We only need to push if we are already inside some active call */
656 1418 : if (proc->calldepth > 0)
657 : {
658 : PLySavedArgs *node;
659 :
660 : /* Build a struct containing current argument values */
661 22 : node = PLy_function_save_args(proc);
662 :
663 : /*
664 : * Push the saved argument values into the procedure's stack. Once we
665 : * modify either proc->argstack or proc->calldepth, we had better
666 : * return without the possibility of error.
667 : */
668 22 : node->next = proc->argstack;
669 22 : proc->argstack = node;
670 : }
671 1418 : proc->calldepth++;
672 1418 : }
673 :
674 : /*
675 : * Pop old arguments when exiting a recursive call.
676 : *
677 : * Note: the idea here is to adjust the proc's callstack state before doing
678 : * anything that could possibly fail. In event of any error, we want the
679 : * callstack to look like we've done the pop. Leaking a bit of memory is
680 : * tolerable.
681 : */
682 : static void
683 1418 : PLy_global_args_pop(PLyProcedure *proc)
684 : {
685 : Assert(proc->calldepth > 0);
686 : /* We only need to pop if we were already inside some active call */
687 1418 : if (proc->calldepth > 1)
688 : {
689 22 : PLySavedArgs *ptr = proc->argstack;
690 :
691 : /* Pop the callstack */
692 : Assert(ptr != NULL);
693 22 : proc->argstack = ptr->next;
694 22 : proc->calldepth--;
695 :
696 : /* Restore argument values, then free ptr */
697 22 : PLy_function_restore_args(proc, ptr);
698 : }
699 : else
700 : {
701 : /* Exiting call depth 1 */
702 : Assert(proc->argstack == NULL);
703 1396 : proc->calldepth--;
704 :
705 : /*
706 : * We used to delete the named arguments (but not "args") from the
707 : * proc's globals dict when exiting the outermost call level for a
708 : * function. This seems rather pointless though: nothing can see the
709 : * dict until the function is called again, at which time we'll
710 : * overwrite those dict entries. So don't bother with that.
711 : */
712 : }
713 1418 : }
714 :
715 : /*
716 : * Memory context deletion callback for cleaning up a PLySRFState.
717 : * We need this in case execution of the SRF is terminated early,
718 : * due to error or the caller simply not running it to completion.
719 : */
720 : static void
721 106 : plpython_srf_cleanup_callback(void *arg)
722 : {
723 106 : PLySRFState *srfstate = (PLySRFState *) arg;
724 :
725 : /* Release refcount on the iter, if we still have one */
726 106 : Py_XDECREF(srfstate->iter);
727 106 : srfstate->iter = NULL;
728 : /* And drop any saved args; we won't need them */
729 106 : if (srfstate->savedargs)
730 0 : PLy_function_drop_args(srfstate->savedargs);
731 106 : srfstate->savedargs = NULL;
732 106 : }
733 :
734 : static void
735 74 : plpython_return_error_callback(void *arg)
736 : {
737 74 : PLyExecutionContext *exec_ctx = PLy_current_execution_context();
738 :
739 74 : if (exec_ctx->curr_proc &&
740 74 : !exec_ctx->curr_proc->is_procedure)
741 72 : errcontext("while creating return value");
742 74 : }
743 :
744 : static PyObject *
745 98 : PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
746 : {
747 98 : TriggerData *tdata = (TriggerData *) fcinfo->context;
748 98 : TupleDesc rel_descr = RelationGetDescr(tdata->tg_relation);
749 : PyObject *pltname,
750 : *pltevent,
751 : *pltwhen,
752 : *pltlevel,
753 : *pltrelid,
754 : *plttablename,
755 : *plttableschema,
756 : *pltargs,
757 : *pytnew,
758 : *pytold,
759 : *pltdata;
760 : char *stroid;
761 :
762 : /*
763 : * Make any Py*_New() calls before the PG_TRY block so that we can quickly
764 : * return NULL on failure. We can't return within the PG_TRY block, else
765 : * we'd miss unwinding the exception stack.
766 : */
767 98 : pltdata = PyDict_New();
768 98 : if (!pltdata)
769 0 : return NULL;
770 :
771 98 : if (tdata->tg_trigger->tgnargs)
772 : {
773 32 : pltargs = PyList_New(tdata->tg_trigger->tgnargs);
774 32 : if (!pltargs)
775 : {
776 0 : Py_DECREF(pltdata);
777 0 : return NULL;
778 : }
779 : }
780 : else
781 : {
782 66 : Py_INCREF(Py_None);
783 66 : pltargs = Py_None;
784 : }
785 :
786 98 : PG_TRY();
787 : {
788 98 : pltname = PLyUnicode_FromString(tdata->tg_trigger->tgname);
789 98 : PyDict_SetItemString(pltdata, "name", pltname);
790 98 : Py_DECREF(pltname);
791 :
792 98 : stroid = DatumGetCString(DirectFunctionCall1(oidout,
793 : ObjectIdGetDatum(tdata->tg_relation->rd_id)));
794 98 : pltrelid = PLyUnicode_FromString(stroid);
795 98 : PyDict_SetItemString(pltdata, "relid", pltrelid);
796 98 : Py_DECREF(pltrelid);
797 98 : pfree(stroid);
798 :
799 98 : stroid = SPI_getrelname(tdata->tg_relation);
800 98 : plttablename = PLyUnicode_FromString(stroid);
801 98 : PyDict_SetItemString(pltdata, "table_name", plttablename);
802 98 : Py_DECREF(plttablename);
803 98 : pfree(stroid);
804 :
805 98 : stroid = SPI_getnspname(tdata->tg_relation);
806 98 : plttableschema = PLyUnicode_FromString(stroid);
807 98 : PyDict_SetItemString(pltdata, "table_schema", plttableschema);
808 98 : Py_DECREF(plttableschema);
809 98 : pfree(stroid);
810 :
811 98 : if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
812 72 : pltwhen = PLyUnicode_FromString("BEFORE");
813 26 : else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
814 20 : pltwhen = PLyUnicode_FromString("AFTER");
815 6 : else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
816 6 : pltwhen = PLyUnicode_FromString("INSTEAD OF");
817 : else
818 : {
819 0 : elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
820 : pltwhen = NULL; /* keep compiler quiet */
821 : }
822 98 : PyDict_SetItemString(pltdata, "when", pltwhen);
823 98 : Py_DECREF(pltwhen);
824 :
825 98 : if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
826 : {
827 88 : pltlevel = PLyUnicode_FromString("ROW");
828 88 : PyDict_SetItemString(pltdata, "level", pltlevel);
829 88 : Py_DECREF(pltlevel);
830 :
831 : /*
832 : * Note: In BEFORE trigger, stored generated columns are not
833 : * computed yet, so don't make them accessible in NEW row.
834 : */
835 :
836 88 : if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
837 : {
838 42 : pltevent = PLyUnicode_FromString("INSERT");
839 :
840 42 : PyDict_SetItemString(pltdata, "old", Py_None);
841 84 : pytnew = PLy_input_from_tuple(&proc->result_in,
842 : tdata->tg_trigtuple,
843 : rel_descr,
844 42 : !TRIGGER_FIRED_BEFORE(tdata->tg_event));
845 42 : PyDict_SetItemString(pltdata, "new", pytnew);
846 42 : Py_DECREF(pytnew);
847 42 : *rv = tdata->tg_trigtuple;
848 : }
849 46 : else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
850 : {
851 12 : pltevent = PLyUnicode_FromString("DELETE");
852 :
853 12 : PyDict_SetItemString(pltdata, "new", Py_None);
854 12 : pytold = PLy_input_from_tuple(&proc->result_in,
855 : tdata->tg_trigtuple,
856 : rel_descr,
857 : true);
858 12 : PyDict_SetItemString(pltdata, "old", pytold);
859 12 : Py_DECREF(pytold);
860 12 : *rv = tdata->tg_trigtuple;
861 : }
862 34 : else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
863 : {
864 34 : pltevent = PLyUnicode_FromString("UPDATE");
865 :
866 68 : pytnew = PLy_input_from_tuple(&proc->result_in,
867 : tdata->tg_newtuple,
868 : rel_descr,
869 34 : !TRIGGER_FIRED_BEFORE(tdata->tg_event));
870 34 : PyDict_SetItemString(pltdata, "new", pytnew);
871 34 : Py_DECREF(pytnew);
872 34 : pytold = PLy_input_from_tuple(&proc->result_in,
873 : tdata->tg_trigtuple,
874 : rel_descr,
875 : true);
876 34 : PyDict_SetItemString(pltdata, "old", pytold);
877 34 : Py_DECREF(pytold);
878 34 : *rv = tdata->tg_newtuple;
879 : }
880 : else
881 : {
882 0 : elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
883 : pltevent = NULL; /* keep compiler quiet */
884 : }
885 :
886 88 : PyDict_SetItemString(pltdata, "event", pltevent);
887 88 : Py_DECREF(pltevent);
888 : }
889 10 : else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
890 : {
891 10 : pltlevel = PLyUnicode_FromString("STATEMENT");
892 10 : PyDict_SetItemString(pltdata, "level", pltlevel);
893 10 : Py_DECREF(pltlevel);
894 :
895 10 : PyDict_SetItemString(pltdata, "old", Py_None);
896 10 : PyDict_SetItemString(pltdata, "new", Py_None);
897 10 : *rv = NULL;
898 :
899 10 : if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
900 2 : pltevent = PLyUnicode_FromString("INSERT");
901 8 : else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
902 2 : pltevent = PLyUnicode_FromString("DELETE");
903 6 : else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
904 4 : pltevent = PLyUnicode_FromString("UPDATE");
905 2 : else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
906 2 : pltevent = PLyUnicode_FromString("TRUNCATE");
907 : else
908 : {
909 0 : elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
910 : pltevent = NULL; /* keep compiler quiet */
911 : }
912 :
913 10 : PyDict_SetItemString(pltdata, "event", pltevent);
914 10 : Py_DECREF(pltevent);
915 : }
916 : else
917 0 : elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
918 :
919 98 : if (tdata->tg_trigger->tgnargs)
920 : {
921 : /*
922 : * all strings...
923 : */
924 : int i;
925 : PyObject *pltarg;
926 :
927 : /* pltargs should have been allocated before the PG_TRY block. */
928 : Assert(pltargs && pltargs != Py_None);
929 :
930 90 : for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
931 : {
932 58 : pltarg = PLyUnicode_FromString(tdata->tg_trigger->tgargs[i]);
933 :
934 : /*
935 : * stolen, don't Py_DECREF
936 : */
937 58 : PyList_SetItem(pltargs, i, pltarg);
938 : }
939 : }
940 : else
941 : {
942 : Assert(pltargs == Py_None);
943 : }
944 98 : PyDict_SetItemString(pltdata, "args", pltargs);
945 98 : Py_DECREF(pltargs);
946 : }
947 0 : PG_CATCH();
948 : {
949 0 : Py_XDECREF(pltargs);
950 0 : Py_XDECREF(pltdata);
951 0 : PG_RE_THROW();
952 : }
953 98 : PG_END_TRY();
954 :
955 98 : return pltdata;
956 : }
957 :
958 : /*
959 : * Apply changes requested by a MODIFY return from a trigger function.
960 : */
961 : static HeapTuple
962 40 : PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
963 : HeapTuple otup)
964 : {
965 : HeapTuple rtup;
966 : PyObject *volatile plntup;
967 : PyObject *volatile plkeys;
968 : PyObject *volatile plval;
969 : Datum *volatile modvalues;
970 : bool *volatile modnulls;
971 : bool *volatile modrepls;
972 : ErrorContextCallback plerrcontext;
973 :
974 40 : plerrcontext.callback = plpython_trigger_error_callback;
975 40 : plerrcontext.previous = error_context_stack;
976 40 : error_context_stack = &plerrcontext;
977 :
978 40 : plntup = plkeys = plval = NULL;
979 40 : modvalues = NULL;
980 40 : modnulls = NULL;
981 40 : modrepls = NULL;
982 :
983 40 : PG_TRY();
984 : {
985 : TupleDesc tupdesc;
986 : int nkeys,
987 : i;
988 :
989 40 : if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
990 2 : ereport(ERROR,
991 : (errcode(ERRCODE_UNDEFINED_OBJECT),
992 : errmsg("TD[\"new\"] deleted, cannot modify row")));
993 38 : Py_INCREF(plntup);
994 38 : if (!PyDict_Check(plntup))
995 2 : ereport(ERROR,
996 : (errcode(ERRCODE_DATATYPE_MISMATCH),
997 : errmsg("TD[\"new\"] is not a dictionary")));
998 :
999 36 : plkeys = PyDict_Keys(plntup);
1000 36 : nkeys = PyList_Size(plkeys);
1001 :
1002 36 : tupdesc = RelationGetDescr(tdata->tg_relation);
1003 :
1004 36 : modvalues = (Datum *) palloc0(tupdesc->natts * sizeof(Datum));
1005 36 : modnulls = (bool *) palloc0(tupdesc->natts * sizeof(bool));
1006 36 : modrepls = (bool *) palloc0(tupdesc->natts * sizeof(bool));
1007 :
1008 90 : for (i = 0; i < nkeys; i++)
1009 : {
1010 : PyObject *platt;
1011 : char *plattstr;
1012 : int attn;
1013 : PLyObToDatum *att;
1014 :
1015 62 : platt = PyList_GetItem(plkeys, i);
1016 62 : if (PyUnicode_Check(platt))
1017 60 : plattstr = PLyUnicode_AsString(platt);
1018 : else
1019 : {
1020 2 : ereport(ERROR,
1021 : (errcode(ERRCODE_DATATYPE_MISMATCH),
1022 : errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
1023 : plattstr = NULL; /* keep compiler quiet */
1024 : }
1025 60 : attn = SPI_fnumber(tupdesc, plattstr);
1026 60 : if (attn == SPI_ERROR_NOATTRIBUTE)
1027 4 : ereport(ERROR,
1028 : (errcode(ERRCODE_UNDEFINED_COLUMN),
1029 : errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
1030 : plattstr)));
1031 56 : if (attn <= 0)
1032 0 : ereport(ERROR,
1033 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1034 : errmsg("cannot set system attribute \"%s\"",
1035 : plattstr)));
1036 56 : if (TupleDescAttr(tupdesc, attn - 1)->attgenerated)
1037 2 : ereport(ERROR,
1038 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1039 : errmsg("cannot set generated column \"%s\"",
1040 : plattstr)));
1041 :
1042 54 : plval = PyDict_GetItem(plntup, platt);
1043 54 : if (plval == NULL)
1044 0 : elog(FATAL, "Python interpreter is probably corrupted");
1045 :
1046 54 : Py_INCREF(plval);
1047 :
1048 : /* We assume proc->result is set up to convert tuples properly */
1049 54 : att = &proc->result.u.tuple.atts[attn - 1];
1050 :
1051 108 : modvalues[attn - 1] = PLy_output_convert(att,
1052 : plval,
1053 54 : &modnulls[attn - 1]);
1054 54 : modrepls[attn - 1] = true;
1055 :
1056 54 : Py_DECREF(plval);
1057 54 : plval = NULL;
1058 : }
1059 :
1060 28 : rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1061 : }
1062 12 : PG_CATCH();
1063 : {
1064 12 : Py_XDECREF(plntup);
1065 12 : Py_XDECREF(plkeys);
1066 12 : Py_XDECREF(plval);
1067 :
1068 12 : if (modvalues)
1069 8 : pfree(modvalues);
1070 12 : if (modnulls)
1071 8 : pfree(modnulls);
1072 12 : if (modrepls)
1073 8 : pfree(modrepls);
1074 :
1075 12 : PG_RE_THROW();
1076 : }
1077 28 : PG_END_TRY();
1078 :
1079 28 : Py_DECREF(plntup);
1080 28 : Py_DECREF(plkeys);
1081 :
1082 28 : pfree(modvalues);
1083 28 : pfree(modnulls);
1084 28 : pfree(modrepls);
1085 :
1086 28 : error_context_stack = plerrcontext.previous;
1087 :
1088 28 : return rtup;
1089 : }
1090 :
1091 : static void
1092 12 : plpython_trigger_error_callback(void *arg)
1093 : {
1094 12 : PLyExecutionContext *exec_ctx = PLy_current_execution_context();
1095 :
1096 12 : if (exec_ctx->curr_proc)
1097 12 : errcontext("while modifying trigger row");
1098 12 : }
1099 :
1100 : /* execute Python code, propagate Python errors to the backend */
1101 : static PyObject *
1102 1144 : PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
1103 : {
1104 1144 : PyObject *rv = NULL;
1105 1144 : int volatile save_subxact_level = list_length(explicit_subtransactions);
1106 :
1107 1144 : PyDict_SetItemString(proc->globals, kargs, vargs);
1108 :
1109 1144 : PG_TRY();
1110 : {
1111 1144 : rv = PyEval_EvalCode(proc->code, proc->globals, proc->globals);
1112 :
1113 : /*
1114 : * Since plpy will only let you close subtransactions that you
1115 : * started, you cannot *unnest* subtransactions, only *nest* them
1116 : * without closing.
1117 : */
1118 : Assert(list_length(explicit_subtransactions) >= save_subxact_level);
1119 : }
1120 0 : PG_FINALLY();
1121 : {
1122 1144 : PLy_abort_open_subtransactions(save_subxact_level);
1123 : }
1124 1144 : PG_END_TRY();
1125 :
1126 : /* If the Python code returned an error, propagate it */
1127 1144 : if (rv == NULL)
1128 108 : PLy_elog(ERROR, NULL);
1129 :
1130 1036 : return rv;
1131 : }
1132 :
1133 : /*
1134 : * Abort lingering subtransactions that have been explicitly started
1135 : * by plpy.subtransaction().start() and not properly closed.
1136 : */
1137 : static void
1138 1144 : PLy_abort_open_subtransactions(int save_subxact_level)
1139 : {
1140 : Assert(save_subxact_level >= 0);
1141 :
1142 1156 : while (list_length(explicit_subtransactions) > save_subxact_level)
1143 : {
1144 : PLySubtransactionData *subtransactiondata;
1145 :
1146 : Assert(explicit_subtransactions != NIL);
1147 :
1148 12 : ereport(WARNING,
1149 : (errmsg("forcibly aborting a subtransaction that has not been exited")));
1150 :
1151 12 : RollbackAndReleaseCurrentSubTransaction();
1152 :
1153 12 : subtransactiondata = (PLySubtransactionData *) linitial(explicit_subtransactions);
1154 12 : explicit_subtransactions = list_delete_first(explicit_subtransactions);
1155 :
1156 12 : MemoryContextSwitchTo(subtransactiondata->oldcontext);
1157 12 : CurrentResourceOwner = subtransactiondata->oldowner;
1158 12 : pfree(subtransactiondata);
1159 : }
1160 1144 : }
|