LCOV - code coverage report
Current view: top level - src/pl/plpython - plpy_exec.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 387 413 93.7 %
Date: 2019-11-13 22:07:24 Functions: 15 15 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13