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/fmgrprotos.h"
22 #include "utils/rel.h"
24 /* saved state for a set-returning function */
25 typedef struct PLySRFState
27 PyObject
*iter
; /* Python iterator producing results */
28 PLySavedArgs
*savedargs
; /* function argument values */
29 MemoryContextCallback callback
; /* for releasing refcounts when done */
32 static PyObject
*PLy_function_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
);
33 static PLySavedArgs
*PLy_function_save_args(PLyProcedure
*proc
);
34 static void PLy_function_restore_args(PLyProcedure
*proc
, PLySavedArgs
*savedargs
);
35 static void PLy_function_drop_args(PLySavedArgs
*savedargs
);
36 static void PLy_global_args_push(PLyProcedure
*proc
);
37 static void PLy_global_args_pop(PLyProcedure
*proc
);
38 static void plpython_srf_cleanup_callback(void *arg
);
39 static void plpython_return_error_callback(void *arg
);
41 static PyObject
*PLy_trigger_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
,
43 static HeapTuple
PLy_modify_tuple(PLyProcedure
*proc
, PyObject
*pltd
,
44 TriggerData
*tdata
, HeapTuple otup
);
45 static void plpython_trigger_error_callback(void *arg
);
47 static PyObject
*PLy_procedure_call(PLyProcedure
*proc
, const char *kargs
, PyObject
*vargs
);
48 static void PLy_abort_open_subtransactions(int save_subxact_level
);
51 /* function subhandler */
53 PLy_exec_function(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
55 bool is_setof
= proc
->is_setof
;
57 PyObject
*volatile plargs
= NULL
;
58 PyObject
*volatile plrv
= NULL
;
59 FuncCallContext
*volatile funcctx
= NULL
;
60 PLySRFState
*volatile srfstate
= NULL
;
61 ErrorContextCallback plerrcontext
;
64 * If the function is called recursively, we must push outer-level
65 * arguments into the stack. This must be immediately before the PG_TRY
66 * to ensure that the corresponding pop happens.
68 PLy_global_args_push(proc
);
74 /* First Call setup */
75 if (SRF_IS_FIRSTCALL())
77 funcctx
= SRF_FIRSTCALL_INIT();
78 srfstate
= (PLySRFState
*)
79 MemoryContextAllocZero(funcctx
->multi_call_memory_ctx
,
81 /* Immediately register cleanup callback */
82 srfstate
->callback
.func
= plpython_srf_cleanup_callback
;
83 srfstate
->callback
.arg
= srfstate
;
84 MemoryContextRegisterResetCallback(funcctx
->multi_call_memory_ctx
,
86 funcctx
->user_fctx
= srfstate
;
88 /* Every call setup */
89 funcctx
= SRF_PERCALL_SETUP();
90 Assert(funcctx
!= NULL
);
91 srfstate
= (PLySRFState
*) funcctx
->user_fctx
;
92 Assert(srfstate
!= NULL
);
95 if (srfstate
== NULL
|| srfstate
->iter
== NULL
)
98 * Non-SETOF function or first time for SETOF function: build
99 * args, then actually execute the function.
101 plargs
= PLy_function_build_args(fcinfo
, proc
);
102 plrv
= PLy_procedure_call(proc
, "args", plargs
);
103 Assert(plrv
!= NULL
);
108 * Second or later call for a SETOF function: restore arguments in
109 * globals dict to what they were when we left off. We must do
110 * this in case multiple evaluations of the same SETOF function
111 * are interleaved. It's a bit annoying, since the iterator may
112 * not look at the arguments at all, but we have no way to know
113 * that. Fortunately this isn't terribly expensive.
115 if (srfstate
->savedargs
)
116 PLy_function_restore_args(proc
, srfstate
->savedargs
);
117 srfstate
->savedargs
= NULL
; /* deleted by restore_args */
121 * If it returns a set, call the iterator to get the next return item.
122 * We stay in the SPI context while doing this, because PyIter_Next()
123 * calls back into Python code which might contain SPI calls.
127 if (srfstate
->iter
== NULL
)
129 /* first time -- do checks and setup */
130 ReturnSetInfo
*rsi
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
132 if (!rsi
|| !IsA(rsi
, ReturnSetInfo
) ||
133 (rsi
->allowedModes
& SFRM_ValuePerCall
) == 0)
136 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
137 errmsg("unsupported set function return mode"),
138 errdetail("PL/Python set-returning functions only support returning one value per call.")));
140 rsi
->returnMode
= SFRM_ValuePerCall
;
142 /* Make iterator out of returned object */
143 srfstate
->iter
= PyObject_GetIter(plrv
);
148 if (srfstate
->iter
== NULL
)
150 (errcode(ERRCODE_DATATYPE_MISMATCH
),
151 errmsg("returned object cannot be iterated"),
152 errdetail("PL/Python set-returning functions must return an iterable object.")));
155 /* Fetch next from iterator */
156 plrv
= PyIter_Next(srfstate
->iter
);
159 /* Iterator is exhausted or error happened */
160 bool has_error
= (PyErr_Occurred() != NULL
);
162 Py_DECREF(srfstate
->iter
);
163 srfstate
->iter
= NULL
;
166 PLy_elog(ERROR
, "error fetching next item from iterator");
168 /* Pass a null through the data-returning steps below */
175 * This won't be last call, so save argument values. We do
176 * this again each time in case the iterator is changing those
179 srfstate
->savedargs
= PLy_function_save_args(proc
);
184 * Disconnect from SPI manager and then create the return values datum
185 * (if the input function does a palloc for it this must not be
186 * allocated in the SPI memory context because SPI_finish would free
189 if (SPI_finish() != SPI_OK_FINISH
)
190 elog(ERROR
, "SPI_finish failed");
192 plerrcontext
.callback
= plpython_return_error_callback
;
193 plerrcontext
.previous
= error_context_stack
;
194 error_context_stack
= &plerrcontext
;
197 * For a procedure or function declared to return void, the Python
198 * return value must be None. For void-returning functions, we also
199 * treat a None return value as a special "void datum" rather than
200 * NULL (as is the case for non-void-returning functions).
202 if (proc
->result
.typoid
== VOIDOID
)
206 if (proc
->is_procedure
)
208 (errcode(ERRCODE_DATATYPE_MISMATCH
),
209 errmsg("PL/Python procedure did not return None")));
212 (errcode(ERRCODE_DATATYPE_MISMATCH
),
213 errmsg("PL/Python function with return type \"void\" did not return None")));
216 fcinfo
->isnull
= false;
219 else if (plrv
== Py_None
&&
220 srfstate
&& srfstate
->iter
== NULL
)
223 * In a SETOF function, the iteration-ending null isn't a real
224 * value; don't pass it through the input function, which might
227 fcinfo
->isnull
= true;
233 * Normal conversion of result. However, if the result is of type
234 * RECORD, we have to set up for that each time through, since it
235 * might be different from last time.
237 if (proc
->result
.typoid
== RECORDOID
)
241 if (get_call_result_type(fcinfo
, NULL
, &desc
) != TYPEFUNC_COMPOSITE
)
243 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
244 errmsg("function returning record called in context "
245 "that cannot accept type record")));
246 PLy_output_setup_record(&proc
->result
, desc
, proc
);
249 rv
= PLy_output_convert(&proc
->result
, plrv
,
255 /* Pop old arguments from the stack if they were pushed above */
256 PLy_global_args_pop(proc
);
262 * If there was an error within a SRF, the iterator might not have
263 * been exhausted yet. Clear it so the next invocation of the
264 * function will start the iteration again. (This code is probably
265 * unnecessary now; plpython_srf_cleanup_callback should take care of
266 * cleanup. But it doesn't hurt anything to do it here.)
270 Py_XDECREF(srfstate
->iter
);
271 srfstate
->iter
= NULL
;
272 /* And drop any saved args; we won't need them */
273 if (srfstate
->savedargs
)
274 PLy_function_drop_args(srfstate
->savedargs
);
275 srfstate
->savedargs
= NULL
;
282 error_context_stack
= plerrcontext
.previous
;
284 /* Pop old arguments from the stack if they were pushed above */
285 PLy_global_args_pop(proc
);
292 /* We're in a SRF, exit appropriately */
293 if (srfstate
->iter
== NULL
)
295 /* Iterator exhausted, so we're done */
296 SRF_RETURN_DONE(funcctx
);
298 else if (fcinfo
->isnull
)
299 SRF_RETURN_NEXT_NULL(funcctx
);
301 SRF_RETURN_NEXT(funcctx
, rv
);
304 /* Plain function, just return the Datum value (possibly null) */
308 /* trigger subhandler
310 * the python function is expected to return Py_None if the tuple is
311 * acceptable and unmodified. Otherwise it should return a PyUnicode
312 * object who's value is SKIP, or MODIFY. SKIP means don't perform
313 * this action. MODIFY means the tuple has been modified, so update
314 * tuple and perform action. SKIP and MODIFY assume the trigger fires
315 * BEFORE the event and is ROW level. postgres expects the function
316 * to take no arguments and return an argument of type trigger.
319 PLy_exec_trigger(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
322 PyObject
*volatile plargs
= NULL
;
323 PyObject
*volatile plrv
= NULL
;
327 Assert(CALLED_AS_TRIGGER(fcinfo
));
328 tdata
= (TriggerData
*) fcinfo
->context
;
331 * Input/output conversion for trigger tuples. We use the result and
332 * result_in fields to store the tuple conversion info. We do this over
333 * again on each call to cover the possibility that the relation's tupdesc
334 * changed since the trigger was last called. The PLy_xxx_setup_func
335 * calls should only happen once, but PLy_input_setup_tuple and
336 * PLy_output_setup_tuple are responsible for not doing repetitive work.
338 rel_descr
= RelationGetDescr(tdata
->tg_relation
);
339 if (proc
->result
.typoid
!= rel_descr
->tdtypeid
)
340 PLy_output_setup_func(&proc
->result
, proc
->mcxt
,
344 if (proc
->result_in
.typoid
!= rel_descr
->tdtypeid
)
345 PLy_input_setup_func(&proc
->result_in
, proc
->mcxt
,
349 PLy_output_setup_tuple(&proc
->result
, rel_descr
, proc
);
350 PLy_input_setup_tuple(&proc
->result_in
, rel_descr
, proc
);
353 * If the trigger is called recursively, we must push outer-level
354 * arguments into the stack. This must be immediately before the PG_TRY
355 * to ensure that the corresponding pop happens.
357 PLy_global_args_push(proc
);
361 int rc PG_USED_FOR_ASSERTS_ONLY
;
363 rc
= SPI_register_trigger_data(tdata
);
366 plargs
= PLy_trigger_build_args(fcinfo
, proc
, &rv
);
367 plrv
= PLy_procedure_call(proc
, "TD", plargs
);
369 Assert(plrv
!= NULL
);
372 * Disconnect from SPI manager
374 if (SPI_finish() != SPI_OK_FINISH
)
375 elog(ERROR
, "SPI_finish failed");
378 * return of None means we're happy with the tuple
384 if (PyUnicode_Check(plrv
))
385 srv
= PLyUnicode_AsString(plrv
);
389 (errcode(ERRCODE_DATA_EXCEPTION
),
390 errmsg("unexpected return value from trigger procedure"),
391 errdetail("Expected None or a string.")));
392 srv
= NULL
; /* keep compiler quiet */
395 if (pg_strcasecmp(srv
, "SKIP") == 0)
397 else if (pg_strcasecmp(srv
, "MODIFY") == 0)
399 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
) ||
400 TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
401 rv
= PLy_modify_tuple(proc
, plargs
, tdata
, rv
);
404 (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
406 else if (pg_strcasecmp(srv
, "OK") != 0)
409 * accept "OK" as an alternative to None; otherwise, raise an
413 (errcode(ERRCODE_DATA_EXCEPTION
),
414 errmsg("unexpected return value from trigger procedure"),
415 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
421 PLy_global_args_pop(proc
);
430 /* helper functions for Python code execution */
433 PLy_function_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
435 PyObject
*volatile arg
= NULL
;
440 * Make any Py*_New() calls before the PG_TRY block so that we can quickly
441 * return NULL on failure. We can't return within the PG_TRY block, else
442 * we'd miss unwinding the exception stack.
444 args
= PyList_New(proc
->nargs
);
450 for (i
= 0; i
< proc
->nargs
; i
++)
452 PLyDatumToOb
*arginfo
= &proc
->args
[i
];
454 if (fcinfo
->args
[i
].isnull
)
457 arg
= PLy_input_convert(arginfo
, fcinfo
->args
[i
].value
);
465 if (PyList_SetItem(args
, i
, arg
) == -1)
466 PLy_elog(ERROR
, "PyList_SetItem() failed, while setting up arguments");
468 if (proc
->argnames
&& proc
->argnames
[i
] &&
469 PyDict_SetItemString(proc
->globals
, proc
->argnames
[i
], arg
) == -1)
470 PLy_elog(ERROR
, "PyDict_SetItemString() failed, while setting up arguments");
487 * Construct a PLySavedArgs struct representing the current values of the
488 * procedure's arguments in its globals dict. This can be used to restore
489 * those values when exiting a recursive call level or returning control to a
490 * set-returning function.
492 * This would not be necessary except for an ancient decision to make args
493 * available via the proc's globals :-( ... but we're stuck with that now.
495 static PLySavedArgs
*
496 PLy_function_save_args(PLyProcedure
*proc
)
498 PLySavedArgs
*result
;
500 /* saved args are always allocated in procedure's context */
501 result
= (PLySavedArgs
*)
502 MemoryContextAllocZero(proc
->mcxt
,
503 offsetof(PLySavedArgs
, namedargs
) +
504 proc
->nargs
* sizeof(PyObject
*));
505 result
->nargs
= proc
->nargs
;
507 /* Fetch the "args" list */
508 result
->args
= PyDict_GetItemString(proc
->globals
, "args");
509 Py_XINCREF(result
->args
);
511 /* If it's a trigger, also save "TD" */
512 if (proc
->is_trigger
)
514 result
->td
= PyDict_GetItemString(proc
->globals
, "TD");
515 Py_XINCREF(result
->td
);
518 /* Fetch all the named arguments */
523 for (i
= 0; i
< result
->nargs
; i
++)
525 if (proc
->argnames
[i
])
527 result
->namedargs
[i
] = PyDict_GetItemString(proc
->globals
,
529 Py_XINCREF(result
->namedargs
[i
]);
538 * Restore procedure's arguments from a PLySavedArgs struct,
539 * then free the struct.
542 PLy_function_restore_args(PLyProcedure
*proc
, PLySavedArgs
*savedargs
)
544 /* Restore named arguments into their slots in the globals dict */
549 for (i
= 0; i
< savedargs
->nargs
; i
++)
551 if (proc
->argnames
[i
] && savedargs
->namedargs
[i
])
553 PyDict_SetItemString(proc
->globals
, proc
->argnames
[i
],
554 savedargs
->namedargs
[i
]);
555 Py_DECREF(savedargs
->namedargs
[i
]);
560 /* Restore the "args" object, too */
563 PyDict_SetItemString(proc
->globals
, "args", savedargs
->args
);
564 Py_DECREF(savedargs
->args
);
567 /* Restore the "TD" object, too */
570 PyDict_SetItemString(proc
->globals
, "TD", savedargs
->td
);
571 Py_DECREF(savedargs
->td
);
574 /* And free the PLySavedArgs struct */
579 * Free a PLySavedArgs struct without restoring the values.
582 PLy_function_drop_args(PLySavedArgs
*savedargs
)
586 /* Drop references for named args */
587 for (i
= 0; i
< savedargs
->nargs
; i
++)
589 Py_XDECREF(savedargs
->namedargs
[i
]);
592 /* Drop refs to the "args" and "TD" objects, too */
593 Py_XDECREF(savedargs
->args
);
594 Py_XDECREF(savedargs
->td
);
596 /* And free the PLySavedArgs struct */
601 * Save away any existing arguments for the given procedure, so that we can
602 * install new values for a recursive call. This should be invoked before
603 * doing PLy_function_build_args() or PLy_trigger_build_args().
605 * NB: callers must ensure that PLy_global_args_pop gets invoked once, and
606 * only once, per successful completion of PLy_global_args_push. Otherwise
607 * we'll end up out-of-sync between the actual call stack and the contents
611 PLy_global_args_push(PLyProcedure
*proc
)
613 /* We only need to push if we are already inside some active call */
614 if (proc
->calldepth
> 0)
618 /* Build a struct containing current argument values */
619 node
= PLy_function_save_args(proc
);
622 * Push the saved argument values into the procedure's stack. Once we
623 * modify either proc->argstack or proc->calldepth, we had better
624 * return without the possibility of error.
626 node
->next
= proc
->argstack
;
627 proc
->argstack
= node
;
633 * Pop old arguments when exiting a recursive call.
635 * Note: the idea here is to adjust the proc's callstack state before doing
636 * anything that could possibly fail. In event of any error, we want the
637 * callstack to look like we've done the pop. Leaking a bit of memory is
641 PLy_global_args_pop(PLyProcedure
*proc
)
643 Assert(proc
->calldepth
> 0);
644 /* We only need to pop if we were already inside some active call */
645 if (proc
->calldepth
> 1)
647 PLySavedArgs
*ptr
= proc
->argstack
;
649 /* Pop the callstack */
651 proc
->argstack
= ptr
->next
;
654 /* Restore argument values, then free ptr */
655 PLy_function_restore_args(proc
, ptr
);
659 /* Exiting call depth 1 */
660 Assert(proc
->argstack
== NULL
);
664 * We used to delete the named arguments (but not "args") from the
665 * proc's globals dict when exiting the outermost call level for a
666 * function. This seems rather pointless though: nothing can see the
667 * dict until the function is called again, at which time we'll
668 * overwrite those dict entries. So don't bother with that.
674 * Memory context deletion callback for cleaning up a PLySRFState.
675 * We need this in case execution of the SRF is terminated early,
676 * due to error or the caller simply not running it to completion.
679 plpython_srf_cleanup_callback(void *arg
)
681 PLySRFState
*srfstate
= (PLySRFState
*) arg
;
683 /* Release refcount on the iter, if we still have one */
684 Py_XDECREF(srfstate
->iter
);
685 srfstate
->iter
= NULL
;
686 /* And drop any saved args; we won't need them */
687 if (srfstate
->savedargs
)
688 PLy_function_drop_args(srfstate
->savedargs
);
689 srfstate
->savedargs
= NULL
;
693 plpython_return_error_callback(void *arg
)
695 PLyExecutionContext
*exec_ctx
= PLy_current_execution_context();
697 if (exec_ctx
->curr_proc
&&
698 !exec_ctx
->curr_proc
->is_procedure
)
699 errcontext("while creating return value");
703 PLy_trigger_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
, HeapTuple
*rv
)
705 TriggerData
*tdata
= (TriggerData
*) fcinfo
->context
;
706 TupleDesc rel_descr
= RelationGetDescr(tdata
->tg_relation
);
721 * Make any Py*_New() calls before the PG_TRY block so that we can quickly
722 * return NULL on failure. We can't return within the PG_TRY block, else
723 * we'd miss unwinding the exception stack.
725 pltdata
= PyDict_New();
729 if (tdata
->tg_trigger
->tgnargs
)
731 pltargs
= PyList_New(tdata
->tg_trigger
->tgnargs
);
746 pltname
= PLyUnicode_FromString(tdata
->tg_trigger
->tgname
);
747 PyDict_SetItemString(pltdata
, "name", pltname
);
750 stroid
= DatumGetCString(DirectFunctionCall1(oidout
,
751 ObjectIdGetDatum(tdata
->tg_relation
->rd_id
)));
752 pltrelid
= PLyUnicode_FromString(stroid
);
753 PyDict_SetItemString(pltdata
, "relid", pltrelid
);
757 stroid
= SPI_getrelname(tdata
->tg_relation
);
758 plttablename
= PLyUnicode_FromString(stroid
);
759 PyDict_SetItemString(pltdata
, "table_name", plttablename
);
760 Py_DECREF(plttablename
);
763 stroid
= SPI_getnspname(tdata
->tg_relation
);
764 plttableschema
= PLyUnicode_FromString(stroid
);
765 PyDict_SetItemString(pltdata
, "table_schema", plttableschema
);
766 Py_DECREF(plttableschema
);
769 if (TRIGGER_FIRED_BEFORE(tdata
->tg_event
))
770 pltwhen
= PLyUnicode_FromString("BEFORE");
771 else if (TRIGGER_FIRED_AFTER(tdata
->tg_event
))
772 pltwhen
= PLyUnicode_FromString("AFTER");
773 else if (TRIGGER_FIRED_INSTEAD(tdata
->tg_event
))
774 pltwhen
= PLyUnicode_FromString("INSTEAD OF");
777 elog(ERROR
, "unrecognized WHEN tg_event: %u", tdata
->tg_event
);
778 pltwhen
= NULL
; /* keep compiler quiet */
780 PyDict_SetItemString(pltdata
, "when", pltwhen
);
783 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
785 pltlevel
= PLyUnicode_FromString("ROW");
786 PyDict_SetItemString(pltdata
, "level", pltlevel
);
790 * Note: In BEFORE trigger, stored generated columns are not
791 * computed yet, so don't make them accessible in NEW row.
794 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
796 pltevent
= PLyUnicode_FromString("INSERT");
798 PyDict_SetItemString(pltdata
, "old", Py_None
);
799 pytnew
= PLy_input_from_tuple(&proc
->result_in
,
802 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
));
803 PyDict_SetItemString(pltdata
, "new", pytnew
);
805 *rv
= tdata
->tg_trigtuple
;
807 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
809 pltevent
= PLyUnicode_FromString("DELETE");
811 PyDict_SetItemString(pltdata
, "new", Py_None
);
812 pytold
= PLy_input_from_tuple(&proc
->result_in
,
816 PyDict_SetItemString(pltdata
, "old", pytold
);
818 *rv
= tdata
->tg_trigtuple
;
820 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
822 pltevent
= PLyUnicode_FromString("UPDATE");
824 pytnew
= PLy_input_from_tuple(&proc
->result_in
,
827 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
));
828 PyDict_SetItemString(pltdata
, "new", pytnew
);
830 pytold
= PLy_input_from_tuple(&proc
->result_in
,
834 PyDict_SetItemString(pltdata
, "old", pytold
);
836 *rv
= tdata
->tg_newtuple
;
840 elog(ERROR
, "unrecognized OP tg_event: %u", tdata
->tg_event
);
841 pltevent
= NULL
; /* keep compiler quiet */
844 PyDict_SetItemString(pltdata
, "event", pltevent
);
847 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata
->tg_event
))
849 pltlevel
= PLyUnicode_FromString("STATEMENT");
850 PyDict_SetItemString(pltdata
, "level", pltlevel
);
853 PyDict_SetItemString(pltdata
, "old", Py_None
);
854 PyDict_SetItemString(pltdata
, "new", Py_None
);
857 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
858 pltevent
= PLyUnicode_FromString("INSERT");
859 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
860 pltevent
= PLyUnicode_FromString("DELETE");
861 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
862 pltevent
= PLyUnicode_FromString("UPDATE");
863 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata
->tg_event
))
864 pltevent
= PLyUnicode_FromString("TRUNCATE");
867 elog(ERROR
, "unrecognized OP tg_event: %u", tdata
->tg_event
);
868 pltevent
= NULL
; /* keep compiler quiet */
871 PyDict_SetItemString(pltdata
, "event", pltevent
);
875 elog(ERROR
, "unrecognized LEVEL tg_event: %u", tdata
->tg_event
);
877 if (tdata
->tg_trigger
->tgnargs
)
885 /* pltargs should have been allocated before the PG_TRY block. */
886 Assert(pltargs
&& pltargs
!= Py_None
);
888 for (i
= 0; i
< tdata
->tg_trigger
->tgnargs
; i
++)
890 pltarg
= PLyUnicode_FromString(tdata
->tg_trigger
->tgargs
[i
]);
893 * stolen, don't Py_DECREF
895 PyList_SetItem(pltargs
, i
, pltarg
);
900 Assert(pltargs
== Py_None
);
902 PyDict_SetItemString(pltdata
, "args", pltargs
);
917 * Apply changes requested by a MODIFY return from a trigger function.
920 PLy_modify_tuple(PLyProcedure
*proc
, PyObject
*pltd
, TriggerData
*tdata
,
924 PyObject
*volatile plntup
;
925 PyObject
*volatile plkeys
;
926 PyObject
*volatile plval
;
927 Datum
*volatile modvalues
;
928 bool *volatile modnulls
;
929 bool *volatile modrepls
;
930 ErrorContextCallback plerrcontext
;
932 plerrcontext
.callback
= plpython_trigger_error_callback
;
933 plerrcontext
.previous
= error_context_stack
;
934 error_context_stack
= &plerrcontext
;
936 plntup
= plkeys
= plval
= NULL
;
947 if ((plntup
= PyDict_GetItemString(pltd
, "new")) == NULL
)
949 (errcode(ERRCODE_UNDEFINED_OBJECT
),
950 errmsg("TD[\"new\"] deleted, cannot modify row")));
952 if (!PyDict_Check(plntup
))
954 (errcode(ERRCODE_DATATYPE_MISMATCH
),
955 errmsg("TD[\"new\"] is not a dictionary")));
957 plkeys
= PyDict_Keys(plntup
);
958 nkeys
= PyList_Size(plkeys
);
960 tupdesc
= RelationGetDescr(tdata
->tg_relation
);
962 modvalues
= (Datum
*) palloc0(tupdesc
->natts
* sizeof(Datum
));
963 modnulls
= (bool *) palloc0(tupdesc
->natts
* sizeof(bool));
964 modrepls
= (bool *) palloc0(tupdesc
->natts
* sizeof(bool));
966 for (i
= 0; i
< nkeys
; i
++)
973 platt
= PyList_GetItem(plkeys
, i
);
974 if (PyUnicode_Check(platt
))
975 plattstr
= PLyUnicode_AsString(platt
);
979 (errcode(ERRCODE_DATATYPE_MISMATCH
),
980 errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i
)));
981 plattstr
= NULL
; /* keep compiler quiet */
983 attn
= SPI_fnumber(tupdesc
, plattstr
);
984 if (attn
== SPI_ERROR_NOATTRIBUTE
)
986 (errcode(ERRCODE_UNDEFINED_COLUMN
),
987 errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
991 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
992 errmsg("cannot set system attribute \"%s\"",
994 if (TupleDescAttr(tupdesc
, attn
- 1)->attgenerated
)
996 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED
),
997 errmsg("cannot set generated column \"%s\"",
1000 plval
= PyDict_GetItem(plntup
, platt
);
1002 elog(FATAL
, "Python interpreter is probably corrupted");
1006 /* We assume proc->result is set up to convert tuples properly */
1007 att
= &proc
->result
.u
.tuple
.atts
[attn
- 1];
1009 modvalues
[attn
- 1] = PLy_output_convert(att
,
1011 &modnulls
[attn
- 1]);
1012 modrepls
[attn
- 1] = true;
1018 rtup
= heap_modify_tuple(otup
, tupdesc
, modvalues
, modnulls
, modrepls
);
1044 error_context_stack
= plerrcontext
.previous
;
1050 plpython_trigger_error_callback(void *arg
)
1052 PLyExecutionContext
*exec_ctx
= PLy_current_execution_context();
1054 if (exec_ctx
->curr_proc
)
1055 errcontext("while modifying trigger row");
1058 /* execute Python code, propagate Python errors to the backend */
1060 PLy_procedure_call(PLyProcedure
*proc
, const char *kargs
, PyObject
*vargs
)
1062 PyObject
*rv
= NULL
;
1063 int volatile save_subxact_level
= list_length(explicit_subtransactions
);
1065 PyDict_SetItemString(proc
->globals
, kargs
, vargs
);
1069 #if PY_VERSION_HEX >= 0x03020000
1070 rv
= PyEval_EvalCode(proc
->code
,
1071 proc
->globals
, proc
->globals
);
1073 rv
= PyEval_EvalCode((PyCodeObject
*) proc
->code
,
1074 proc
->globals
, proc
->globals
);
1078 * Since plpy will only let you close subtransactions that you
1079 * started, you cannot *unnest* subtransactions, only *nest* them
1082 Assert(list_length(explicit_subtransactions
) >= save_subxact_level
);
1086 PLy_abort_open_subtransactions(save_subxact_level
);
1090 /* If the Python code returned an error, propagate it */
1092 PLy_elog(ERROR
, NULL
);
1098 * Abort lingering subtransactions that have been explicitly started
1099 * by plpy.subtransaction().start() and not properly closed.
1102 PLy_abort_open_subtransactions(int save_subxact_level
)
1104 Assert(save_subxact_level
>= 0);
1106 while (list_length(explicit_subtransactions
) > save_subxact_level
)
1108 PLySubtransactionData
*subtransactiondata
;
1110 Assert(explicit_subtransactions
!= NIL
);
1113 (errmsg("forcibly aborting a subtransaction that has not been exited")));
1115 RollbackAndReleaseCurrentSubTransaction();
1117 subtransactiondata
= (PLySubtransactionData
*) linitial(explicit_subtransactions
);
1118 explicit_subtransactions
= list_delete_first(explicit_subtransactions
);
1120 MemoryContextSwitchTo(subtransactiondata
->oldcontext
);
1121 CurrentResourceOwner
= subtransactiondata
->oldowner
;
1122 pfree(subtransactiondata
);