2 * executing Python code
4 * src/pl/plpython/plpy_exec.c
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"
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"
21 #include "utils/builtins.h"
22 #include "utils/lsyscache.h"
23 #include "utils/rel.h"
24 #include "utils/typcache.h"
26 /* saved state for a set-returning function */
27 typedef struct PLySRFState
29 PyObject
*iter
; /* Python iterator producing results */
30 PLySavedArgs
*savedargs
; /* function argument values */
31 MemoryContextCallback callback
; /* for releasing refcounts when done */
34 static PyObject
*PLy_function_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
);
35 static PLySavedArgs
*PLy_function_save_args(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
);
43 static PyObject
*PLy_trigger_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
,
45 static HeapTuple
PLy_modify_tuple(PLyProcedure
*proc
, PyObject
*pltd
,
46 TriggerData
*tdata
, HeapTuple otup
);
47 static void plpython_trigger_error_callback(void *arg
);
49 static PyObject
*PLy_procedure_call(PLyProcedure
*proc
, const char *kargs
, PyObject
*vargs
);
50 static void PLy_abort_open_subtransactions(int save_subxact_level
);
53 /* function subhandler */
55 PLy_exec_function(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
57 bool is_setof
= proc
->is_setof
;
59 PyObject
*volatile plargs
= NULL
;
60 PyObject
*volatile plrv
= NULL
;
61 FuncCallContext
*volatile funcctx
= NULL
;
62 PLySRFState
*volatile srfstate
= NULL
;
63 ErrorContextCallback plerrcontext
;
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.
70 PLy_global_args_push(proc
);
76 /* First Call setup */
77 if (SRF_IS_FIRSTCALL())
79 funcctx
= SRF_FIRSTCALL_INIT();
80 srfstate
= (PLySRFState
*)
81 MemoryContextAllocZero(funcctx
->multi_call_memory_ctx
,
83 /* Immediately register cleanup callback */
84 srfstate
->callback
.func
= plpython_srf_cleanup_callback
;
85 srfstate
->callback
.arg
= (void *) srfstate
;
86 MemoryContextRegisterResetCallback(funcctx
->multi_call_memory_ctx
,
88 funcctx
->user_fctx
= (void *) srfstate
;
90 /* Every call setup */
91 funcctx
= SRF_PERCALL_SETUP();
92 Assert(funcctx
!= NULL
);
93 srfstate
= (PLySRFState
*) funcctx
->user_fctx
;
94 Assert(srfstate
!= NULL
);
97 if (srfstate
== NULL
|| srfstate
->iter
== NULL
)
100 * Non-SETOF function or first time for SETOF function: build
101 * args, then actually execute the function.
103 plargs
= PLy_function_build_args(fcinfo
, proc
);
104 plrv
= PLy_procedure_call(proc
, "args", plargs
);
105 Assert(plrv
!= NULL
);
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.
117 if (srfstate
->savedargs
)
118 PLy_function_restore_args(proc
, srfstate
->savedargs
);
119 srfstate
->savedargs
= NULL
; /* deleted by restore_args */
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.
129 if (srfstate
->iter
== NULL
)
131 /* first time -- do checks and setup */
132 ReturnSetInfo
*rsi
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
134 if (!rsi
|| !IsA(rsi
, ReturnSetInfo
) ||
135 (rsi
->allowedModes
& SFRM_ValuePerCall
) == 0)
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.")));
142 rsi
->returnMode
= SFRM_ValuePerCall
;
144 /* Make iterator out of returned object */
145 srfstate
->iter
= PyObject_GetIter(plrv
);
150 if (srfstate
->iter
== NULL
)
152 (errcode(ERRCODE_DATATYPE_MISMATCH
),
153 errmsg("returned object cannot be iterated"),
154 errdetail("PL/Python set-returning functions must return an iterable object.")));
157 /* Fetch next from iterator */
158 plrv
= PyIter_Next(srfstate
->iter
);
161 /* Iterator is exhausted or error happened */
162 bool has_error
= (PyErr_Occurred() != NULL
);
164 Py_DECREF(srfstate
->iter
);
165 srfstate
->iter
= NULL
;
168 PLy_elog(ERROR
, "error fetching next item from iterator");
170 /* Pass a null through the data-returning steps below */
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
181 srfstate
->savedargs
= PLy_function_save_args(proc
);
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
191 if (SPI_finish() != SPI_OK_FINISH
)
192 elog(ERROR
, "SPI_finish failed");
194 plerrcontext
.callback
= plpython_return_error_callback
;
195 plerrcontext
.previous
= error_context_stack
;
196 error_context_stack
= &plerrcontext
;
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).
204 if (proc
->result
.typoid
== VOIDOID
)
208 if (proc
->is_procedure
)
210 (errcode(ERRCODE_DATATYPE_MISMATCH
),
211 errmsg("PL/Python procedure did not return None")));
214 (errcode(ERRCODE_DATATYPE_MISMATCH
),
215 errmsg("PL/Python function with return type \"void\" did not return None")));
218 fcinfo
->isnull
= false;
221 else if (plrv
== Py_None
&&
222 srfstate
&& srfstate
->iter
== NULL
)
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
229 fcinfo
->isnull
= true;
235 * Normal conversion of result. However, if the result is of type
236 * RECORD, we have to set up for that each time through, since it
237 * might be different from last time.
239 if (proc
->result
.typoid
== RECORDOID
)
243 if (get_call_result_type(fcinfo
, NULL
, &desc
) != TYPEFUNC_COMPOSITE
)
245 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
246 errmsg("function returning record called in context "
247 "that cannot accept type record")));
248 PLy_output_setup_record(&proc
->result
, desc
, proc
);
251 rv
= PLy_output_convert(&proc
->result
, plrv
,
257 /* Pop old arguments from the stack if they were pushed above */
258 PLy_global_args_pop(proc
);
264 * If there was an error within a SRF, the iterator might not have
265 * been exhausted yet. Clear it so the next invocation of the
266 * function will start the iteration again. (This code is probably
267 * unnecessary now; plpython_srf_cleanup_callback should take care of
268 * cleanup. But it doesn't hurt anything to do it here.)
272 Py_XDECREF(srfstate
->iter
);
273 srfstate
->iter
= NULL
;
274 /* And drop any saved args; we won't need them */
275 if (srfstate
->savedargs
)
276 PLy_function_drop_args(srfstate
->savedargs
);
277 srfstate
->savedargs
= NULL
;
284 error_context_stack
= plerrcontext
.previous
;
286 /* Pop old arguments from the stack if they were pushed above */
287 PLy_global_args_pop(proc
);
294 /* We're in a SRF, exit appropriately */
295 if (srfstate
->iter
== NULL
)
297 /* Iterator exhausted, so we're done */
298 SRF_RETURN_DONE(funcctx
);
300 else if (fcinfo
->isnull
)
301 SRF_RETURN_NEXT_NULL(funcctx
);
303 SRF_RETURN_NEXT(funcctx
, rv
);
306 /* Plain function, just return the Datum value (possibly null) */
310 /* trigger subhandler
312 * the python function is expected to return Py_None if the tuple is
313 * acceptable and unmodified. Otherwise it should return a PyUnicode
314 * object who's value is SKIP, or MODIFY. SKIP means don't perform
315 * this action. MODIFY means the tuple has been modified, so update
316 * tuple and perform action. SKIP and MODIFY assume the trigger fires
317 * BEFORE the event and is ROW level. postgres expects the function
318 * to take no arguments and return an argument of type trigger.
321 PLy_exec_trigger(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
324 PyObject
*volatile plargs
= NULL
;
325 PyObject
*volatile plrv
= NULL
;
329 Assert(CALLED_AS_TRIGGER(fcinfo
));
330 tdata
= (TriggerData
*) fcinfo
->context
;
333 * Input/output conversion for trigger tuples. We use the result and
334 * result_in fields to store the tuple conversion info. We do this over
335 * again on each call to cover the possibility that the relation's tupdesc
336 * changed since the trigger was last called. The PLy_xxx_setup_func
337 * calls should only happen once, but PLy_input_setup_tuple and
338 * PLy_output_setup_tuple are responsible for not doing repetitive work.
340 rel_descr
= RelationGetDescr(tdata
->tg_relation
);
341 if (proc
->result
.typoid
!= rel_descr
->tdtypeid
)
342 PLy_output_setup_func(&proc
->result
, proc
->mcxt
,
346 if (proc
->result_in
.typoid
!= rel_descr
->tdtypeid
)
347 PLy_input_setup_func(&proc
->result_in
, proc
->mcxt
,
351 PLy_output_setup_tuple(&proc
->result
, rel_descr
, proc
);
352 PLy_input_setup_tuple(&proc
->result_in
, rel_descr
, proc
);
355 * If the trigger is called recursively, we must push outer-level
356 * arguments into the stack. This must be immediately before the PG_TRY
357 * to ensure that the corresponding pop happens.
359 PLy_global_args_push(proc
);
363 int rc PG_USED_FOR_ASSERTS_ONLY
;
365 rc
= SPI_register_trigger_data(tdata
);
368 plargs
= PLy_trigger_build_args(fcinfo
, proc
, &rv
);
369 plrv
= PLy_procedure_call(proc
, "TD", plargs
);
371 Assert(plrv
!= NULL
);
374 * Disconnect from SPI manager
376 if (SPI_finish() != SPI_OK_FINISH
)
377 elog(ERROR
, "SPI_finish failed");
380 * return of None means we're happy with the tuple
386 if (PyUnicode_Check(plrv
))
387 srv
= PLyUnicode_AsString(plrv
);
391 (errcode(ERRCODE_DATA_EXCEPTION
),
392 errmsg("unexpected return value from trigger procedure"),
393 errdetail("Expected None or a string.")));
394 srv
= NULL
; /* keep compiler quiet */
397 if (pg_strcasecmp(srv
, "SKIP") == 0)
399 else if (pg_strcasecmp(srv
, "MODIFY") == 0)
401 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
) ||
402 TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
403 rv
= PLy_modify_tuple(proc
, plargs
, tdata
, rv
);
406 (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
408 else if (pg_strcasecmp(srv
, "OK") != 0)
411 * accept "OK" as an alternative to None; otherwise, raise an
415 (errcode(ERRCODE_DATA_EXCEPTION
),
416 errmsg("unexpected return value from trigger procedure"),
417 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
423 PLy_global_args_pop(proc
);
432 /* helper functions for Python code execution */
435 PLy_function_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
437 PyObject
*volatile arg
= NULL
;
442 * Make any Py*_New() calls before the PG_TRY block so that we can quickly
443 * return NULL on failure. We can't return within the PG_TRY block, else
444 * we'd miss unwinding the exception stack.
446 args
= PyList_New(proc
->nargs
);
452 for (i
= 0; i
< proc
->nargs
; i
++)
454 PLyDatumToOb
*arginfo
= &proc
->args
[i
];
456 if (fcinfo
->args
[i
].isnull
)
459 arg
= PLy_input_convert(arginfo
, fcinfo
->args
[i
].value
);
467 if (PyList_SetItem(args
, i
, arg
) == -1)
468 PLy_elog(ERROR
, "PyList_SetItem() failed, while setting up arguments");
470 if (proc
->argnames
&& proc
->argnames
[i
] &&
471 PyDict_SetItemString(proc
->globals
, proc
->argnames
[i
], arg
) == -1)
472 PLy_elog(ERROR
, "PyDict_SetItemString() failed, while setting up arguments");
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.
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.
497 static PLySavedArgs
*
498 PLy_function_save_args(PLyProcedure
*proc
)
500 PLySavedArgs
*result
;
502 /* saved args are always allocated in procedure's context */
503 result
= (PLySavedArgs
*)
504 MemoryContextAllocZero(proc
->mcxt
,
505 offsetof(PLySavedArgs
, namedargs
) +
506 proc
->nargs
* sizeof(PyObject
*));
507 result
->nargs
= proc
->nargs
;
509 /* Fetch the "args" list */
510 result
->args
= PyDict_GetItemString(proc
->globals
, "args");
511 Py_XINCREF(result
->args
);
513 /* If it's a trigger, also save "TD" */
514 if (proc
->is_trigger
)
516 result
->td
= PyDict_GetItemString(proc
->globals
, "TD");
517 Py_XINCREF(result
->td
);
520 /* Fetch all the named arguments */
525 for (i
= 0; i
< result
->nargs
; i
++)
527 if (proc
->argnames
[i
])
529 result
->namedargs
[i
] = PyDict_GetItemString(proc
->globals
,
531 Py_XINCREF(result
->namedargs
[i
]);
540 * Restore procedure's arguments from a PLySavedArgs struct,
541 * then free the struct.
544 PLy_function_restore_args(PLyProcedure
*proc
, PLySavedArgs
*savedargs
)
546 /* Restore named arguments into their slots in the globals dict */
551 for (i
= 0; i
< savedargs
->nargs
; i
++)
553 if (proc
->argnames
[i
] && savedargs
->namedargs
[i
])
555 PyDict_SetItemString(proc
->globals
, proc
->argnames
[i
],
556 savedargs
->namedargs
[i
]);
557 Py_DECREF(savedargs
->namedargs
[i
]);
562 /* Restore the "args" object, too */
565 PyDict_SetItemString(proc
->globals
, "args", savedargs
->args
);
566 Py_DECREF(savedargs
->args
);
569 /* Restore the "TD" object, too */
572 PyDict_SetItemString(proc
->globals
, "TD", savedargs
->td
);
573 Py_DECREF(savedargs
->td
);
576 /* And free the PLySavedArgs struct */
581 * Free a PLySavedArgs struct without restoring the values.
584 PLy_function_drop_args(PLySavedArgs
*savedargs
)
588 /* Drop references for named args */
589 for (i
= 0; i
< savedargs
->nargs
; i
++)
591 Py_XDECREF(savedargs
->namedargs
[i
]);
594 /* Drop refs to the "args" and "TD" objects, too */
595 Py_XDECREF(savedargs
->args
);
596 Py_XDECREF(savedargs
->td
);
598 /* And free the PLySavedArgs struct */
603 * Save away any existing arguments for the given procedure, so that we can
604 * install new values for a recursive call. This should be invoked before
605 * doing PLy_function_build_args() or PLy_trigger_build_args().
607 * NB: callers must ensure that PLy_global_args_pop gets invoked once, and
608 * only once, per successful completion of PLy_global_args_push. Otherwise
609 * we'll end up out-of-sync between the actual call stack and the contents
613 PLy_global_args_push(PLyProcedure
*proc
)
615 /* We only need to push if we are already inside some active call */
616 if (proc
->calldepth
> 0)
620 /* Build a struct containing current argument values */
621 node
= PLy_function_save_args(proc
);
624 * Push the saved argument values into the procedure's stack. Once we
625 * modify either proc->argstack or proc->calldepth, we had better
626 * return without the possibility of error.
628 node
->next
= proc
->argstack
;
629 proc
->argstack
= node
;
635 * Pop old arguments when exiting a recursive call.
637 * Note: the idea here is to adjust the proc's callstack state before doing
638 * anything that could possibly fail. In event of any error, we want the
639 * callstack to look like we've done the pop. Leaking a bit of memory is
643 PLy_global_args_pop(PLyProcedure
*proc
)
645 Assert(proc
->calldepth
> 0);
646 /* We only need to pop if we were already inside some active call */
647 if (proc
->calldepth
> 1)
649 PLySavedArgs
*ptr
= proc
->argstack
;
651 /* Pop the callstack */
653 proc
->argstack
= ptr
->next
;
656 /* Restore argument values, then free ptr */
657 PLy_function_restore_args(proc
, ptr
);
661 /* Exiting call depth 1 */
662 Assert(proc
->argstack
== NULL
);
666 * We used to delete the named arguments (but not "args") from the
667 * proc's globals dict when exiting the outermost call level for a
668 * function. This seems rather pointless though: nothing can see the
669 * dict until the function is called again, at which time we'll
670 * overwrite those dict entries. So don't bother with that.
676 * Memory context deletion callback for cleaning up a PLySRFState.
677 * We need this in case execution of the SRF is terminated early,
678 * due to error or the caller simply not running it to completion.
681 plpython_srf_cleanup_callback(void *arg
)
683 PLySRFState
*srfstate
= (PLySRFState
*) arg
;
685 /* Release refcount on the iter, if we still have one */
686 Py_XDECREF(srfstate
->iter
);
687 srfstate
->iter
= NULL
;
688 /* And drop any saved args; we won't need them */
689 if (srfstate
->savedargs
)
690 PLy_function_drop_args(srfstate
->savedargs
);
691 srfstate
->savedargs
= NULL
;
695 plpython_return_error_callback(void *arg
)
697 PLyExecutionContext
*exec_ctx
= PLy_current_execution_context();
699 if (exec_ctx
->curr_proc
&&
700 !exec_ctx
->curr_proc
->is_procedure
)
701 errcontext("while creating return value");
705 PLy_trigger_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
, HeapTuple
*rv
)
707 TriggerData
*tdata
= (TriggerData
*) fcinfo
->context
;
708 TupleDesc rel_descr
= RelationGetDescr(tdata
->tg_relation
);
723 * Make any Py*_New() calls before the PG_TRY block so that we can quickly
724 * return NULL on failure. We can't return within the PG_TRY block, else
725 * we'd miss unwinding the exception stack.
727 pltdata
= PyDict_New();
731 if (tdata
->tg_trigger
->tgnargs
)
733 pltargs
= PyList_New(tdata
->tg_trigger
->tgnargs
);
748 pltname
= PLyUnicode_FromString(tdata
->tg_trigger
->tgname
);
749 PyDict_SetItemString(pltdata
, "name", pltname
);
752 stroid
= DatumGetCString(DirectFunctionCall1(oidout
,
753 ObjectIdGetDatum(tdata
->tg_relation
->rd_id
)));
754 pltrelid
= PLyUnicode_FromString(stroid
);
755 PyDict_SetItemString(pltdata
, "relid", pltrelid
);
759 stroid
= SPI_getrelname(tdata
->tg_relation
);
760 plttablename
= PLyUnicode_FromString(stroid
);
761 PyDict_SetItemString(pltdata
, "table_name", plttablename
);
762 Py_DECREF(plttablename
);
765 stroid
= SPI_getnspname(tdata
->tg_relation
);
766 plttableschema
= PLyUnicode_FromString(stroid
);
767 PyDict_SetItemString(pltdata
, "table_schema", plttableschema
);
768 Py_DECREF(plttableschema
);
771 if (TRIGGER_FIRED_BEFORE(tdata
->tg_event
))
772 pltwhen
= PLyUnicode_FromString("BEFORE");
773 else if (TRIGGER_FIRED_AFTER(tdata
->tg_event
))
774 pltwhen
= PLyUnicode_FromString("AFTER");
775 else if (TRIGGER_FIRED_INSTEAD(tdata
->tg_event
))
776 pltwhen
= PLyUnicode_FromString("INSTEAD OF");
779 elog(ERROR
, "unrecognized WHEN tg_event: %u", tdata
->tg_event
);
780 pltwhen
= NULL
; /* keep compiler quiet */
782 PyDict_SetItemString(pltdata
, "when", pltwhen
);
785 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
787 pltlevel
= PLyUnicode_FromString("ROW");
788 PyDict_SetItemString(pltdata
, "level", pltlevel
);
792 * Note: In BEFORE trigger, stored generated columns are not
793 * computed yet, so don't make them accessible in NEW row.
796 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
798 pltevent
= PLyUnicode_FromString("INSERT");
800 PyDict_SetItemString(pltdata
, "old", Py_None
);
801 pytnew
= PLy_input_from_tuple(&proc
->result_in
,
804 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
));
805 PyDict_SetItemString(pltdata
, "new", pytnew
);
807 *rv
= tdata
->tg_trigtuple
;
809 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
811 pltevent
= PLyUnicode_FromString("DELETE");
813 PyDict_SetItemString(pltdata
, "new", Py_None
);
814 pytold
= PLy_input_from_tuple(&proc
->result_in
,
818 PyDict_SetItemString(pltdata
, "old", pytold
);
820 *rv
= tdata
->tg_trigtuple
;
822 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
824 pltevent
= PLyUnicode_FromString("UPDATE");
826 pytnew
= PLy_input_from_tuple(&proc
->result_in
,
829 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
));
830 PyDict_SetItemString(pltdata
, "new", pytnew
);
832 pytold
= PLy_input_from_tuple(&proc
->result_in
,
836 PyDict_SetItemString(pltdata
, "old", pytold
);
838 *rv
= tdata
->tg_newtuple
;
842 elog(ERROR
, "unrecognized OP tg_event: %u", tdata
->tg_event
);
843 pltevent
= NULL
; /* keep compiler quiet */
846 PyDict_SetItemString(pltdata
, "event", pltevent
);
849 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata
->tg_event
))
851 pltlevel
= PLyUnicode_FromString("STATEMENT");
852 PyDict_SetItemString(pltdata
, "level", pltlevel
);
855 PyDict_SetItemString(pltdata
, "old", Py_None
);
856 PyDict_SetItemString(pltdata
, "new", Py_None
);
859 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
860 pltevent
= PLyUnicode_FromString("INSERT");
861 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
862 pltevent
= PLyUnicode_FromString("DELETE");
863 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
864 pltevent
= PLyUnicode_FromString("UPDATE");
865 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata
->tg_event
))
866 pltevent
= PLyUnicode_FromString("TRUNCATE");
869 elog(ERROR
, "unrecognized OP tg_event: %u", tdata
->tg_event
);
870 pltevent
= NULL
; /* keep compiler quiet */
873 PyDict_SetItemString(pltdata
, "event", pltevent
);
877 elog(ERROR
, "unrecognized LEVEL tg_event: %u", tdata
->tg_event
);
879 if (tdata
->tg_trigger
->tgnargs
)
887 /* pltargs should have been allocated before the PG_TRY block. */
888 Assert(pltargs
&& pltargs
!= Py_None
);
890 for (i
= 0; i
< tdata
->tg_trigger
->tgnargs
; i
++)
892 pltarg
= PLyUnicode_FromString(tdata
->tg_trigger
->tgargs
[i
]);
895 * stolen, don't Py_DECREF
897 PyList_SetItem(pltargs
, i
, pltarg
);
902 Assert(pltargs
== Py_None
);
904 PyDict_SetItemString(pltdata
, "args", pltargs
);
919 * Apply changes requested by a MODIFY return from a trigger function.
922 PLy_modify_tuple(PLyProcedure
*proc
, PyObject
*pltd
, TriggerData
*tdata
,
926 PyObject
*volatile plntup
;
927 PyObject
*volatile plkeys
;
928 PyObject
*volatile plval
;
929 Datum
*volatile modvalues
;
930 bool *volatile modnulls
;
931 bool *volatile modrepls
;
932 ErrorContextCallback plerrcontext
;
934 plerrcontext
.callback
= plpython_trigger_error_callback
;
935 plerrcontext
.previous
= error_context_stack
;
936 error_context_stack
= &plerrcontext
;
938 plntup
= plkeys
= plval
= NULL
;
949 if ((plntup
= PyDict_GetItemString(pltd
, "new")) == NULL
)
951 (errcode(ERRCODE_UNDEFINED_OBJECT
),
952 errmsg("TD[\"new\"] deleted, cannot modify row")));
954 if (!PyDict_Check(plntup
))
956 (errcode(ERRCODE_DATATYPE_MISMATCH
),
957 errmsg("TD[\"new\"] is not a dictionary")));
959 plkeys
= PyDict_Keys(plntup
);
960 nkeys
= PyList_Size(plkeys
);
962 tupdesc
= RelationGetDescr(tdata
->tg_relation
);
964 modvalues
= (Datum
*) palloc0(tupdesc
->natts
* sizeof(Datum
));
965 modnulls
= (bool *) palloc0(tupdesc
->natts
* sizeof(bool));
966 modrepls
= (bool *) palloc0(tupdesc
->natts
* sizeof(bool));
968 for (i
= 0; i
< nkeys
; i
++)
975 platt
= PyList_GetItem(plkeys
, i
);
976 if (PyUnicode_Check(platt
))
977 plattstr
= PLyUnicode_AsString(platt
);
981 (errcode(ERRCODE_DATATYPE_MISMATCH
),
982 errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i
)));
983 plattstr
= NULL
; /* keep compiler quiet */
985 attn
= SPI_fnumber(tupdesc
, plattstr
);
986 if (attn
== SPI_ERROR_NOATTRIBUTE
)
988 (errcode(ERRCODE_UNDEFINED_COLUMN
),
989 errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
993 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
994 errmsg("cannot set system attribute \"%s\"",
996 if (TupleDescAttr(tupdesc
, attn
- 1)->attgenerated
)
998 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED
),
999 errmsg("cannot set generated column \"%s\"",
1002 plval
= PyDict_GetItem(plntup
, platt
);
1004 elog(FATAL
, "Python interpreter is probably corrupted");
1008 /* We assume proc->result is set up to convert tuples properly */
1009 att
= &proc
->result
.u
.tuple
.atts
[attn
- 1];
1011 modvalues
[attn
- 1] = PLy_output_convert(att
,
1013 &modnulls
[attn
- 1]);
1014 modrepls
[attn
- 1] = true;
1020 rtup
= heap_modify_tuple(otup
, tupdesc
, modvalues
, modnulls
, modrepls
);
1046 error_context_stack
= plerrcontext
.previous
;
1052 plpython_trigger_error_callback(void *arg
)
1054 PLyExecutionContext
*exec_ctx
= PLy_current_execution_context();
1056 if (exec_ctx
->curr_proc
)
1057 errcontext("while modifying trigger row");
1060 /* execute Python code, propagate Python errors to the backend */
1062 PLy_procedure_call(PLyProcedure
*proc
, const char *kargs
, PyObject
*vargs
)
1064 PyObject
*rv
= NULL
;
1065 int volatile save_subxact_level
= list_length(explicit_subtransactions
);
1067 PyDict_SetItemString(proc
->globals
, kargs
, vargs
);
1071 #if PY_VERSION_HEX >= 0x03020000
1072 rv
= PyEval_EvalCode(proc
->code
,
1073 proc
->globals
, proc
->globals
);
1075 rv
= PyEval_EvalCode((PyCodeObject
*) proc
->code
,
1076 proc
->globals
, proc
->globals
);
1080 * Since plpy will only let you close subtransactions that you
1081 * started, you cannot *unnest* subtransactions, only *nest* them
1084 Assert(list_length(explicit_subtransactions
) >= save_subxact_level
);
1088 PLy_abort_open_subtransactions(save_subxact_level
);
1092 /* If the Python code returned an error, propagate it */
1094 PLy_elog(ERROR
, NULL
);
1100 * Abort lingering subtransactions that have been explicitly started
1101 * by plpy.subtransaction().start() and not properly closed.
1104 PLy_abort_open_subtransactions(int save_subxact_level
)
1106 Assert(save_subxact_level
>= 0);
1108 while (list_length(explicit_subtransactions
) > save_subxact_level
)
1110 PLySubtransactionData
*subtransactiondata
;
1112 Assert(explicit_subtransactions
!= NIL
);
1115 (errmsg("forcibly aborting a subtransaction that has not been exited")));
1117 RollbackAndReleaseCurrentSubTransaction();
1119 subtransactiondata
= (PLySubtransactionData
*) linitial(explicit_subtransactions
);
1120 explicit_subtransactions
= list_delete_first(explicit_subtransactions
);
1122 MemoryContextSwitchTo(subtransactiondata
->oldcontext
);
1123 CurrentResourceOwner
= subtransactiondata
->oldowner
;
1124 pfree(subtransactiondata
);