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

Generated by: LCOV version 1.13