TLA Line data Source code
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 */
32 : } PLySRFState;
33 :
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);
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
55 CBC 640 : PLy_exec_function(FunctionCallInfo fcinfo, PLyProcedure *proc)
56 : {
57 640 : bool is_setof = proc->is_setof;
58 : Datum rv;
59 640 : PyObject *volatile plargs = NULL;
60 640 : PyObject *volatile plrv = NULL;
61 640 : FuncCallContext *volatile funcctx = NULL;
62 640 : 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 : */
70 640 : PLy_global_args_push(proc);
71 :
72 640 : PG_TRY();
73 : {
74 640 : if (is_setof)
75 : {
76 : /* First Call setup */
77 191 : if (SRF_IS_FIRSTCALL())
78 : {
79 48 : funcctx = SRF_FIRSTCALL_INIT();
80 48 : srfstate = (PLySRFState *)
81 48 : MemoryContextAllocZero(funcctx->multi_call_memory_ctx,
82 : sizeof(PLySRFState));
83 : /* Immediately register cleanup callback */
84 48 : srfstate->callback.func = plpython_srf_cleanup_callback;
85 48 : srfstate->callback.arg = (void *) srfstate;
86 48 : MemoryContextRegisterResetCallback(funcctx->multi_call_memory_ctx,
87 48 : &srfstate->callback);
88 48 : funcctx->user_fctx = (void *) srfstate;
89 : }
90 : /* Every call setup */
91 191 : funcctx = SRF_PERCALL_SETUP();
92 191 : Assert(funcctx != NULL);
93 191 : srfstate = (PLySRFState *) funcctx->user_fctx;
94 191 : Assert(srfstate != NULL);
95 : }
96 :
97 640 : 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 497 : plargs = PLy_function_build_args(fcinfo, proc);
104 497 : plrv = PLy_procedure_call(proc, "args", plargs);
105 443 : 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 143 : if (srfstate->savedargs)
118 143 : PLy_function_restore_args(proc, srfstate->savedargs);
119 143 : 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 586 : if (is_setof)
128 : {
129 190 : if (srfstate->iter == NULL)
130 : {
131 : /* first time -- do checks and setup */
132 47 : ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
133 :
134 47 : if (!rsi || !IsA(rsi, ReturnSetInfo) ||
135 47 : (rsi->allowedModes & SFRM_ValuePerCall) == 0)
136 : {
137 UBC 0 : 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 : }
142 CBC 47 : rsi->returnMode = SFRM_ValuePerCall;
143 :
144 : /* Make iterator out of returned object */
145 47 : srfstate->iter = PyObject_GetIter(plrv);
146 :
147 47 : Py_DECREF(plrv);
148 47 : plrv = NULL;
149 :
150 47 : if (srfstate->iter == NULL)
151 1 : 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 189 : plrv = PyIter_Next(srfstate->iter);
159 189 : if (plrv == NULL)
160 : {
161 : /* Iterator is exhausted or error happened */
162 44 : bool has_error = (PyErr_Occurred() != NULL);
163 :
164 44 : Py_DECREF(srfstate->iter);
165 44 : srfstate->iter = NULL;
166 :
167 44 : if (has_error)
168 UBC 0 : PLy_elog(ERROR, "error fetching next item from iterator");
169 :
170 : /* Pass a null through the data-returning steps below */
171 CBC 44 : Py_INCREF(Py_None);
172 44 : 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 145 : 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 585 : if (SPI_finish() != SPI_OK_FINISH)
192 UBC 0 : elog(ERROR, "SPI_finish failed");
193 :
194 CBC 585 : plerrcontext.callback = plpython_return_error_callback;
195 585 : plerrcontext.previous = error_context_stack;
196 585 : 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 585 : if (proc->result.typoid == VOIDOID)
205 : {
206 29 : if (plrv != Py_None)
207 : {
208 2 : if (proc->is_procedure)
209 1 : ereport(ERROR,
210 : (errcode(ERRCODE_DATATYPE_MISMATCH),
211 : errmsg("PL/Python procedure did not return None")));
212 : else
213 1 : ereport(ERROR,
214 : (errcode(ERRCODE_DATATYPE_MISMATCH),
215 : errmsg("PL/Python function with return type \"void\" did not return None")));
216 : }
217 :
218 27 : fcinfo->isnull = false;
219 27 : rv = (Datum) 0;
220 : }
221 556 : else if (plrv == Py_None &&
222 50 : 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 44 : fcinfo->isnull = true;
230 44 : rv = (Datum) 0;
231 : }
232 : else
233 : {
234 : /* Normal conversion of result */
235 512 : rv = PLy_output_convert(&proc->result, plrv,
236 : &fcinfo->isnull);
237 : }
238 : }
239 84 : PG_CATCH();
240 : {
241 : /* Pop old arguments from the stack if they were pushed above */
242 84 : PLy_global_args_pop(proc);
243 :
244 84 : Py_XDECREF(plargs);
245 84 : 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 84 : if (srfstate)
255 : {
256 4 : Py_XDECREF(srfstate->iter);
257 4 : srfstate->iter = NULL;
258 : /* And drop any saved args; we won't need them */
259 4 : if (srfstate->savedargs)
260 2 : PLy_function_drop_args(srfstate->savedargs);
261 4 : srfstate->savedargs = NULL;
262 : }
263 :
264 84 : PG_RE_THROW();
265 : }
266 556 : PG_END_TRY();
267 :
268 556 : error_context_stack = plerrcontext.previous;
269 :
270 : /* Pop old arguments from the stack if they were pushed above */
271 556 : PLy_global_args_pop(proc);
272 :
273 556 : Py_XDECREF(plargs);
274 556 : Py_DECREF(plrv);
275 :
276 556 : if (srfstate)
277 : {
278 : /* We're in a SRF, exit appropriately */
279 187 : if (srfstate->iter == NULL)
280 : {
281 : /* Iterator exhausted, so we're done */
282 44 : SRF_RETURN_DONE(funcctx);
283 : }
284 143 : else if (fcinfo->isnull)
285 6 : SRF_RETURN_NEXT_NULL(funcctx);
286 : else
287 137 : SRF_RETURN_NEXT(funcctx, rv);
288 : }
289 :
290 : /* Plain function, just return the Datum value (possibly null) */
291 369 : 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
305 46 : PLy_exec_trigger(FunctionCallInfo fcinfo, PLyProcedure *proc)
306 : {
307 46 : HeapTuple rv = NULL;
308 46 : PyObject *volatile plargs = NULL;
309 46 : PyObject *volatile plrv = NULL;
310 : TriggerData *tdata;
311 : TupleDesc rel_descr;
312 :
313 46 : Assert(CALLED_AS_TRIGGER(fcinfo));
314 46 : 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 46 : rel_descr = RelationGetDescr(tdata->tg_relation);
325 46 : if (proc->result.typoid != rel_descr->tdtypeid)
326 25 : PLy_output_setup_func(&proc->result, proc->mcxt,
327 : rel_descr->tdtypeid,
328 : rel_descr->tdtypmod,
329 : proc);
330 46 : if (proc->result_in.typoid != rel_descr->tdtypeid)
331 25 : PLy_input_setup_func(&proc->result_in, proc->mcxt,
332 : rel_descr->tdtypeid,
333 : rel_descr->tdtypmod,
334 : proc);
335 46 : PLy_output_setup_tuple(&proc->result, rel_descr, proc);
336 46 : PLy_input_setup_tuple(&proc->result_in, rel_descr, proc);
337 :
338 46 : PG_TRY();
339 : {
340 : int rc PG_USED_FOR_ASSERTS_ONLY;
341 :
342 46 : rc = SPI_register_trigger_data(tdata);
343 46 : Assert(rc >= 0);
344 :
345 46 : plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
346 46 : plrv = PLy_procedure_call(proc, "TD", plargs);
347 :
348 46 : Assert(plrv != NULL);
349 :
350 : /*
351 : * Disconnect from SPI manager
352 : */
353 46 : if (SPI_finish() != SPI_OK_FINISH)
354 UBC 0 : elog(ERROR, "SPI_finish failed");
355 :
356 : /*
357 : * return of None means we're happy with the tuple
358 : */
359 CBC 46 : if (plrv != Py_None)
360 : {
361 : char *srv;
362 :
363 25 : if (PyUnicode_Check(plrv))
364 24 : srv = PLyUnicode_AsString(plrv);
365 : else
366 : {
367 1 : 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 24 : if (pg_strcasecmp(srv, "SKIP") == 0)
375 1 : rv = NULL;
376 23 : else if (pg_strcasecmp(srv, "MODIFY") == 0)
377 : {
378 21 : if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
379 GIC 9 : TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
380 CBC 20 : rv = PLy_modify_tuple(proc, plargs, tdata, rv);
381 : else
382 GIC 1 : ereport(WARNING,
383 ECB : (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
384 : }
385 GIC 2 : else if (pg_strcasecmp(srv, "OK") != 0)
386 : {
387 : /*
388 : * accept "OK" as an alternative to None; otherwise, raise an
389 ECB : * error
390 : */
391 GIC 2 : 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 ECB : }
397 : }
398 CBC 9 : PG_FINALLY();
399 ECB : {
400 GIC 46 : Py_XDECREF(plargs);
401 CBC 46 : Py_XDECREF(plrv);
402 : }
403 46 : PG_END_TRY();
404 :
405 GIC 37 : return rv;
406 : }
407 :
408 : /* helper functions for Python code execution */
409 ECB :
410 : static PyObject *
411 CBC 497 : PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
412 ECB : {
413 GIC 497 : PyObject *volatile arg = NULL;
414 497 : PyObject *volatile args = NULL;
415 ECB : int i;
416 :
417 CBC 497 : PG_TRY();
418 ECB : {
419 GBC 497 : args = PyList_New(proc->nargs);
420 GIC 497 : if (!args)
421 LBC 0 : return NULL;
422 :
423 CBC 1202 : for (i = 0; i < proc->nargs; i++)
424 : {
425 705 : PLyDatumToOb *arginfo = &proc->args[i];
426 ECB :
427 GIC 705 : if (fcinfo->args[i].isnull)
428 CBC 120 : arg = NULL;
429 : else
430 585 : arg = PLy_input_convert(arginfo, fcinfo->args[i].value);
431 :
432 705 : if (arg == NULL)
433 ECB : {
434 GIC 120 : Py_INCREF(Py_None);
435 120 : arg = Py_None;
436 ECB : }
437 EUB :
438 GIC 705 : if (PyList_SetItem(args, i, arg) == -1)
439 LBC 0 : PLy_elog(ERROR, "PyList_SetItem() failed, while setting up arguments");
440 ECB :
441 GBC 705 : if (proc->argnames && proc->argnames[i] &&
442 CBC 702 : PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1)
443 UIC 0 : PLy_elog(ERROR, "PyDict_SetItemString() failed, while setting up arguments");
444 GIC 705 : arg = NULL;
445 : }
446 ECB :
447 : /* Set up output conversion for functions returning RECORD */
448 GIC 497 : if (proc->result.typoid == RECORDOID)
449 : {
450 ECB : TupleDesc desc;
451 EUB :
452 GIC 74 : if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
453 UIC 0 : ereport(ERROR,
454 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
455 : errmsg("function returning record called in context "
456 : "that cannot accept type record")));
457 ECB :
458 : /* cache the output conversion functions */
459 GIC 74 : PLy_output_setup_record(&proc->result, desc, proc);
460 EUB : }
461 : }
462 UBC 0 : PG_CATCH();
463 EUB : {
464 UIC 0 : Py_XDECREF(arg);
465 UBC 0 : Py_XDECREF(args);
466 :
467 LBC 0 : PG_RE_THROW();
468 : }
469 CBC 497 : PG_END_TRY();
470 :
471 GIC 497 : 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 ECB : */
483 : static PLySavedArgs *
484 GIC 154 : PLy_function_save_args(PLyProcedure *proc)
485 : {
486 : PLySavedArgs *result;
487 :
488 ECB : /* saved args are always allocated in procedure's context */
489 : result = (PLySavedArgs *)
490 CBC 154 : MemoryContextAllocZero(proc->mcxt,
491 154 : offsetof(PLySavedArgs, namedargs) +
492 GIC 154 : proc->nargs * sizeof(PyObject *));
493 154 : result->nargs = proc->nargs;
494 ECB :
495 : /* Fetch the "args" list */
496 GIC 154 : result->args = PyDict_GetItemString(proc->globals, "args");
497 154 : Py_XINCREF(result->args);
498 ECB :
499 : /* Fetch all the named arguments */
500 GIC 154 : if (proc->argnames)
501 : {
502 ECB : int i;
503 :
504 CBC 299 : for (i = 0; i < result->nargs; i++)
505 : {
506 207 : if (proc->argnames[i])
507 ECB : {
508 CBC 414 : result->namedargs[i] = PyDict_GetItemString(proc->globals,
509 GIC 207 : proc->argnames[i]);
510 207 : Py_XINCREF(result->namedargs[i]);
511 : }
512 : }
513 ECB : }
514 :
515 GIC 154 : return result;
516 : }
517 :
518 : /*
519 : * Restore procedure's arguments from a PLySavedArgs struct,
520 : * then free the struct.
521 ECB : */
522 : static void
523 GIC 152 : PLy_function_restore_args(PLyProcedure *proc, PLySavedArgs *savedargs)
524 ECB : {
525 : /* Restore named arguments into their slots in the globals dict */
526 GIC 152 : if (proc->argnames)
527 : {
528 ECB : int i;
529 :
530 CBC 299 : for (i = 0; i < savedargs->nargs; i++)
531 : {
532 207 : if (proc->argnames[i] && savedargs->namedargs[i])
533 : {
534 207 : PyDict_SetItemString(proc->globals, proc->argnames[i],
535 : savedargs->namedargs[i]);
536 GIC 207 : Py_DECREF(savedargs->namedargs[i]);
537 : }
538 : }
539 : }
540 ECB :
541 : /* Restore the "args" object, too */
542 CBC 152 : if (savedargs->args)
543 ECB : {
544 GIC 152 : PyDict_SetItemString(proc->globals, "args", savedargs->args);
545 152 : Py_DECREF(savedargs->args);
546 : }
547 ECB :
548 : /* And free the PLySavedArgs struct */
549 GIC 152 : pfree(savedargs);
550 152 : }
551 :
552 : /*
553 : * Free a PLySavedArgs struct without restoring the values.
554 ECB : */
555 : static void
556 GIC 2 : PLy_function_drop_args(PLySavedArgs *savedargs)
557 : {
558 : int i;
559 ECB :
560 : /* Drop references for named args */
561 GBC 2 : for (i = 0; i < savedargs->nargs; i++)
562 : {
563 UIC 0 : Py_XDECREF(savedargs->namedargs[i]);
564 : }
565 ECB :
566 : /* Drop ref to the "args" object, too */
567 GIC 2 : Py_XDECREF(savedargs->args);
568 ECB :
569 : /* And free the PLySavedArgs struct */
570 GIC 2 : pfree(savedargs);
571 2 : }
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 ECB : */
583 : static void
584 GIC 640 : PLy_global_args_push(PLyProcedure *proc)
585 ECB : {
586 : /* We only need to push if we are already inside some active call */
587 GIC 640 : if (proc->calldepth > 0)
588 : {
589 : PLySavedArgs *node;
590 ECB :
591 : /* Build a struct containing current argument values */
592 GIC 9 : 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 ECB : * return without the possibility of error.
598 : */
599 GIC 9 : node->next = proc->argstack;
600 CBC 9 : proc->argstack = node;
601 ECB : }
602 GIC 640 : proc->calldepth++;
603 640 : }
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 ECB : */
613 : static void
614 CBC 640 : PLy_global_args_pop(PLyProcedure *proc)
615 : {
616 640 : Assert(proc->calldepth > 0);
617 : /* We only need to pop if we were already inside some active call */
618 640 : if (proc->calldepth > 1)
619 : {
620 GIC 9 : PLySavedArgs *ptr = proc->argstack;
621 ECB :
622 : /* Pop the callstack */
623 CBC 9 : Assert(ptr != NULL);
624 GIC 9 : proc->argstack = ptr->next;
625 9 : proc->calldepth--;
626 ECB :
627 : /* Restore argument values, then free ptr */
628 GIC 9 : PLy_function_restore_args(proc, ptr);
629 : }
630 : else
631 ECB : {
632 : /* Exiting call depth 1 */
633 GIC 631 : Assert(proc->argstack == NULL);
634 631 : 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 ECB : */
643 : }
644 GIC 640 : }
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 ECB : */
651 : static void
652 CBC 48 : plpython_srf_cleanup_callback(void *arg)
653 : {
654 GIC 48 : PLySRFState *srfstate = (PLySRFState *) arg;
655 ECB :
656 : /* Release refcount on the iter, if we still have one */
657 GIC 48 : Py_XDECREF(srfstate->iter);
658 CBC 48 : srfstate->iter = NULL;
659 EUB : /* And drop any saved args; we won't need them */
660 CBC 48 : if (srfstate->savedargs)
661 LBC 0 : PLy_function_drop_args(srfstate->savedargs);
662 GIC 48 : srfstate->savedargs = NULL;
663 48 : }
664 ECB :
665 : static void
666 CBC 30 : plpython_return_error_callback(void *arg)
667 : {
668 30 : PLyExecutionContext *exec_ctx = PLy_current_execution_context();
669 ECB :
670 CBC 30 : if (exec_ctx->curr_proc &&
671 30 : !exec_ctx->curr_proc->is_procedure)
672 GIC 29 : errcontext("while creating return value");
673 30 : }
674 ECB :
675 : static PyObject *
676 CBC 46 : PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
677 ECB : {
678 GIC 46 : TriggerData *tdata = (TriggerData *) fcinfo->context;
679 46 : 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 ECB : *pytnew,
689 : *pytold;
690 GIC 46 : PyObject *volatile pltdata = NULL;
691 ECB : char *stroid;
692 :
693 CBC 46 : PG_TRY();
694 ECB : {
695 GBC 46 : pltdata = PyDict_New();
696 GIC 46 : if (!pltdata)
697 LBC 0 : return NULL;
698 ECB :
699 CBC 46 : pltname = PLyUnicode_FromString(tdata->tg_trigger->tgname);
700 GIC 46 : PyDict_SetItemString(pltdata, "name", pltname);
701 CBC 46 : Py_DECREF(pltname);
702 :
703 46 : stroid = DatumGetCString(DirectFunctionCall1(oidout,
704 ECB : ObjectIdGetDatum(tdata->tg_relation->rd_id)));
705 CBC 46 : pltrelid = PLyUnicode_FromString(stroid);
706 46 : PyDict_SetItemString(pltdata, "relid", pltrelid);
707 GIC 46 : Py_DECREF(pltrelid);
708 CBC 46 : pfree(stroid);
709 ECB :
710 CBC 46 : stroid = SPI_getrelname(tdata->tg_relation);
711 46 : plttablename = PLyUnicode_FromString(stroid);
712 46 : PyDict_SetItemString(pltdata, "table_name", plttablename);
713 GIC 46 : Py_DECREF(plttablename);
714 CBC 46 : pfree(stroid);
715 ECB :
716 CBC 46 : stroid = SPI_getnspname(tdata->tg_relation);
717 46 : plttableschema = PLyUnicode_FromString(stroid);
718 46 : PyDict_SetItemString(pltdata, "table_schema", plttableschema);
719 GIC 46 : Py_DECREF(plttableschema);
720 CBC 46 : pfree(stroid);
721 ECB :
722 CBC 46 : if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
723 36 : pltwhen = PLyUnicode_FromString("BEFORE");
724 10 : else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
725 7 : pltwhen = PLyUnicode_FromString("AFTER");
726 GIC 3 : else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
727 3 : pltwhen = PLyUnicode_FromString("INSTEAD OF");
728 EUB : else
729 : {
730 UIC 0 : elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
731 ECB : pltwhen = NULL; /* keep compiler quiet */
732 : }
733 GIC 46 : PyDict_SetItemString(pltdata, "when", pltwhen);
734 CBC 46 : Py_DECREF(pltwhen);
735 :
736 46 : if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
737 ECB : {
738 CBC 41 : pltlevel = PLyUnicode_FromString("ROW");
739 GIC 41 : PyDict_SetItemString(pltdata, "level", pltlevel);
740 41 : 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 ECB : */
746 :
747 CBC 41 : if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
748 : {
749 19 : pltevent = PLyUnicode_FromString("INSERT");
750 ECB :
751 GIC 19 : PyDict_SetItemString(pltdata, "old", Py_None);
752 38 : pytnew = PLy_input_from_tuple(&proc->result_in,
753 ECB : tdata->tg_trigtuple,
754 : rel_descr,
755 CBC 19 : !TRIGGER_FIRED_BEFORE(tdata->tg_event));
756 19 : PyDict_SetItemString(pltdata, "new", pytnew);
757 GIC 19 : Py_DECREF(pytnew);
758 CBC 19 : *rv = tdata->tg_trigtuple;
759 : }
760 22 : else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
761 : {
762 6 : pltevent = PLyUnicode_FromString("DELETE");
763 ECB :
764 GIC 6 : PyDict_SetItemString(pltdata, "new", Py_None);
765 6 : pytold = PLy_input_from_tuple(&proc->result_in,
766 : tdata->tg_trigtuple,
767 ECB : rel_descr,
768 : true);
769 CBC 6 : PyDict_SetItemString(pltdata, "old", pytold);
770 GIC 6 : Py_DECREF(pytold);
771 CBC 6 : *rv = tdata->tg_trigtuple;
772 : }
773 16 : else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
774 : {
775 16 : pltevent = PLyUnicode_FromString("UPDATE");
776 :
777 GIC 32 : pytnew = PLy_input_from_tuple(&proc->result_in,
778 ECB : tdata->tg_newtuple,
779 : rel_descr,
780 CBC 16 : !TRIGGER_FIRED_BEFORE(tdata->tg_event));
781 16 : PyDict_SetItemString(pltdata, "new", pytnew);
782 GIC 16 : Py_DECREF(pytnew);
783 16 : pytold = PLy_input_from_tuple(&proc->result_in,
784 : tdata->tg_trigtuple,
785 ECB : rel_descr,
786 : true);
787 CBC 16 : PyDict_SetItemString(pltdata, "old", pytold);
788 GIC 16 : Py_DECREF(pytold);
789 16 : *rv = tdata->tg_newtuple;
790 : }
791 EUB : else
792 : {
793 UIC 0 : elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
794 : pltevent = NULL; /* keep compiler quiet */
795 ECB : }
796 :
797 GIC 41 : PyDict_SetItemString(pltdata, "event", pltevent);
798 CBC 41 : Py_DECREF(pltevent);
799 : }
800 5 : else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
801 ECB : {
802 CBC 5 : pltlevel = PLyUnicode_FromString("STATEMENT");
803 GIC 5 : PyDict_SetItemString(pltdata, "level", pltlevel);
804 CBC 5 : Py_DECREF(pltlevel);
805 ECB :
806 CBC 5 : PyDict_SetItemString(pltdata, "old", Py_None);
807 GIC 5 : PyDict_SetItemString(pltdata, "new", Py_None);
808 CBC 5 : *rv = NULL;
809 ECB :
810 CBC 5 : if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
811 1 : pltevent = PLyUnicode_FromString("INSERT");
812 4 : else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
813 1 : pltevent = PLyUnicode_FromString("DELETE");
814 3 : else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
815 2 : pltevent = PLyUnicode_FromString("UPDATE");
816 GIC 1 : else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
817 1 : pltevent = PLyUnicode_FromString("TRUNCATE");
818 EUB : else
819 : {
820 UIC 0 : elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
821 : pltevent = NULL; /* keep compiler quiet */
822 ECB : }
823 :
824 GIC 5 : PyDict_SetItemString(pltdata, "event", pltevent);
825 5 : Py_DECREF(pltevent);
826 EUB : }
827 : else
828 LBC 0 : elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
829 :
830 GIC 46 : if (tdata->tg_trigger->tgnargs)
831 : {
832 : /*
833 : * all strings...
834 : */
835 : int i;
836 ECB : PyObject *pltarg;
837 :
838 GIC 16 : pltargs = PyList_New(tdata->tg_trigger->tgnargs);
839 GBC 16 : if (!pltargs)
840 EUB : {
841 UIC 0 : Py_DECREF(pltdata);
842 LBC 0 : return NULL;
843 : }
844 CBC 45 : for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
845 : {
846 GIC 29 : pltarg = PLyUnicode_FromString(tdata->tg_trigger->tgargs[i]);
847 :
848 : /*
849 ECB : * stolen, don't Py_DECREF
850 : */
851 GIC 29 : PyList_SetItem(pltargs, i, pltarg);
852 : }
853 : }
854 ECB : else
855 : {
856 GIC 30 : Py_INCREF(Py_None);
857 CBC 30 : pltargs = Py_None;
858 ECB : }
859 GIC 46 : PyDict_SetItemString(pltdata, "args", pltargs);
860 GBC 46 : Py_DECREF(pltargs);
861 : }
862 UBC 0 : PG_CATCH();
863 EUB : {
864 UIC 0 : Py_XDECREF(pltdata);
865 LBC 0 : PG_RE_THROW();
866 : }
867 CBC 46 : PG_END_TRY();
868 :
869 GIC 46 : return pltdata;
870 : }
871 :
872 : /*
873 : * Apply changes requested by a MODIFY return from a trigger function.
874 ECB : */
875 : static HeapTuple
876 GIC 20 : 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 ECB : ErrorContextCallback plerrcontext;
887 :
888 CBC 20 : plerrcontext.callback = plpython_trigger_error_callback;
889 GIC 20 : plerrcontext.previous = error_context_stack;
890 CBC 20 : error_context_stack = &plerrcontext;
891 ECB :
892 CBC 20 : plntup = plkeys = plval = NULL;
893 20 : modvalues = NULL;
894 GIC 20 : modnulls = NULL;
895 CBC 20 : modrepls = NULL;
896 :
897 GIC 20 : PG_TRY();
898 : {
899 : TupleDesc tupdesc;
900 : int nkeys,
901 ECB : i;
902 :
903 GIC 20 : if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
904 1 : ereport(ERROR,
905 ECB : (errcode(ERRCODE_UNDEFINED_OBJECT),
906 : errmsg("TD[\"new\"] deleted, cannot modify row")));
907 CBC 19 : Py_INCREF(plntup);
908 GIC 19 : if (!PyDict_Check(plntup))
909 1 : ereport(ERROR,
910 : (errcode(ERRCODE_DATATYPE_MISMATCH),
911 ECB : errmsg("TD[\"new\"] is not a dictionary")));
912 :
913 GIC 18 : plkeys = PyDict_Keys(plntup);
914 CBC 18 : nkeys = PyList_Size(plkeys);
915 :
916 18 : tupdesc = RelationGetDescr(tdata->tg_relation);
917 ECB :
918 CBC 18 : modvalues = (Datum *) palloc0(tupdesc->natts * sizeof(Datum));
919 GIC 18 : modnulls = (bool *) palloc0(tupdesc->natts * sizeof(bool));
920 CBC 18 : modrepls = (bool *) palloc0(tupdesc->natts * sizeof(bool));
921 :
922 GIC 45 : for (i = 0; i < nkeys; i++)
923 : {
924 : PyObject *platt;
925 : char *plattstr;
926 : int attn;
927 ECB : PLyObToDatum *att;
928 :
929 CBC 31 : platt = PyList_GetItem(plkeys, i);
930 GIC 31 : if (PyUnicode_Check(platt))
931 30 : plattstr = PLyUnicode_AsString(platt);
932 ECB : else
933 : {
934 GIC 1 : ereport(ERROR,
935 : (errcode(ERRCODE_DATATYPE_MISMATCH),
936 : errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
937 ECB : plattstr = NULL; /* keep compiler quiet */
938 : }
939 CBC 30 : attn = SPI_fnumber(tupdesc, plattstr);
940 GIC 30 : if (attn == SPI_ERROR_NOATTRIBUTE)
941 2 : ereport(ERROR,
942 : (errcode(ERRCODE_UNDEFINED_COLUMN),
943 ECB : errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
944 EUB : plattstr)));
945 GIC 28 : if (attn <= 0)
946 UIC 0 : ereport(ERROR,
947 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
948 ECB : errmsg("cannot set system attribute \"%s\"",
949 : plattstr)));
950 GIC 28 : if (TupleDescAttr(tupdesc, attn - 1)->attgenerated)
951 1 : ereport(ERROR,
952 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
953 : errmsg("cannot set generated column \"%s\"",
954 ECB : plattstr)));
955 :
956 GBC 27 : plval = PyDict_GetItem(plntup, platt);
957 GIC 27 : if (plval == NULL)
958 LBC 0 : elog(FATAL, "Python interpreter is probably corrupted");
959 :
960 GIC 27 : Py_INCREF(plval);
961 ECB :
962 : /* We assume proc->result is set up to convert tuples properly */
963 CBC 27 : att = &proc->result.u.tuple.atts[attn - 1];
964 :
965 54 : modvalues[attn - 1] = PLy_output_convert(att,
966 ECB : plval,
967 GIC 27 : &modnulls[attn - 1]);
968 CBC 27 : modrepls[attn - 1] = true;
969 ECB :
970 GIC 27 : Py_DECREF(plval);
971 27 : plval = NULL;
972 ECB : }
973 :
974 CBC 14 : rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
975 : }
976 6 : PG_CATCH();
977 ECB : {
978 CBC 6 : Py_XDECREF(plntup);
979 GIC 6 : Py_XDECREF(plkeys);
980 CBC 6 : Py_XDECREF(plval);
981 ECB :
982 CBC 6 : if (modvalues)
983 4 : pfree(modvalues);
984 6 : if (modnulls)
985 4 : pfree(modnulls);
986 GIC 6 : if (modrepls)
987 CBC 4 : pfree(modrepls);
988 :
989 6 : PG_RE_THROW();
990 : }
991 14 : PG_END_TRY();
992 ECB :
993 GIC 14 : Py_DECREF(plntup);
994 CBC 14 : Py_DECREF(plkeys);
995 ECB :
996 CBC 14 : pfree(modvalues);
997 GIC 14 : pfree(modnulls);
998 CBC 14 : pfree(modrepls);
999 :
1000 14 : error_context_stack = plerrcontext.previous;
1001 :
1002 GIC 14 : return rtup;
1003 : }
1004 ECB :
1005 : static void
1006 CBC 6 : plpython_trigger_error_callback(void *arg)
1007 : {
1008 6 : PLyExecutionContext *exec_ctx = PLy_current_execution_context();
1009 ECB :
1010 CBC 6 : if (exec_ctx->curr_proc)
1011 GIC 6 : errcontext("while modifying trigger row");
1012 6 : }
1013 :
1014 ECB : /* execute Python code, propagate Python errors to the backend */
1015 : static PyObject *
1016 CBC 543 : PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
1017 ECB : {
1018 GIC 543 : PyObject *rv = NULL;
1019 CBC 543 : int volatile save_subxact_level = list_length(explicit_subtransactions);
1020 :
1021 543 : PyDict_SetItemString(proc->globals, kargs, vargs);
1022 :
1023 GIC 543 : PG_TRY();
1024 ECB : {
1025 : #if PY_VERSION_HEX >= 0x03020000
1026 GIC 543 : 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 ECB : * without closing.
1037 : */
1038 GBC 543 : Assert(list_length(explicit_subtransactions) >= save_subxact_level);
1039 : }
1040 LBC 0 : PG_FINALLY();
1041 : {
1042 CBC 543 : PLy_abort_open_subtransactions(save_subxact_level);
1043 : }
1044 GIC 543 : PG_END_TRY();
1045 ECB :
1046 : /* If the Python code returned an error, propagate it */
1047 GIC 543 : if (rv == NULL)
1048 CBC 54 : PLy_elog(ERROR, NULL);
1049 :
1050 GIC 489 : return rv;
1051 : }
1052 :
1053 : /*
1054 : * Abort lingering subtransactions that have been explicitly started
1055 : * by plpy.subtransaction().start() and not properly closed.
1056 ECB : */
1057 : static void
1058 CBC 543 : PLy_abort_open_subtransactions(int save_subxact_level)
1059 : {
1060 543 : Assert(save_subxact_level >= 0);
1061 :
1062 GIC 549 : while (list_length(explicit_subtransactions) > save_subxact_level)
1063 : {
1064 ECB : PLySubtransactionData *subtransactiondata;
1065 :
1066 CBC 6 : Assert(explicit_subtransactions != NIL);
1067 :
1068 GIC 6 : ereport(WARNING,
1069 ECB : (errmsg("forcibly aborting a subtransaction that has not been exited")));
1070 :
1071 CBC 6 : RollbackAndReleaseCurrentSubTransaction();
1072 ECB :
1073 GIC 6 : subtransactiondata = (PLySubtransactionData *) linitial(explicit_subtransactions);
1074 CBC 6 : explicit_subtransactions = list_delete_first(explicit_subtransactions);
1075 ECB :
1076 CBC 6 : MemoryContextSwitchTo(subtransactiondata->oldcontext);
1077 GIC 6 : CurrentResourceOwner = subtransactiondata->oldowner;
1078 CBC 6 : pfree(subtransactiondata);
1079 : }
1080 GIC 543 : }
|