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;
234 /* Normal conversion of result */
235 rv
= PLy_output_convert(&proc
->result
, plrv
,
241 /* Pop old arguments from the stack if they were pushed above */
242 PLy_global_args_pop(proc
);
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.)
256 Py_XDECREF(srfstate
->iter
);
257 srfstate
->iter
= NULL
;
258 /* And drop any saved args; we won't need them */
259 if (srfstate
->savedargs
)
260 PLy_function_drop_args(srfstate
->savedargs
);
261 srfstate
->savedargs
= NULL
;
268 error_context_stack
= plerrcontext
.previous
;
270 /* Pop old arguments from the stack if they were pushed above */
271 PLy_global_args_pop(proc
);
278 /* We're in a SRF, exit appropriately */
279 if (srfstate
->iter
== NULL
)
281 /* Iterator exhausted, so we're done */
282 SRF_RETURN_DONE(funcctx
);
284 else if (fcinfo
->isnull
)
285 SRF_RETURN_NEXT_NULL(funcctx
);
287 SRF_RETURN_NEXT(funcctx
, rv
);
290 /* Plain function, just return the Datum value (possibly null) */
294 /* trigger subhandler
296 * the python function is expected to return Py_None if the tuple is
297 * acceptable and unmodified. Otherwise it should return a PyString
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.
305 PLy_exec_trigger(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
308 PyObject
*volatile plargs
= NULL
;
309 PyObject
*volatile plrv
= NULL
;
313 Assert(CALLED_AS_TRIGGER(fcinfo
));
314 tdata
= (TriggerData
*) fcinfo
->context
;
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.
324 rel_descr
= RelationGetDescr(tdata
->tg_relation
);
325 if (proc
->result
.typoid
!= rel_descr
->tdtypeid
)
326 PLy_output_setup_func(&proc
->result
, proc
->mcxt
,
330 if (proc
->result_in
.typoid
!= rel_descr
->tdtypeid
)
331 PLy_input_setup_func(&proc
->result_in
, proc
->mcxt
,
335 PLy_output_setup_tuple(&proc
->result
, rel_descr
, proc
);
336 PLy_input_setup_tuple(&proc
->result_in
, rel_descr
, proc
);
340 int rc PG_USED_FOR_ASSERTS_ONLY
;
342 rc
= SPI_register_trigger_data(tdata
);
345 plargs
= PLy_trigger_build_args(fcinfo
, proc
, &rv
);
346 plrv
= PLy_procedure_call(proc
, "TD", plargs
);
348 Assert(plrv
!= NULL
);
351 * Disconnect from SPI manager
353 if (SPI_finish() != SPI_OK_FINISH
)
354 elog(ERROR
, "SPI_finish failed");
357 * return of None means we're happy with the tuple
363 if (PyString_Check(plrv
))
364 srv
= PyString_AsString(plrv
);
365 else if (PyUnicode_Check(plrv
))
366 srv
= PLyUnicode_AsString(plrv
);
370 (errcode(ERRCODE_DATA_EXCEPTION
),
371 errmsg("unexpected return value from trigger procedure"),
372 errdetail("Expected None or a string.")));
373 srv
= NULL
; /* keep compiler quiet */
376 if (pg_strcasecmp(srv
, "SKIP") == 0)
378 else if (pg_strcasecmp(srv
, "MODIFY") == 0)
380 TriggerData
*tdata
= (TriggerData
*) fcinfo
->context
;
382 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
) ||
383 TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
384 rv
= PLy_modify_tuple(proc
, plargs
, tdata
, rv
);
387 (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
389 else if (pg_strcasecmp(srv
, "OK") != 0)
392 * accept "OK" as an alternative to None; otherwise, raise an
396 (errcode(ERRCODE_DATA_EXCEPTION
),
397 errmsg("unexpected return value from trigger procedure"),
398 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
412 /* helper functions for Python code execution */
415 PLy_function_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
)
417 PyObject
*volatile arg
= NULL
;
418 PyObject
*volatile args
= NULL
;
423 args
= PyList_New(proc
->nargs
);
427 for (i
= 0; i
< proc
->nargs
; i
++)
429 PLyDatumToOb
*arginfo
= &proc
->args
[i
];
431 if (fcinfo
->args
[i
].isnull
)
434 arg
= PLy_input_convert(arginfo
, fcinfo
->args
[i
].value
);
442 if (PyList_SetItem(args
, i
, arg
) == -1)
443 PLy_elog(ERROR
, "PyList_SetItem() failed, while setting up arguments");
445 if (proc
->argnames
&& proc
->argnames
[i
] &&
446 PyDict_SetItemString(proc
->globals
, proc
->argnames
[i
], arg
) == -1)
447 PLy_elog(ERROR
, "PyDict_SetItemString() failed, while setting up arguments");
451 /* Set up output conversion for functions returning RECORD */
452 if (proc
->result
.typoid
== RECORDOID
)
456 if (get_call_result_type(fcinfo
, NULL
, &desc
) != TYPEFUNC_COMPOSITE
)
458 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
459 errmsg("function returning record called in context "
460 "that cannot accept type record")));
462 /* cache the output conversion functions */
463 PLy_output_setup_record(&proc
->result
, desc
, proc
);
479 * Construct a PLySavedArgs struct representing the current values of the
480 * procedure's arguments in its globals dict. This can be used to restore
481 * those values when exiting a recursive call level or returning control to a
482 * set-returning function.
484 * This would not be necessary except for an ancient decision to make args
485 * available via the proc's globals :-( ... but we're stuck with that now.
487 static PLySavedArgs
*
488 PLy_function_save_args(PLyProcedure
*proc
)
490 PLySavedArgs
*result
;
492 /* saved args are always allocated in procedure's context */
493 result
= (PLySavedArgs
*)
494 MemoryContextAllocZero(proc
->mcxt
,
495 offsetof(PLySavedArgs
, namedargs
) +
496 proc
->nargs
* sizeof(PyObject
*));
497 result
->nargs
= proc
->nargs
;
499 /* Fetch the "args" list */
500 result
->args
= PyDict_GetItemString(proc
->globals
, "args");
501 Py_XINCREF(result
->args
);
503 /* Fetch all the named arguments */
508 for (i
= 0; i
< result
->nargs
; i
++)
510 if (proc
->argnames
[i
])
512 result
->namedargs
[i
] = PyDict_GetItemString(proc
->globals
,
514 Py_XINCREF(result
->namedargs
[i
]);
523 * Restore procedure's arguments from a PLySavedArgs struct,
524 * then free the struct.
527 PLy_function_restore_args(PLyProcedure
*proc
, PLySavedArgs
*savedargs
)
529 /* Restore named arguments into their slots in the globals dict */
534 for (i
= 0; i
< savedargs
->nargs
; i
++)
536 if (proc
->argnames
[i
] && savedargs
->namedargs
[i
])
538 PyDict_SetItemString(proc
->globals
, proc
->argnames
[i
],
539 savedargs
->namedargs
[i
]);
540 Py_DECREF(savedargs
->namedargs
[i
]);
545 /* Restore the "args" object, too */
548 PyDict_SetItemString(proc
->globals
, "args", savedargs
->args
);
549 Py_DECREF(savedargs
->args
);
552 /* And free the PLySavedArgs struct */
557 * Free a PLySavedArgs struct without restoring the values.
560 PLy_function_drop_args(PLySavedArgs
*savedargs
)
564 /* Drop references for named args */
565 for (i
= 0; i
< savedargs
->nargs
; i
++)
567 Py_XDECREF(savedargs
->namedargs
[i
]);
570 /* Drop ref to the "args" object, too */
571 Py_XDECREF(savedargs
->args
);
573 /* And free the PLySavedArgs struct */
578 * Save away any existing arguments for the given procedure, so that we can
579 * install new values for a recursive call. This should be invoked before
580 * doing PLy_function_build_args().
582 * NB: caller must ensure that PLy_global_args_pop gets invoked once, and
583 * only once, per successful completion of PLy_global_args_push. Otherwise
584 * we'll end up out-of-sync between the actual call stack and the contents
588 PLy_global_args_push(PLyProcedure
*proc
)
590 /* We only need to push if we are already inside some active call */
591 if (proc
->calldepth
> 0)
595 /* Build a struct containing current argument values */
596 node
= PLy_function_save_args(proc
);
599 * Push the saved argument values into the procedure's stack. Once we
600 * modify either proc->argstack or proc->calldepth, we had better
601 * return without the possibility of error.
603 node
->next
= proc
->argstack
;
604 proc
->argstack
= node
;
610 * Pop old arguments when exiting a recursive call.
612 * Note: the idea here is to adjust the proc's callstack state before doing
613 * anything that could possibly fail. In event of any error, we want the
614 * callstack to look like we've done the pop. Leaking a bit of memory is
618 PLy_global_args_pop(PLyProcedure
*proc
)
620 Assert(proc
->calldepth
> 0);
621 /* We only need to pop if we were already inside some active call */
622 if (proc
->calldepth
> 1)
624 PLySavedArgs
*ptr
= proc
->argstack
;
626 /* Pop the callstack */
628 proc
->argstack
= ptr
->next
;
631 /* Restore argument values, then free ptr */
632 PLy_function_restore_args(proc
, ptr
);
636 /* Exiting call depth 1 */
637 Assert(proc
->argstack
== NULL
);
641 * We used to delete the named arguments (but not "args") from the
642 * proc's globals dict when exiting the outermost call level for a
643 * function. This seems rather pointless though: nothing can see the
644 * dict until the function is called again, at which time we'll
645 * overwrite those dict entries. So don't bother with that.
651 * Memory context deletion callback for cleaning up a PLySRFState.
652 * We need this in case execution of the SRF is terminated early,
653 * due to error or the caller simply not running it to completion.
656 plpython_srf_cleanup_callback(void *arg
)
658 PLySRFState
*srfstate
= (PLySRFState
*) arg
;
660 /* Release refcount on the iter, if we still have one */
661 Py_XDECREF(srfstate
->iter
);
662 srfstate
->iter
= NULL
;
663 /* And drop any saved args; we won't need them */
664 if (srfstate
->savedargs
)
665 PLy_function_drop_args(srfstate
->savedargs
);
666 srfstate
->savedargs
= NULL
;
670 plpython_return_error_callback(void *arg
)
672 PLyExecutionContext
*exec_ctx
= PLy_current_execution_context();
674 if (exec_ctx
->curr_proc
&&
675 !exec_ctx
->curr_proc
->is_procedure
)
676 errcontext("while creating return value");
680 PLy_trigger_build_args(FunctionCallInfo fcinfo
, PLyProcedure
*proc
, HeapTuple
*rv
)
682 TriggerData
*tdata
= (TriggerData
*) fcinfo
->context
;
683 TupleDesc rel_descr
= RelationGetDescr(tdata
->tg_relation
);
694 PyObject
*volatile pltdata
= NULL
;
699 pltdata
= PyDict_New();
703 pltname
= PyString_FromString(tdata
->tg_trigger
->tgname
);
704 PyDict_SetItemString(pltdata
, "name", pltname
);
707 stroid
= DatumGetCString(DirectFunctionCall1(oidout
,
708 ObjectIdGetDatum(tdata
->tg_relation
->rd_id
)));
709 pltrelid
= PyString_FromString(stroid
);
710 PyDict_SetItemString(pltdata
, "relid", pltrelid
);
714 stroid
= SPI_getrelname(tdata
->tg_relation
);
715 plttablename
= PyString_FromString(stroid
);
716 PyDict_SetItemString(pltdata
, "table_name", plttablename
);
717 Py_DECREF(plttablename
);
720 stroid
= SPI_getnspname(tdata
->tg_relation
);
721 plttableschema
= PyString_FromString(stroid
);
722 PyDict_SetItemString(pltdata
, "table_schema", plttableschema
);
723 Py_DECREF(plttableschema
);
726 if (TRIGGER_FIRED_BEFORE(tdata
->tg_event
))
727 pltwhen
= PyString_FromString("BEFORE");
728 else if (TRIGGER_FIRED_AFTER(tdata
->tg_event
))
729 pltwhen
= PyString_FromString("AFTER");
730 else if (TRIGGER_FIRED_INSTEAD(tdata
->tg_event
))
731 pltwhen
= PyString_FromString("INSTEAD OF");
734 elog(ERROR
, "unrecognized WHEN tg_event: %u", tdata
->tg_event
);
735 pltwhen
= NULL
; /* keep compiler quiet */
737 PyDict_SetItemString(pltdata
, "when", pltwhen
);
740 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
742 pltlevel
= PyString_FromString("ROW");
743 PyDict_SetItemString(pltdata
, "level", pltlevel
);
747 * Note: In BEFORE trigger, stored generated columns are not
748 * computed yet, so don't make them accessible in NEW row.
751 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
753 pltevent
= PyString_FromString("INSERT");
755 PyDict_SetItemString(pltdata
, "old", Py_None
);
756 pytnew
= PLy_input_from_tuple(&proc
->result_in
,
759 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
));
760 PyDict_SetItemString(pltdata
, "new", pytnew
);
762 *rv
= tdata
->tg_trigtuple
;
764 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
766 pltevent
= PyString_FromString("DELETE");
768 PyDict_SetItemString(pltdata
, "new", Py_None
);
769 pytold
= PLy_input_from_tuple(&proc
->result_in
,
773 PyDict_SetItemString(pltdata
, "old", pytold
);
775 *rv
= tdata
->tg_trigtuple
;
777 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
779 pltevent
= PyString_FromString("UPDATE");
781 pytnew
= PLy_input_from_tuple(&proc
->result_in
,
784 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
));
785 PyDict_SetItemString(pltdata
, "new", pytnew
);
787 pytold
= PLy_input_from_tuple(&proc
->result_in
,
791 PyDict_SetItemString(pltdata
, "old", pytold
);
793 *rv
= tdata
->tg_newtuple
;
797 elog(ERROR
, "unrecognized OP tg_event: %u", tdata
->tg_event
);
798 pltevent
= NULL
; /* keep compiler quiet */
801 PyDict_SetItemString(pltdata
, "event", pltevent
);
804 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata
->tg_event
))
806 pltlevel
= PyString_FromString("STATEMENT");
807 PyDict_SetItemString(pltdata
, "level", pltlevel
);
810 PyDict_SetItemString(pltdata
, "old", Py_None
);
811 PyDict_SetItemString(pltdata
, "new", Py_None
);
814 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
815 pltevent
= PyString_FromString("INSERT");
816 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
817 pltevent
= PyString_FromString("DELETE");
818 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
819 pltevent
= PyString_FromString("UPDATE");
820 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata
->tg_event
))
821 pltevent
= PyString_FromString("TRUNCATE");
824 elog(ERROR
, "unrecognized OP tg_event: %u", tdata
->tg_event
);
825 pltevent
= NULL
; /* keep compiler quiet */
828 PyDict_SetItemString(pltdata
, "event", pltevent
);
832 elog(ERROR
, "unrecognized LEVEL tg_event: %u", tdata
->tg_event
);
834 if (tdata
->tg_trigger
->tgnargs
)
842 pltargs
= PyList_New(tdata
->tg_trigger
->tgnargs
);
848 for (i
= 0; i
< tdata
->tg_trigger
->tgnargs
; i
++)
850 pltarg
= PyString_FromString(tdata
->tg_trigger
->tgargs
[i
]);
853 * stolen, don't Py_DECREF
855 PyList_SetItem(pltargs
, i
, pltarg
);
863 PyDict_SetItemString(pltdata
, "args", pltargs
);
877 * Apply changes requested by a MODIFY return from a trigger function.
880 PLy_modify_tuple(PLyProcedure
*proc
, PyObject
*pltd
, TriggerData
*tdata
,
884 PyObject
*volatile plntup
;
885 PyObject
*volatile plkeys
;
886 PyObject
*volatile plval
;
887 Datum
*volatile modvalues
;
888 bool *volatile modnulls
;
889 bool *volatile modrepls
;
890 ErrorContextCallback plerrcontext
;
892 plerrcontext
.callback
= plpython_trigger_error_callback
;
893 plerrcontext
.previous
= error_context_stack
;
894 error_context_stack
= &plerrcontext
;
896 plntup
= plkeys
= plval
= NULL
;
907 if ((plntup
= PyDict_GetItemString(pltd
, "new")) == NULL
)
909 (errcode(ERRCODE_UNDEFINED_OBJECT
),
910 errmsg("TD[\"new\"] deleted, cannot modify row")));
912 if (!PyDict_Check(plntup
))
914 (errcode(ERRCODE_DATATYPE_MISMATCH
),
915 errmsg("TD[\"new\"] is not a dictionary")));
917 plkeys
= PyDict_Keys(plntup
);
918 nkeys
= PyList_Size(plkeys
);
920 tupdesc
= RelationGetDescr(tdata
->tg_relation
);
922 modvalues
= (Datum
*) palloc0(tupdesc
->natts
* sizeof(Datum
));
923 modnulls
= (bool *) palloc0(tupdesc
->natts
* sizeof(bool));
924 modrepls
= (bool *) palloc0(tupdesc
->natts
* sizeof(bool));
926 for (i
= 0; i
< nkeys
; i
++)
933 platt
= PyList_GetItem(plkeys
, i
);
934 if (PyString_Check(platt
))
935 plattstr
= PyString_AsString(platt
);
936 else if (PyUnicode_Check(platt
))
937 plattstr
= PLyUnicode_AsString(platt
);
941 (errcode(ERRCODE_DATATYPE_MISMATCH
),
942 errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i
)));
943 plattstr
= NULL
; /* keep compiler quiet */
945 attn
= SPI_fnumber(tupdesc
, plattstr
);
946 if (attn
== SPI_ERROR_NOATTRIBUTE
)
948 (errcode(ERRCODE_UNDEFINED_COLUMN
),
949 errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
953 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
954 errmsg("cannot set system attribute \"%s\"",
956 if (TupleDescAttr(tupdesc
, attn
- 1)->attgenerated
)
958 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED
),
959 errmsg("cannot set generated column \"%s\"",
962 plval
= PyDict_GetItem(plntup
, platt
);
964 elog(FATAL
, "Python interpreter is probably corrupted");
968 /* We assume proc->result is set up to convert tuples properly */
969 att
= &proc
->result
.u
.tuple
.atts
[attn
- 1];
971 modvalues
[attn
- 1] = PLy_output_convert(att
,
973 &modnulls
[attn
- 1]);
974 modrepls
[attn
- 1] = true;
980 rtup
= heap_modify_tuple(otup
, tupdesc
, modvalues
, modnulls
, modrepls
);
1006 error_context_stack
= plerrcontext
.previous
;
1012 plpython_trigger_error_callback(void *arg
)
1014 PLyExecutionContext
*exec_ctx
= PLy_current_execution_context();
1016 if (exec_ctx
->curr_proc
)
1017 errcontext("while modifying trigger row");
1020 /* execute Python code, propagate Python errors to the backend */
1022 PLy_procedure_call(PLyProcedure
*proc
, const char *kargs
, PyObject
*vargs
)
1024 PyObject
*rv
= NULL
;
1025 int volatile save_subxact_level
= list_length(explicit_subtransactions
);
1027 PyDict_SetItemString(proc
->globals
, kargs
, vargs
);
1031 #if PY_VERSION_HEX >= 0x03020000
1032 rv
= PyEval_EvalCode(proc
->code
,
1033 proc
->globals
, proc
->globals
);
1035 rv
= PyEval_EvalCode((PyCodeObject
*) proc
->code
,
1036 proc
->globals
, proc
->globals
);
1040 * Since plpy will only let you close subtransactions that you
1041 * started, you cannot *unnest* subtransactions, only *nest* them
1044 Assert(list_length(explicit_subtransactions
) >= save_subxact_level
);
1048 PLy_abort_open_subtransactions(save_subxact_level
);
1052 /* If the Python code returned an error, propagate it */
1054 PLy_elog(ERROR
, NULL
);
1060 * Abort lingering subtransactions that have been explicitly started
1061 * by plpy.subtransaction().start() and not properly closed.
1064 PLy_abort_open_subtransactions(int save_subxact_level
)
1066 Assert(save_subxact_level
>= 0);
1068 while (list_length(explicit_subtransactions
) > save_subxact_level
)
1070 PLySubtransactionData
*subtransactiondata
;
1072 Assert(explicit_subtransactions
!= NIL
);
1075 (errmsg("forcibly aborting a subtransaction that has not been exited")));
1077 RollbackAndReleaseCurrentSubTransaction();
1079 subtransactiondata
= (PLySubtransactionData
*) linitial(explicit_subtransactions
);
1080 explicit_subtransactions
= list_delete_first(explicit_subtransactions
);
1082 MemoryContextSwitchTo(subtransactiondata
->oldcontext
);
1083 CurrentResourceOwner
= subtransactiondata
->oldowner
;
1084 pfree(subtransactiondata
);