PostgreSQL Source Code  git master
plpy_exec.c
Go to the documentation of this file.
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/trigger.h"
13 #include "executor/spi.h"
14 #include "funcapi.h"
15 #include "utils/builtins.h"
16 #include "utils/rel.h"
17 #include "utils/typcache.h"
18 
19 #include "plpython.h"
20 
21 #include "plpy_exec.h"
22 
23 #include "plpy_elog.h"
24 #include "plpy_main.h"
25 #include "plpy_procedure.h"
26 #include "plpy_subxactobject.h"
27 
28 
29 /* saved state for a set-returning function */
30 typedef struct PLySRFState
31 {
32  PyObject *iter; /* Python iterator producing results */
33  PLySavedArgs *savedargs; /* function argument values */
34  MemoryContextCallback callback; /* for releasing refcounts when done */
35 } PLySRFState;
36 
37 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc);
41 static void PLy_global_args_push(PLyProcedure *proc);
42 static void PLy_global_args_pop(PLyProcedure *proc);
43 static void plpython_srf_cleanup_callback(void *arg);
44 static void plpython_return_error_callback(void *arg);
45 
46 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc,
47  HeapTuple *rv);
48 static HeapTuple PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd,
49  TriggerData *tdata, HeapTuple otup);
50 static void plpython_trigger_error_callback(void *arg);
51 
52 static PyObject *PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs);
53 static void PLy_abort_open_subtransactions(int save_subxact_level);
54 
55 
56 /* function subhandler */
57 Datum
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 return value
203  * must be None. For void-returning functions, we also treat a None
204  * return value as a special "void datum" rather than NULL (as is the
205  * case for non-void-returning functions).
206  */
207  if (proc->is_procedure)
208  {
209  if (plrv != Py_None)
210  ereport(ERROR,
211  (errcode(ERRCODE_DATATYPE_MISMATCH),
212  errmsg("PL/Python procedure did not return None")));
213  fcinfo->isnull = false;
214  rv = (Datum) 0;
215  }
216  else if (proc->result.typoid == VOIDOID)
217  {
218  if (plrv != Py_None)
219  ereport(ERROR,
220  (errcode(ERRCODE_DATATYPE_MISMATCH),
221  errmsg("PL/Python function with return type \"void\" did not return None")));
222 
223  fcinfo->isnull = false;
224  rv = (Datum) 0;
225  }
226  else if (plrv == Py_None &&
227  srfstate && srfstate->iter == NULL)
228  {
229  /*
230  * In a SETOF function, the iteration-ending null isn't a real
231  * value; don't pass it through the input function, which might
232  * complain.
233  */
234  fcinfo->isnull = true;
235  rv = (Datum) 0;
236  }
237  else
238  {
239  /* Normal conversion of result */
240  rv = PLy_output_convert(&proc->result, plrv,
241  &fcinfo->isnull);
242  }
243  }
244  PG_CATCH();
245  {
246  /* Pop old arguments from the stack if they were pushed above */
247  PLy_global_args_pop(proc);
248 
249  Py_XDECREF(plargs);
250  Py_XDECREF(plrv);
251 
252  /*
253  * If there was an error within a SRF, the iterator might not have
254  * been exhausted yet. Clear it so the next invocation of the
255  * function will start the iteration again. (This code is probably
256  * unnecessary now; plpython_srf_cleanup_callback should take care of
257  * cleanup. But it doesn't hurt anything to do it here.)
258  */
259  if (srfstate)
260  {
261  Py_XDECREF(srfstate->iter);
262  srfstate->iter = NULL;
263  /* And drop any saved args; we won't need them */
264  if (srfstate->savedargs)
266  srfstate->savedargs = NULL;
267  }
268 
269  PG_RE_THROW();
270  }
271  PG_END_TRY();
272 
273  error_context_stack = plerrcontext.previous;
274 
275  /* Pop old arguments from the stack if they were pushed above */
276  PLy_global_args_pop(proc);
277 
278  Py_XDECREF(plargs);
279  Py_DECREF(plrv);
280 
281  if (srfstate)
282  {
283  /* We're in a SRF, exit appropriately */
284  if (srfstate->iter == NULL)
285  {
286  /* Iterator exhausted, so we're done */
287  SRF_RETURN_DONE(funcctx);
288  }
289  else if (fcinfo->isnull)
290  SRF_RETURN_NEXT_NULL(funcctx);
291  else
292  SRF_RETURN_NEXT(funcctx, rv);
293  }
294 
295  /* Plain function, just return the Datum value (possibly null) */
296  return rv;
297 }
298 
299 /* trigger subhandler
300  *
301  * the python function is expected to return Py_None if the tuple is
302  * acceptable and unmodified. Otherwise it should return a PyString
303  * object who's value is SKIP, or MODIFY. SKIP means don't perform
304  * this action. MODIFY means the tuple has been modified, so update
305  * tuple and perform action. SKIP and MODIFY assume the trigger fires
306  * BEFORE the event and is ROW level. postgres expects the function
307  * to take no arguments and return an argument of type trigger.
308  */
309 HeapTuple
311 {
312  HeapTuple rv = NULL;
313  PyObject *volatile plargs = NULL;
314  PyObject *volatile plrv = NULL;
315  TriggerData *tdata;
316  TupleDesc rel_descr;
317 
318  Assert(CALLED_AS_TRIGGER(fcinfo));
319  tdata = (TriggerData *) fcinfo->context;
320 
321  /*
322  * Input/output conversion for trigger tuples. We use the result and
323  * result_in fields to store the tuple conversion info. We do this over
324  * again on each call to cover the possibility that the relation's tupdesc
325  * changed since the trigger was last called. The PLy_xxx_setup_func
326  * calls should only happen once, but PLy_input_setup_tuple and
327  * PLy_output_setup_tuple are responsible for not doing repetitive work.
328  */
329  rel_descr = RelationGetDescr(tdata->tg_relation);
330  if (proc->result.typoid != rel_descr->tdtypeid)
331  PLy_output_setup_func(&proc->result, proc->mcxt,
332  rel_descr->tdtypeid,
333  rel_descr->tdtypmod,
334  proc);
335  if (proc->result_in.typoid != rel_descr->tdtypeid)
336  PLy_input_setup_func(&proc->result_in, proc->mcxt,
337  rel_descr->tdtypeid,
338  rel_descr->tdtypmod,
339  proc);
340  PLy_output_setup_tuple(&proc->result, rel_descr, proc);
341  PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
342 
343  PG_TRY();
344  {
346 
347  rc = SPI_register_trigger_data(tdata);
348  Assert(rc >= 0);
349 
350  plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
351  plrv = PLy_procedure_call(proc, "TD", plargs);
352 
353  Assert(plrv != NULL);
354 
355  /*
356  * Disconnect from SPI manager
357  */
358  if (SPI_finish() != SPI_OK_FINISH)
359  elog(ERROR, "SPI_finish failed");
360 
361  /*
362  * return of None means we're happy with the tuple
363  */
364  if (plrv != Py_None)
365  {
366  char *srv;
367 
368  if (PyString_Check(plrv))
369  srv = PyString_AsString(plrv);
370  else if (PyUnicode_Check(plrv))
371  srv = PLyUnicode_AsString(plrv);
372  else
373  {
374  ereport(ERROR,
375  (errcode(ERRCODE_DATA_EXCEPTION),
376  errmsg("unexpected return value from trigger procedure"),
377  errdetail("Expected None or a string.")));
378  srv = NULL; /* keep compiler quiet */
379  }
380 
381  if (pg_strcasecmp(srv, "SKIP") == 0)
382  rv = NULL;
383  else if (pg_strcasecmp(srv, "MODIFY") == 0)
384  {
385  TriggerData *tdata = (TriggerData *) fcinfo->context;
386 
387  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
389  rv = PLy_modify_tuple(proc, plargs, tdata, rv);
390  else
392  (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
393  }
394  else if (pg_strcasecmp(srv, "OK") != 0)
395  {
396  /*
397  * accept "OK" as an alternative to None; otherwise, raise an
398  * error
399  */
400  ereport(ERROR,
401  (errcode(ERRCODE_DATA_EXCEPTION),
402  errmsg("unexpected return value from trigger procedure"),
403  errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
404  }
405  }
406  }
407  PG_CATCH();
408  {
409  Py_XDECREF(plargs);
410  Py_XDECREF(plrv);
411 
412  PG_RE_THROW();
413  }
414  PG_END_TRY();
415 
416  Py_DECREF(plargs);
417  Py_DECREF(plrv);
418 
419  return rv;
420 }
421 
422 /* helper functions for Python code execution */
423 
424 static PyObject *
426 {
427  PyObject *volatile arg = NULL;
428  PyObject *volatile args = NULL;
429  int i;
430 
431  PG_TRY();
432  {
433  args = PyList_New(proc->nargs);
434  if (!args)
435  return NULL;
436 
437  for (i = 0; i < proc->nargs; i++)
438  {
439  PLyDatumToOb *arginfo = &proc->args[i];
440 
441  if (fcinfo->argnull[i])
442  arg = NULL;
443  else
444  arg = PLy_input_convert(arginfo, fcinfo->arg[i]);
445 
446  if (arg == NULL)
447  {
448  Py_INCREF(Py_None);
449  arg = Py_None;
450  }
451 
452  if (PyList_SetItem(args, i, arg) == -1)
453  PLy_elog(ERROR, "PyList_SetItem() failed, while setting up arguments");
454 
455  if (proc->argnames && proc->argnames[i] &&
456  PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1)
457  PLy_elog(ERROR, "PyDict_SetItemString() failed, while setting up arguments");
458  arg = NULL;
459  }
460 
461  /* Set up output conversion for functions returning RECORD */
462  if (proc->result.typoid == RECORDOID)
463  {
464  TupleDesc desc;
465 
466  if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
467  ereport(ERROR,
468  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
469  errmsg("function returning record called in context "
470  "that cannot accept type record")));
471 
472  /* cache the output conversion functions */
473  PLy_output_setup_record(&proc->result, desc, proc);
474  }
475  }
476  PG_CATCH();
477  {
478  Py_XDECREF(arg);
479  Py_XDECREF(args);
480 
481  PG_RE_THROW();
482  }
483  PG_END_TRY();
484 
485  return args;
486 }
487 
488 /*
489  * Construct a PLySavedArgs struct representing the current values of the
490  * procedure's arguments in its globals dict. This can be used to restore
491  * those values when exiting a recursive call level or returning control to a
492  * set-returning function.
493  *
494  * This would not be necessary except for an ancient decision to make args
495  * available via the proc's globals :-( ... but we're stuck with that now.
496  */
497 static PLySavedArgs *
499 {
500  PLySavedArgs *result;
501 
502  /* saved args are always allocated in procedure's context */
503  result = (PLySavedArgs *)
505  offsetof(PLySavedArgs, namedargs) +
506  proc->nargs * sizeof(PyObject *));
507  result->nargs = proc->nargs;
508 
509  /* Fetch the "args" list */
510  result->args = PyDict_GetItemString(proc->globals, "args");
511  Py_XINCREF(result->args);
512 
513  /* Fetch all the named arguments */
514  if (proc->argnames)
515  {
516  int i;
517 
518  for (i = 0; i < result->nargs; i++)
519  {
520  if (proc->argnames[i])
521  {
522  result->namedargs[i] = PyDict_GetItemString(proc->globals,
523  proc->argnames[i]);
524  Py_XINCREF(result->namedargs[i]);
525  }
526  }
527  }
528 
529  return result;
530 }
531 
532 /*
533  * Restore procedure's arguments from a PLySavedArgs struct,
534  * then free the struct.
535  */
536 static void
538 {
539  /* Restore named arguments into their slots in the globals dict */
540  if (proc->argnames)
541  {
542  int i;
543 
544  for (i = 0; i < savedargs->nargs; i++)
545  {
546  if (proc->argnames[i] && savedargs->namedargs[i])
547  {
548  PyDict_SetItemString(proc->globals, proc->argnames[i],
549  savedargs->namedargs[i]);
550  Py_DECREF(savedargs->namedargs[i]);
551  }
552  }
553  }
554 
555  /* Restore the "args" object, too */
556  if (savedargs->args)
557  {
558  PyDict_SetItemString(proc->globals, "args", savedargs->args);
559  Py_DECREF(savedargs->args);
560  }
561 
562  /* And free the PLySavedArgs struct */
563  pfree(savedargs);
564 }
565 
566 /*
567  * Free a PLySavedArgs struct without restoring the values.
568  */
569 static void
571 {
572  int i;
573 
574  /* Drop references for named args */
575  for (i = 0; i < savedargs->nargs; i++)
576  {
577  Py_XDECREF(savedargs->namedargs[i]);
578  }
579 
580  /* Drop ref to the "args" object, too */
581  Py_XDECREF(savedargs->args);
582 
583  /* And free the PLySavedArgs struct */
584  pfree(savedargs);
585 }
586 
587 /*
588  * Save away any existing arguments for the given procedure, so that we can
589  * install new values for a recursive call. This should be invoked before
590  * doing PLy_function_build_args().
591  *
592  * NB: caller must ensure that PLy_global_args_pop gets invoked once, and
593  * only once, per successful completion of PLy_global_args_push. Otherwise
594  * we'll end up out-of-sync between the actual call stack and the contents
595  * of proc->argstack.
596  */
597 static void
599 {
600  /* We only need to push if we are already inside some active call */
601  if (proc->calldepth > 0)
602  {
603  PLySavedArgs *node;
604 
605  /* Build a struct containing current argument values */
606  node = PLy_function_save_args(proc);
607 
608  /*
609  * Push the saved argument values into the procedure's stack. Once we
610  * modify either proc->argstack or proc->calldepth, we had better
611  * return without the possibility of error.
612  */
613  node->next = proc->argstack;
614  proc->argstack = node;
615  }
616  proc->calldepth++;
617 }
618 
619 /*
620  * Pop old arguments when exiting a recursive call.
621  *
622  * Note: the idea here is to adjust the proc's callstack state before doing
623  * anything that could possibly fail. In event of any error, we want the
624  * callstack to look like we've done the pop. Leaking a bit of memory is
625  * tolerable.
626  */
627 static void
629 {
630  Assert(proc->calldepth > 0);
631  /* We only need to pop if we were already inside some active call */
632  if (proc->calldepth > 1)
633  {
634  PLySavedArgs *ptr = proc->argstack;
635 
636  /* Pop the callstack */
637  Assert(ptr != NULL);
638  proc->argstack = ptr->next;
639  proc->calldepth--;
640 
641  /* Restore argument values, then free ptr */
642  PLy_function_restore_args(proc, ptr);
643  }
644  else
645  {
646  /* Exiting call depth 1 */
647  Assert(proc->argstack == NULL);
648  proc->calldepth--;
649 
650  /*
651  * We used to delete the named arguments (but not "args") from the
652  * proc's globals dict when exiting the outermost call level for a
653  * function. This seems rather pointless though: nothing can see the
654  * dict until the function is called again, at which time we'll
655  * overwrite those dict entries. So don't bother with that.
656  */
657  }
658 }
659 
660 /*
661  * Memory context deletion callback for cleaning up a PLySRFState.
662  * We need this in case execution of the SRF is terminated early,
663  * due to error or the caller simply not running it to completion.
664  */
665 static void
667 {
668  PLySRFState *srfstate = (PLySRFState *) arg;
669 
670  /* Release refcount on the iter, if we still have one */
671  Py_XDECREF(srfstate->iter);
672  srfstate->iter = NULL;
673  /* And drop any saved args; we won't need them */
674  if (srfstate->savedargs)
676  srfstate->savedargs = NULL;
677 }
678 
679 static void
681 {
683 
684  if (exec_ctx->curr_proc &&
685  !exec_ctx->curr_proc->is_procedure)
686  errcontext("while creating return value");
687 }
688 
689 static PyObject *
691 {
692  TriggerData *tdata = (TriggerData *) fcinfo->context;
693  TupleDesc rel_descr = RelationGetDescr(tdata->tg_relation);
694  PyObject *pltname,
695  *pltevent,
696  *pltwhen,
697  *pltlevel,
698  *pltrelid,
699  *plttablename,
700  *plttableschema;
701  PyObject *pltargs,
702  *pytnew,
703  *pytold;
704  PyObject *volatile pltdata = NULL;
705  char *stroid;
706 
707  PG_TRY();
708  {
709  pltdata = PyDict_New();
710  if (!pltdata)
711  return NULL;
712 
713  pltname = PyString_FromString(tdata->tg_trigger->tgname);
714  PyDict_SetItemString(pltdata, "name", pltname);
715  Py_DECREF(pltname);
716 
719  pltrelid = PyString_FromString(stroid);
720  PyDict_SetItemString(pltdata, "relid", pltrelid);
721  Py_DECREF(pltrelid);
722  pfree(stroid);
723 
724  stroid = SPI_getrelname(tdata->tg_relation);
725  plttablename = PyString_FromString(stroid);
726  PyDict_SetItemString(pltdata, "table_name", plttablename);
727  Py_DECREF(plttablename);
728  pfree(stroid);
729 
730  stroid = SPI_getnspname(tdata->tg_relation);
731  plttableschema = PyString_FromString(stroid);
732  PyDict_SetItemString(pltdata, "table_schema", plttableschema);
733  Py_DECREF(plttableschema);
734  pfree(stroid);
735 
736  if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
737  pltwhen = PyString_FromString("BEFORE");
738  else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
739  pltwhen = PyString_FromString("AFTER");
740  else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
741  pltwhen = PyString_FromString("INSTEAD OF");
742  else
743  {
744  elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
745  pltwhen = NULL; /* keep compiler quiet */
746  }
747  PyDict_SetItemString(pltdata, "when", pltwhen);
748  Py_DECREF(pltwhen);
749 
750  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
751  {
752  pltlevel = PyString_FromString("ROW");
753  PyDict_SetItemString(pltdata, "level", pltlevel);
754  Py_DECREF(pltlevel);
755 
756  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
757  {
758  pltevent = PyString_FromString("INSERT");
759 
760  PyDict_SetItemString(pltdata, "old", Py_None);
761  pytnew = PLy_input_from_tuple(&proc->result_in,
762  tdata->tg_trigtuple,
763  rel_descr);
764  PyDict_SetItemString(pltdata, "new", pytnew);
765  Py_DECREF(pytnew);
766  *rv = tdata->tg_trigtuple;
767  }
768  else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
769  {
770  pltevent = PyString_FromString("DELETE");
771 
772  PyDict_SetItemString(pltdata, "new", Py_None);
773  pytold = PLy_input_from_tuple(&proc->result_in,
774  tdata->tg_trigtuple,
775  rel_descr);
776  PyDict_SetItemString(pltdata, "old", pytold);
777  Py_DECREF(pytold);
778  *rv = tdata->tg_trigtuple;
779  }
780  else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
781  {
782  pltevent = PyString_FromString("UPDATE");
783 
784  pytnew = PLy_input_from_tuple(&proc->result_in,
785  tdata->tg_newtuple,
786  rel_descr);
787  PyDict_SetItemString(pltdata, "new", pytnew);
788  Py_DECREF(pytnew);
789  pytold = PLy_input_from_tuple(&proc->result_in,
790  tdata->tg_trigtuple,
791  rel_descr);
792  PyDict_SetItemString(pltdata, "old", pytold);
793  Py_DECREF(pytold);
794  *rv = tdata->tg_newtuple;
795  }
796  else
797  {
798  elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
799  pltevent = NULL; /* keep compiler quiet */
800  }
801 
802  PyDict_SetItemString(pltdata, "event", pltevent);
803  Py_DECREF(pltevent);
804  }
805  else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
806  {
807  pltlevel = PyString_FromString("STATEMENT");
808  PyDict_SetItemString(pltdata, "level", pltlevel);
809  Py_DECREF(pltlevel);
810 
811  PyDict_SetItemString(pltdata, "old", Py_None);
812  PyDict_SetItemString(pltdata, "new", Py_None);
813  *rv = NULL;
814 
815  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
816  pltevent = PyString_FromString("INSERT");
817  else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
818  pltevent = PyString_FromString("DELETE");
819  else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
820  pltevent = PyString_FromString("UPDATE");
821  else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
822  pltevent = PyString_FromString("TRUNCATE");
823  else
824  {
825  elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
826  pltevent = NULL; /* keep compiler quiet */
827  }
828 
829  PyDict_SetItemString(pltdata, "event", pltevent);
830  Py_DECREF(pltevent);
831  }
832  else
833  elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
834 
835  if (tdata->tg_trigger->tgnargs)
836  {
837  /*
838  * all strings...
839  */
840  int i;
841  PyObject *pltarg;
842 
843  pltargs = PyList_New(tdata->tg_trigger->tgnargs);
844  if (!pltargs)
845  {
846  Py_DECREF(pltdata);
847  return NULL;
848  }
849  for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
850  {
851  pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
852 
853  /*
854  * stolen, don't Py_DECREF
855  */
856  PyList_SetItem(pltargs, i, pltarg);
857  }
858  }
859  else
860  {
861  Py_INCREF(Py_None);
862  pltargs = Py_None;
863  }
864  PyDict_SetItemString(pltdata, "args", pltargs);
865  Py_DECREF(pltargs);
866  }
867  PG_CATCH();
868  {
869  Py_XDECREF(pltdata);
870  PG_RE_THROW();
871  }
872  PG_END_TRY();
873 
874  return pltdata;
875 }
876 
877 /*
878  * Apply changes requested by a MODIFY return from a trigger function.
879  */
880 static HeapTuple
881 PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
882  HeapTuple otup)
883 {
884  HeapTuple rtup;
885  PyObject *volatile plntup;
886  PyObject *volatile plkeys;
887  PyObject *volatile plval;
888  Datum *volatile modvalues;
889  bool *volatile modnulls;
890  bool *volatile modrepls;
891  ErrorContextCallback plerrcontext;
892 
894  plerrcontext.previous = error_context_stack;
895  error_context_stack = &plerrcontext;
896 
897  plntup = plkeys = plval = NULL;
898  modvalues = NULL;
899  modnulls = NULL;
900  modrepls = NULL;
901 
902  PG_TRY();
903  {
904  TupleDesc tupdesc;
905  int nkeys,
906  i;
907 
908  if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
909  ereport(ERROR,
910  (errcode(ERRCODE_UNDEFINED_OBJECT),
911  errmsg("TD[\"new\"] deleted, cannot modify row")));
912  Py_INCREF(plntup);
913  if (!PyDict_Check(plntup))
914  ereport(ERROR,
915  (errcode(ERRCODE_DATATYPE_MISMATCH),
916  errmsg("TD[\"new\"] is not a dictionary")));
917 
918  plkeys = PyDict_Keys(plntup);
919  nkeys = PyList_Size(plkeys);
920 
921  tupdesc = RelationGetDescr(tdata->tg_relation);
922 
923  modvalues = (Datum *) palloc0(tupdesc->natts * sizeof(Datum));
924  modnulls = (bool *) palloc0(tupdesc->natts * sizeof(bool));
925  modrepls = (bool *) palloc0(tupdesc->natts * sizeof(bool));
926 
927  for (i = 0; i < nkeys; i++)
928  {
929  PyObject *platt;
930  char *plattstr;
931  int attn;
932  PLyObToDatum *att;
933 
934  platt = PyList_GetItem(plkeys, i);
935  if (PyString_Check(platt))
936  plattstr = PyString_AsString(platt);
937  else if (PyUnicode_Check(platt))
938  plattstr = PLyUnicode_AsString(platt);
939  else
940  {
941  ereport(ERROR,
942  (errcode(ERRCODE_DATATYPE_MISMATCH),
943  errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
944  plattstr = NULL; /* keep compiler quiet */
945  }
946  attn = SPI_fnumber(tupdesc, plattstr);
947  if (attn == SPI_ERROR_NOATTRIBUTE)
948  ereport(ERROR,
949  (errcode(ERRCODE_UNDEFINED_COLUMN),
950  errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
951  plattstr)));
952  if (attn <= 0)
953  ereport(ERROR,
954  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
955  errmsg("cannot set system attribute \"%s\"",
956  plattstr)));
957 
958  plval = PyDict_GetItem(plntup, platt);
959  if (plval == NULL)
960  elog(FATAL, "Python interpreter is probably corrupted");
961 
962  Py_INCREF(plval);
963 
964  /* We assume proc->result is set up to convert tuples properly */
965  att = &proc->result.u.tuple.atts[attn - 1];
966 
967  modvalues[attn - 1] = PLy_output_convert(att,
968  plval,
969  &modnulls[attn - 1]);
970  modrepls[attn - 1] = true;
971 
972  Py_DECREF(plval);
973  plval = NULL;
974  }
975 
976  rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
977  }
978  PG_CATCH();
979  {
980  Py_XDECREF(plntup);
981  Py_XDECREF(plkeys);
982  Py_XDECREF(plval);
983 
984  if (modvalues)
985  pfree(modvalues);
986  if (modnulls)
987  pfree(modnulls);
988  if (modrepls)
989  pfree(modrepls);
990 
991  PG_RE_THROW();
992  }
993  PG_END_TRY();
994 
995  Py_DECREF(plntup);
996  Py_DECREF(plkeys);
997 
998  pfree(modvalues);
999  pfree(modnulls);
1000  pfree(modrepls);
1001 
1002  error_context_stack = plerrcontext.previous;
1003 
1004  return rtup;
1005 }
1006 
1007 static void
1009 {
1011 
1012  if (exec_ctx->curr_proc)
1013  errcontext("while modifying trigger row");
1014 }
1015 
1016 /* execute Python code, propagate Python errors to the backend */
1017 static PyObject *
1018 PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
1019 {
1020  PyObject *rv;
1021  int volatile save_subxact_level = list_length(explicit_subtransactions);
1022 
1023  PyDict_SetItemString(proc->globals, kargs, vargs);
1024 
1025  PG_TRY();
1026  {
1027 #if PY_VERSION_HEX >= 0x03020000
1028  rv = PyEval_EvalCode(proc->code,
1029  proc->globals, proc->globals);
1030 #else
1031  rv = PyEval_EvalCode((PyCodeObject *) proc->code,
1032  proc->globals, proc->globals);
1033 #endif
1034 
1035  /*
1036  * Since plpy will only let you close subtransactions that you
1037  * started, you cannot *unnest* subtransactions, only *nest* them
1038  * without closing.
1039  */
1040  Assert(list_length(explicit_subtransactions) >= save_subxact_level);
1041  }
1042  PG_CATCH();
1043  {
1044  PLy_abort_open_subtransactions(save_subxact_level);
1045  PG_RE_THROW();
1046  }
1047  PG_END_TRY();
1048 
1049  PLy_abort_open_subtransactions(save_subxact_level);
1050 
1051  /* If the Python code returned an error, propagate it */
1052  if (rv == NULL)
1053  PLy_elog(ERROR, NULL);
1054 
1055  return rv;
1056 }
1057 
1058 /*
1059  * Abort lingering subtransactions that have been explicitly started
1060  * by plpy.subtransaction().start() and not properly closed.
1061  */
1062 static void
1063 PLy_abort_open_subtransactions(int save_subxact_level)
1064 {
1065  Assert(save_subxact_level >= 0);
1066 
1067  while (list_length(explicit_subtransactions) > save_subxact_level)
1068  {
1069  PLySubtransactionData *subtransactiondata;
1070 
1072 
1073  ereport(WARNING,
1074  (errmsg("forcibly aborting a subtransaction that has not been exited")));
1075 
1077 
1078  subtransactiondata = (PLySubtransactionData *) linitial(explicit_subtransactions);
1080 
1081  MemoryContextSwitchTo(subtransactiondata->oldcontext);
1082  CurrentResourceOwner = subtransactiondata->oldowner;
1083  pfree(subtransactiondata);
1084  }
1085 }
HeapTuple PLy_exec_trigger(FunctionCallInfo fcinfo, PLyProcedure *proc)
Definition: plpy_exec.c:310
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:767
MemoryContextCallbackFunction func
Definition: palloc.h:49
#define NIL
Definition: pg_list.h:69
struct PLySavedArgs * next
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
Oid tdtypeid
Definition: tupdesc.h:80
Datum PLy_output_convert(PLyObToDatum *arg, PyObject *val, bool *isnull)
Definition: plpy_typeio.c:123
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
static void PLy_global_args_push(PLyProcedure *proc)
Definition: plpy_exec.c:598
PyObject * PLy_input_from_tuple(PLyDatumToOb *arg, HeapTuple tuple, TupleDesc desc)
Definition: plpy_typeio.c:137
#define RelationGetDescr(relation)
Definition: rel.h:437
static void PLy_global_args_pop(PLyProcedure *proc)
Definition: plpy_exec.c:628
fmNodePtr context
Definition: fmgr.h:80
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:293
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
int SPI_finish(void)
Definition: spi.c:149
PyObject * args
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
static void PLy_function_restore_args(PLyProcedure *proc, PLySavedArgs *savedargs)
Definition: plpy_exec.c:537
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
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:881
PLyExecutionContext * PLy_current_execution_context(void)
Definition: plpy_main.c:409
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:137
Datum oidout(PG_FUNCTION_ARGS)
Definition: oid.c:127
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:297
int natts
Definition: tupdesc.h:79
#define TRIGGER_FIRED_FOR_STATEMENT(event)
Definition: trigger.h:131
int32 tdtypmod
Definition: tupdesc.h:81
HeapTuple tg_trigtuple
Definition: trigger.h:35
static PyObject * PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
Definition: plpy_exec.c:425
char * PLyUnicode_AsString(PyObject *unicode)
Definition: plpy_util.c:94
PLyDatumToOb * args
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:299
char ** argnames
void pfree(void *pointer)
Definition: mcxt.c:949
#define TRIGGER_FIRED_BY_TRUNCATE(event)
Definition: trigger.h:125
#define linitial(l)
Definition: pg_list.h:111
#define VOIDOID
Definition: pg_type.h:690
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define DatumGetCString(X)
Definition: postgres.h:572
static void plpython_return_error_callback(void *arg)
Definition: plpy_exec.c:680
void PLy_output_setup_record(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:264
char * tgname
Definition: reltrigger.h:27
#define FATAL
Definition: elog.h:52
MemoryContext mcxt
static PLySavedArgs * PLy_function_save_args(PLyProcedure *proc)
Definition: plpy_exec.c:498
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4276
void PLy_input_setup_tuple(PLyDatumToOb *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:168
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
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
List * explicit_subtransactions
#define SRF_RETURN_NEXT_NULL(_funcctx)
Definition: funcapi.h:308
fmNodePtr resultinfo
Definition: fmgr.h:81
#define RECORDOID
Definition: pg_type.h:680
bool argnull[FUNC_MAX_ARGS]
Definition: fmgr.h:86
struct PLySRFState PLySRFState
#define ereport(elevel, rest)
Definition: elog.h:122
int SPI_register_trigger_data(TriggerData *tdata)
Definition: spi.c:2752
Oid rd_id
Definition: rel.h:116
PLyProcedure * curr_proc
Definition: plpy_main.h:20
#define WARNING
Definition: elog.h:40
static void PLy_function_drop_args(PLySavedArgs *savedargs)
Definition: plpy_exec.c:570
char ** tgargs
Definition: reltrigger.h:40
PyObject * namedargs[FLEXIBLE_ARRAY_MEMBER]
#define PLy_elog
Definition: plpy_elog.h:36
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:119
PyObject * code
static void PLy_abort_open_subtransactions(int save_subxact_level)
Definition: plpy_exec.c:1063
void * palloc0(Size size)
Definition: mcxt.c:877
uintptr_t Datum
Definition: postgres.h:372
union PLyObToDatum::@142 u
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
void PLy_output_setup_tuple(PLyObToDatum *arg, TupleDesc desc, PLyProcedure *proc)
Definition: plpy_typeio.c:218
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:741
char * SPI_getrelname(Relation rel)
Definition: spi.c:918
int allowedModes
Definition: execnodes.h:269
Datum arg[FUNC_MAX_ARGS]
Definition: fmgr.h:85
SetFunctionReturnMode returnMode
Definition: execnodes.h:271
#define PG_CATCH()
Definition: elog.h:293
PyObject * PLy_input_convert(PLyDatumToOb *arg, Datum val)
Definition: plpy_typeio.c:84
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define Assert(condition)
Definition: c.h:670
TriggerEvent tg_event
Definition: trigger.h:33
char * SPI_getnspname(Relation rel)
Definition: spi.c:924
static void plpython_trigger_error_callback(void *arg)
Definition: plpy_exec.c:1008
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:110
PLyDatumToOb result_in
static int list_length(const List *l)
Definition: pg_list.h:89
#define SPI_OK_FINISH
Definition: spi.h:51
#define PG_RE_THROW()
Definition: elog.h:314
PLySavedArgs * argstack
#define TRIGGER_FIRED_BEFORE(event)
Definition: trigger.h:134
#define TRIGGER_FIRED_INSTEAD(event)
Definition: trigger.h:140
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
PLyObToTuple tuple
Definition: plpy_typeio.h:142
void * user_fctx
Definition: funcapi.h:91
static PyObject * PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
Definition: plpy_exec.c:690
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
int16 tgnargs
Definition: reltrigger.h:37
#define errcontext
Definition: elog.h:164
void * arg
PyObject * iter
Definition: plpy_exec.c:32
void MemoryContextRegisterResetCallback(MemoryContext context, MemoryContextCallback *cb)
Definition: mcxt.c:265
PLyObToDatum * atts
Definition: plpy_typeio.h:112
PLySavedArgs * savedargs
Definition: plpy_exec.c:33
MemoryContextCallback callback
Definition: plpy_exec.c:34
#define elog
Definition: elog.h:219
Datum PLy_exec_function(FunctionCallInfo fcinfo, PLyProcedure *proc)
Definition: plpy_exec.c:58
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:122
#define PG_TRY()
Definition: elog.h:284
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:128
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
PyObject * globals
#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:1018
#define PG_END_TRY()
Definition: elog.h:300
#define offsetof(type, field)
Definition: c.h:593
List * list_delete_first(List *list)
Definition: list.c:666
static void plpython_srf_cleanup_callback(void *arg)
Definition: plpy_exec.c:666
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:317
Relation tg_relation
Definition: trigger.h:34
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:295