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