LCOV - code coverage report
Current view: top level - src/pl/plpython - plpy_spi.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 82.3 % 254 209
Test Date: 2026-07-18 10:15:36 Functions: 100.0 % 11 11
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 64.5 % 124 80

             Branch data     Line data    Source code
       1                 :             : /*
       2                 :             :  * interface to SPI functions
       3                 :             :  *
       4                 :             :  * src/pl/plpython/plpy_spi.c
       5                 :             :  */
       6                 :             : 
       7                 :             : #include "postgres.h"
       8                 :             : 
       9                 :             : #include <limits.h>
      10                 :             : 
      11                 :             : #include "access/xact.h"
      12                 :             : #include "catalog/pg_type.h"
      13                 :             : #include "executor/spi.h"
      14                 :             : #include "mb/pg_wchar.h"
      15                 :             : #include "parser/parse_type.h"
      16                 :             : #include "plpy_elog.h"
      17                 :             : #include "plpy_main.h"
      18                 :             : #include "plpy_planobject.h"
      19                 :             : #include "plpy_plpymodule.h"
      20                 :             : #include "plpy_resultobject.h"
      21                 :             : #include "plpy_spi.h"
      22                 :             : #include "plpy_util.h"
      23                 :             : #include "utils/memutils.h"
      24                 :             : 
      25                 :             : static PyObject *PLy_spi_execute_query(char *query, long limit);
      26                 :             : static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *tuptable,
      27                 :             :                                               uint64 rows, int status);
      28                 :             : static void PLy_spi_exception_set(PyObject *excclass, ErrorData *edata);
      29                 :             : 
      30                 :             : 
      31                 :             : /*
      32                 :             :  * prepare(query="select * from foo")
      33                 :             :  * prepare(query="select * from foo where bar = $1", params=["text"])
      34                 :             :  * prepare(query="select * from foo where bar = $1", params=["text"], limit=5)
      35                 :             :  */
      36                 :             : PyObject *
      37                 :          29 : PLy_spi_prepare(PyObject *self, PyObject *args)
      38                 :             : {
      39                 :             :     PLyPlanObject *plan;
      40                 :          29 :     PyObject   *list = NULL;
      41                 :          29 :     PyObject   *volatile optr = NULL;
      42                 :             :     char       *query;
      43                 :          29 :     PLyExecutionContext *exec_ctx = PLy_current_execution_context();
      44                 :             :     volatile MemoryContext oldcontext;
      45                 :             :     volatile ResourceOwner oldowner;
      46                 :             :     volatile int nargs;
      47                 :             : 
      48         [ -  + ]:          29 :     if (!PyArg_ParseTuple(args, "s|O:prepare", &query, &list))
      49                 :           0 :         return NULL;
      50                 :             : 
      51   [ +  +  -  + ]:          29 :     if (list && (!PySequence_Check(list)))
      52                 :             :     {
      53                 :           0 :         PLy_exception_set(PyExc_TypeError,
      54                 :             :                           "second argument of plpy.prepare must be a sequence");
      55                 :           0 :         return NULL;
      56                 :             :     }
      57                 :             : 
      58         [ -  + ]:          29 :     if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
      59                 :           0 :         return NULL;
      60                 :             : 
      61                 :          29 :     plan->mcxt = AllocSetContextCreate(TopMemoryContext,
      62                 :             :                                        "PL/Python plan context",
      63                 :             :                                        ALLOCSET_DEFAULT_SIZES);
      64                 :          29 :     oldcontext = MemoryContextSwitchTo(plan->mcxt);
      65                 :             : 
      66         [ +  + ]:          29 :     nargs = list ? PySequence_Length(list) : 0;
      67                 :             : 
      68                 :          29 :     plan->nargs = nargs;
      69         [ +  + ]:          29 :     plan->types = nargs ? palloc0_array(Oid, nargs) : NULL;
      70         [ +  + ]:          29 :     plan->args = nargs ? palloc0_array(PLyObToDatum, nargs) : NULL;
      71                 :             : 
      72                 :          29 :     MemoryContextSwitchTo(oldcontext);
      73                 :             : 
      74                 :          29 :     oldcontext = CurrentMemoryContext;
      75                 :          29 :     oldowner = CurrentResourceOwner;
      76                 :             : 
      77                 :          29 :     PLy_spi_subtransaction_begin(oldcontext, oldowner);
      78                 :             : 
      79         [ +  + ]:          29 :     PG_TRY();
      80                 :             :     {
      81                 :             :         int         i;
      82                 :             : 
      83         [ +  + ]:          45 :         for (i = 0; i < nargs; i++)
      84                 :             :         {
      85                 :             :             char       *sptr;
      86                 :             :             Oid         typeId;
      87                 :             :             int32       typmod;
      88                 :             : 
      89                 :          20 :             optr = PySequence_GetItem(list, i);
      90                 :             : 
      91                 :             :             /* PySequence_GetItem() can return NULL, with an exception set */
      92         [ +  + ]:          20 :             if (optr == NULL)
      93                 :           1 :                 PLy_elog(ERROR, "could not get element %d from sequence", i);
      94                 :             : 
      95         [ +  - ]:          19 :             if (PyUnicode_Check(optr))
      96                 :          19 :                 sptr = PLyUnicode_AsString(optr);
      97                 :             :             else
      98                 :             :             {
      99         [ #  # ]:           0 :                 ereport(ERROR,
     100                 :             :                         (errmsg("plpy.prepare: type name at ordinal position %d is not a string", i)));
     101                 :             :                 sptr = NULL;    /* keep compiler quiet */
     102                 :             :             }
     103                 :             : 
     104                 :             :             /********************************************************
     105                 :             :              * Resolve argument type names and then look them up by
     106                 :             :              * oid in the system cache, and remember the required
     107                 :             :              *information for input conversion.
     108                 :             :              ********************************************************/
     109                 :             : 
     110                 :          19 :             (void) parseTypeString(sptr, &typeId, &typmod, NULL);
     111                 :             : 
     112                 :          16 :             Py_DECREF(optr);
     113                 :             : 
     114                 :             :             /*
     115                 :             :              * set optr to NULL, so we won't try to unref it again in case of
     116                 :             :              * an error
     117                 :             :              */
     118                 :          16 :             optr = NULL;
     119                 :             : 
     120                 :          16 :             plan->types[i] = typeId;
     121                 :          16 :             PLy_output_setup_func(&plan->args[i], plan->mcxt,
     122                 :             :                                   typeId, typmod,
     123                 :          16 :                                   exec_ctx->curr_proc);
     124                 :             :         }
     125                 :             : 
     126                 :          25 :         pg_verifymbstr(query, strlen(query), false);
     127                 :          25 :         plan->plan = SPI_prepare(query, plan->nargs, plan->types);
     128         [ -  + ]:          25 :         if (plan->plan == NULL)
     129         [ #  # ]:           0 :             elog(ERROR, "SPI_prepare failed: %s",
     130                 :             :                  SPI_result_code_string(SPI_result));
     131                 :             : 
     132                 :             :         /* transfer plan from procCxt to topCxt */
     133         [ -  + ]:          25 :         if (SPI_keepplan(plan->plan))
     134         [ #  # ]:           0 :             elog(ERROR, "SPI_keepplan failed");
     135                 :             : 
     136                 :          25 :         PLy_spi_subtransaction_commit(oldcontext, oldowner);
     137                 :             :     }
     138                 :           4 :     PG_CATCH();
     139                 :             :     {
     140                 :             :         Py_DECREF(plan);
     141                 :           4 :         Py_XDECREF(optr);
     142                 :             : 
     143                 :           4 :         PLy_spi_subtransaction_abort(oldcontext, oldowner);
     144                 :           4 :         return NULL;
     145                 :             :     }
     146         [ -  + ]:          25 :     PG_END_TRY();
     147                 :             : 
     148                 :             :     Assert(plan->plan != NULL);
     149                 :          25 :     return (PyObject *) plan;
     150                 :             : }
     151                 :             : 
     152                 :             : /*
     153                 :             :  * execute(query="select * from foo", limit=5)
     154                 :             :  * execute(plan=plan, values=(foo, bar), limit=5)
     155                 :             :  */
     156                 :             : PyObject *
     157                 :         168 : PLy_spi_execute(PyObject *self, PyObject *args)
     158                 :             : {
     159                 :             :     char       *query;
     160                 :             :     PyObject   *plan;
     161                 :         168 :     PyObject   *list = NULL;
     162                 :         168 :     long        limit = 0;
     163                 :             : 
     164         [ +  + ]:         168 :     if (PyArg_ParseTuple(args, "s|l", &query, &limit))
     165                 :         146 :         return PLy_spi_execute_query(query, limit);
     166                 :             : 
     167                 :          22 :     PyErr_Clear();
     168                 :             : 
     169   [ +  -  +  - ]:          44 :     if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
     170                 :          22 :         is_PLyPlanObject(plan))
     171                 :          22 :         return PLy_spi_execute_plan(plan, list, limit);
     172                 :             : 
     173                 :           0 :     PLy_exception_set(PLy_exc_error, "plpy.execute expected a query or a plan");
     174                 :           0 :     return NULL;
     175                 :             : }
     176                 :             : 
     177                 :             : PyObject *
     178                 :          23 : PLy_spi_execute_plan(PyObject *ob, PyObject *list, long limit)
     179                 :             : {
     180                 :             :     volatile int nargs;
     181                 :             :     int         rv;
     182                 :             :     PLyPlanObject *plan;
     183                 :             :     volatile MemoryContext oldcontext;
     184                 :             :     volatile ResourceOwner oldowner;
     185                 :             :     PyObject   *ret;
     186                 :             : 
     187         [ +  + ]:          23 :     if (list != NULL)
     188                 :             :     {
     189   [ +  -  -  + ]:          17 :         if (!PySequence_Check(list) || PyUnicode_Check(list))
     190                 :             :         {
     191                 :           0 :             PLy_exception_set(PyExc_TypeError, "plpy.execute takes a sequence as its second argument");
     192                 :           0 :             return NULL;
     193                 :             :         }
     194                 :          17 :         nargs = PySequence_Length(list);
     195                 :             :     }
     196                 :             :     else
     197                 :           6 :         nargs = 0;
     198                 :             : 
     199                 :          23 :     plan = (PLyPlanObject *) ob;
     200                 :             : 
     201         [ -  + ]:          23 :     if (nargs != plan->nargs)
     202                 :             :     {
     203                 :             :         char       *sv;
     204                 :           0 :         PyObject   *so = PyObject_Str(list);
     205                 :             : 
     206         [ #  # ]:           0 :         if (!so)
     207                 :           0 :             PLy_elog(ERROR, "could not execute plan");
     208                 :           0 :         sv = PLyUnicode_AsString(so);
     209                 :           0 :         PLy_exception_set_plural(PyExc_TypeError,
     210                 :             :                                  "Expected sequence of %d argument, got %d: %s",
     211                 :             :                                  "Expected sequence of %d arguments, got %d: %s",
     212                 :           0 :                                  plan->nargs,
     213                 :             :                                  plan->nargs, nargs, sv);
     214                 :             :         Py_DECREF(so);
     215                 :             : 
     216                 :           0 :         return NULL;
     217                 :             :     }
     218                 :             : 
     219                 :          23 :     oldcontext = CurrentMemoryContext;
     220                 :          23 :     oldowner = CurrentResourceOwner;
     221                 :             : 
     222                 :          23 :     PLy_spi_subtransaction_begin(oldcontext, oldowner);
     223                 :             : 
     224         [ +  + ]:          23 :     PG_TRY();
     225                 :             :     {
     226                 :          23 :         PLyExecutionContext *exec_ctx = PLy_current_execution_context();
     227                 :             :         MemoryContext tmpcontext;
     228                 :             :         Datum      *volatile values;
     229                 :             :         char       *volatile nulls;
     230                 :             :         volatile int j;
     231                 :             : 
     232                 :             :         /*
     233                 :             :          * Converted arguments and associated cruft will be in this context,
     234                 :             :          * which is local to our subtransaction.
     235                 :             :          */
     236                 :          23 :         tmpcontext = AllocSetContextCreate(CurTransactionContext,
     237                 :             :                                            "PL/Python temporary context",
     238                 :             :                                            ALLOCSET_SMALL_SIZES);
     239                 :          23 :         MemoryContextSwitchTo(tmpcontext);
     240                 :             : 
     241         [ +  + ]:          23 :         if (nargs > 0)
     242                 :             :         {
     243                 :          16 :             values = (Datum *) palloc(nargs * sizeof(Datum));
     244                 :          16 :             nulls = (char *) palloc(nargs * sizeof(char));
     245                 :             :         }
     246                 :             :         else
     247                 :             :         {
     248                 :           7 :             values = NULL;
     249                 :           7 :             nulls = NULL;
     250                 :             :         }
     251                 :             : 
     252         [ +  + ]:          37 :         for (j = 0; j < nargs; j++)
     253                 :             :         {
     254                 :          17 :             PLyObToDatum *arg = &plan->args[j];
     255                 :             :             PyObject   *elem;
     256                 :             : 
     257                 :          17 :             elem = PySequence_GetItem(list, j);
     258                 :             : 
     259                 :             :             /* PySequence_GetItem() can return NULL, with an exception set */
     260         [ +  + ]:          17 :             if (elem == NULL)
     261                 :           1 :                 PLy_elog(ERROR, "could not get element %d from sequence", j);
     262                 :             : 
     263         [ +  + ]:          16 :             PG_TRY(2);
     264                 :             :             {
     265                 :             :                 bool        isnull;
     266                 :             : 
     267                 :          16 :                 values[j] = PLy_output_convert(arg, elem, &isnull);
     268         [ -  + ]:          14 :                 nulls[j] = isnull ? 'n' : ' ';
     269                 :             :             }
     270                 :          16 :             PG_FINALLY(2);
     271                 :             :             {
     272                 :             :                 Py_DECREF(elem);
     273                 :             :             }
     274         [ +  + ]:          16 :             PG_END_TRY(2);
     275                 :             :         }
     276                 :             : 
     277                 :          20 :         MemoryContextSwitchTo(oldcontext);
     278                 :             : 
     279                 :          40 :         rv = SPI_execute_plan(plan->plan, values, nulls,
     280                 :          20 :                               exec_ctx->curr_proc->fn_readonly, limit);
     281                 :          20 :         ret = PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
     282                 :             : 
     283                 :          20 :         MemoryContextDelete(tmpcontext);
     284                 :          20 :         PLy_spi_subtransaction_commit(oldcontext, oldowner);
     285                 :             :     }
     286                 :           3 :     PG_CATCH();
     287                 :             :     {
     288                 :             :         /* Subtransaction abort will remove the tmpcontext */
     289                 :           3 :         PLy_spi_subtransaction_abort(oldcontext, oldowner);
     290                 :           3 :         return NULL;
     291                 :             :     }
     292         [ -  + ]:          20 :     PG_END_TRY();
     293                 :             : 
     294         [ +  + ]:          20 :     if (rv < 0)
     295                 :             :     {
     296                 :           1 :         PLy_exception_set(PLy_exc_spi_error,
     297                 :             :                           "SPI_execute_plan failed: %s",
     298                 :             :                           SPI_result_code_string(rv));
     299                 :           1 :         return NULL;
     300                 :             :     }
     301                 :             : 
     302                 :          19 :     return ret;
     303                 :             : }
     304                 :             : 
     305                 :             : static PyObject *
     306                 :         146 : PLy_spi_execute_query(char *query, long limit)
     307                 :             : {
     308                 :             :     int         rv;
     309                 :             :     volatile MemoryContext oldcontext;
     310                 :             :     volatile ResourceOwner oldowner;
     311                 :         146 :     PyObject   *ret = NULL;
     312                 :             : 
     313                 :         146 :     oldcontext = CurrentMemoryContext;
     314                 :         146 :     oldowner = CurrentResourceOwner;
     315                 :             : 
     316                 :         146 :     PLy_spi_subtransaction_begin(oldcontext, oldowner);
     317                 :             : 
     318         [ +  + ]:         146 :     PG_TRY();
     319                 :             :     {
     320                 :         146 :         PLyExecutionContext *exec_ctx = PLy_current_execution_context();
     321                 :             : 
     322                 :         146 :         pg_verifymbstr(query, strlen(query), false);
     323                 :         146 :         rv = SPI_execute(query, exec_ctx->curr_proc->fn_readonly, limit);
     324                 :         125 :         ret = PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
     325                 :             : 
     326                 :         125 :         PLy_spi_subtransaction_commit(oldcontext, oldowner);
     327                 :             :     }
     328                 :          21 :     PG_CATCH();
     329                 :             :     {
     330                 :          21 :         PLy_spi_subtransaction_abort(oldcontext, oldowner);
     331                 :          21 :         return NULL;
     332                 :             :     }
     333         [ -  + ]:         125 :     PG_END_TRY();
     334                 :             : 
     335         [ +  + ]:         125 :     if (rv < 0)
     336                 :             :     {
     337                 :           1 :         Py_XDECREF(ret);
     338                 :           1 :         PLy_exception_set(PLy_exc_spi_error,
     339                 :             :                           "SPI_execute failed: %s",
     340                 :             :                           SPI_result_code_string(rv));
     341                 :           1 :         return NULL;
     342                 :             :     }
     343                 :             : 
     344                 :         124 :     return ret;
     345                 :             : }
     346                 :             : 
     347                 :             : static PyObject *
     348                 :         145 : PLy_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 rows, int status)
     349                 :             : {
     350                 :             :     PLyResultObject *result;
     351                 :         145 :     PLyExecutionContext *exec_ctx = PLy_current_execution_context();
     352                 :             :     volatile MemoryContext oldcontext;
     353                 :             : 
     354                 :         145 :     result = (PLyResultObject *) PLy_result_new();
     355         [ -  + ]:         145 :     if (!result)
     356                 :             :     {
     357                 :           0 :         SPI_freetuptable(tuptable);
     358                 :           0 :         return NULL;
     359                 :             :     }
     360                 :         145 :     Py_DECREF(result->status);
     361                 :         145 :     result->status = PyLong_FromLong(status);
     362                 :             : 
     363   [ +  +  +  + ]:         145 :     if (status > 0 && tuptable == NULL)
     364                 :             :     {
     365                 :          81 :         Py_DECREF(result->nrows);
     366                 :          81 :         result->nrows = PyLong_FromUnsignedLongLong(rows);
     367                 :             :     }
     368   [ +  +  +  - ]:          64 :     else if (status > 0 && tuptable != NULL)
     369                 :             :     {
     370                 :             :         PLyDatumToOb ininfo;
     371                 :             :         MemoryContext cxt;
     372                 :             : 
     373                 :          62 :         Py_DECREF(result->nrows);
     374                 :          62 :         result->nrows = PyLong_FromUnsignedLongLong(rows);
     375                 :             : 
     376                 :          62 :         cxt = AllocSetContextCreate(CurrentMemoryContext,
     377                 :             :                                     "PL/Python temp context",
     378                 :             :                                     ALLOCSET_DEFAULT_SIZES);
     379                 :             : 
     380                 :             :         /* Initialize for converting result tuples to Python */
     381                 :          62 :         PLy_input_setup_func(&ininfo, cxt, RECORDOID, -1,
     382                 :          62 :                              exec_ctx->curr_proc);
     383                 :             : 
     384                 :          62 :         oldcontext = CurrentMemoryContext;
     385         [ +  - ]:          62 :         PG_TRY();
     386                 :             :         {
     387                 :             :             MemoryContext oldcontext2;
     388                 :             : 
     389         [ +  + ]:          62 :             if (rows)
     390                 :             :             {
     391                 :             :                 uint64      i;
     392                 :             : 
     393                 :             :                 /*
     394                 :             :                  * PyList_New() and PyList_SetItem() use Py_ssize_t for list
     395                 :             :                  * size and list indices; so we cannot support a result larger
     396                 :             :                  * than PY_SSIZE_T_MAX.
     397                 :             :                  */
     398         [ -  + ]:          60 :                 if (rows > (uint64) PY_SSIZE_T_MAX)
     399         [ #  # ]:           0 :                     ereport(ERROR,
     400                 :             :                             (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     401                 :             :                              errmsg("query result has too many rows to fit in a Python list")));
     402                 :             : 
     403                 :          60 :                 Py_DECREF(result->rows);
     404                 :          60 :                 result->rows = PyList_New(rows);
     405         [ +  - ]:          60 :                 if (result->rows)
     406                 :             :                 {
     407                 :          60 :                     PLy_input_setup_tuple(&ininfo, tuptable->tupdesc,
     408                 :          60 :                                           exec_ctx->curr_proc);
     409                 :             : 
     410         [ +  + ]:         143 :                     for (i = 0; i < rows; i++)
     411                 :             :                     {
     412                 :         166 :                         PyObject   *row = PLy_input_from_tuple(&ininfo,
     413                 :          83 :                                                                tuptable->vals[i],
     414                 :             :                                                                tuptable->tupdesc,
     415                 :             :                                                                true);
     416                 :             : 
     417                 :          83 :                         PyList_SetItem(result->rows, i, row);
     418                 :             :                     }
     419                 :             :                 }
     420                 :             :             }
     421                 :             : 
     422                 :             :             /*
     423                 :             :              * Save tuple descriptor for later use by result set metadata
     424                 :             :              * functions.  Save it in TopMemoryContext so that it survives
     425                 :             :              * outside of an SPI context.  We trust that PLy_result_dealloc()
     426                 :             :              * will clean it up when the time is right.  (Do this as late as
     427                 :             :              * possible, to minimize the number of ways the tupdesc could get
     428                 :             :              * leaked due to errors.)
     429                 :             :              */
     430                 :          62 :             oldcontext2 = MemoryContextSwitchTo(TopMemoryContext);
     431                 :          62 :             result->tupdesc = CreateTupleDescCopy(tuptable->tupdesc);
     432                 :          62 :             MemoryContextSwitchTo(oldcontext2);
     433                 :             :         }
     434                 :           0 :         PG_CATCH();
     435                 :             :         {
     436                 :           0 :             MemoryContextSwitchTo(oldcontext);
     437                 :           0 :             MemoryContextDelete(cxt);
     438                 :             :             Py_DECREF(result);
     439                 :           0 :             PG_RE_THROW();
     440                 :             :         }
     441         [ -  + ]:          62 :         PG_END_TRY();
     442                 :             : 
     443                 :          62 :         MemoryContextDelete(cxt);
     444                 :          62 :         SPI_freetuptable(tuptable);
     445                 :             : 
     446                 :             :         /* in case PyList_New() failed above */
     447         [ -  + ]:          62 :         if (!result->rows)
     448                 :             :         {
     449                 :             :             Py_DECREF(result);
     450                 :           0 :             result = NULL;
     451                 :             :         }
     452                 :             :     }
     453                 :             : 
     454                 :         145 :     return (PyObject *) result;
     455                 :             : }
     456                 :             : 
     457                 :             : PyObject *
     458                 :          26 : PLy_commit(PyObject *self, PyObject *args)
     459                 :             : {
     460                 :          26 :     MemoryContext oldcontext = CurrentMemoryContext;
     461                 :          26 :     PLyExecutionContext *exec_ctx = PLy_current_execution_context();
     462                 :             : 
     463         [ +  + ]:          26 :     PG_TRY();
     464                 :             :     {
     465                 :          26 :         SPI_commit();
     466                 :             : 
     467                 :             :         /* was cleared at transaction end, reset pointer */
     468                 :          20 :         exec_ctx->scratch_ctx = NULL;
     469                 :             :     }
     470                 :           6 :     PG_CATCH();
     471                 :             :     {
     472                 :             :         ErrorData  *edata;
     473                 :             :         PLyExceptionEntry *entry;
     474                 :             :         PyObject   *exc;
     475                 :             : 
     476                 :             :         /* Save error info */
     477                 :           6 :         MemoryContextSwitchTo(oldcontext);
     478                 :           6 :         edata = CopyErrorData();
     479                 :           6 :         FlushErrorState();
     480                 :             : 
     481                 :             :         /* was cleared at transaction end, reset pointer */
     482                 :           6 :         exec_ctx->scratch_ctx = NULL;
     483                 :             : 
     484                 :             :         /* Look up the correct exception */
     485                 :           6 :         entry = hash_search(PLy_spi_exceptions, &(edata->sqlerrcode),
     486                 :             :                             HASH_FIND, NULL);
     487                 :             : 
     488                 :             :         /*
     489                 :             :          * This could be a custom error code, if that's the case fallback to
     490                 :             :          * SPIError
     491                 :             :          */
     492         [ +  - ]:           6 :         exc = entry ? entry->exc : PLy_exc_spi_error;
     493                 :             :         /* Make Python raise the exception */
     494                 :           6 :         PLy_spi_exception_set(exc, edata);
     495                 :           6 :         FreeErrorData(edata);
     496                 :             : 
     497                 :           6 :         return NULL;
     498                 :             :     }
     499         [ -  + ]:          20 :     PG_END_TRY();
     500                 :             : 
     501                 :          20 :     Py_RETURN_NONE;
     502                 :             : }
     503                 :             : 
     504                 :             : PyObject *
     505                 :          17 : PLy_rollback(PyObject *self, PyObject *args)
     506                 :             : {
     507                 :          17 :     MemoryContext oldcontext = CurrentMemoryContext;
     508                 :          17 :     PLyExecutionContext *exec_ctx = PLy_current_execution_context();
     509                 :             : 
     510         [ +  - ]:          17 :     PG_TRY();
     511                 :             :     {
     512                 :          17 :         SPI_rollback();
     513                 :             : 
     514                 :             :         /* was cleared at transaction end, reset pointer */
     515                 :          17 :         exec_ctx->scratch_ctx = NULL;
     516                 :             :     }
     517                 :           0 :     PG_CATCH();
     518                 :             :     {
     519                 :             :         ErrorData  *edata;
     520                 :             :         PLyExceptionEntry *entry;
     521                 :             :         PyObject   *exc;
     522                 :             : 
     523                 :             :         /* Save error info */
     524                 :           0 :         MemoryContextSwitchTo(oldcontext);
     525                 :           0 :         edata = CopyErrorData();
     526                 :           0 :         FlushErrorState();
     527                 :             : 
     528                 :             :         /* was cleared at transaction end, reset pointer */
     529                 :           0 :         exec_ctx->scratch_ctx = NULL;
     530                 :             : 
     531                 :             :         /* Look up the correct exception */
     532                 :           0 :         entry = hash_search(PLy_spi_exceptions, &(edata->sqlerrcode),
     533                 :             :                             HASH_FIND, NULL);
     534                 :             : 
     535                 :             :         /*
     536                 :             :          * This could be a custom error code, if that's the case fallback to
     537                 :             :          * SPIError
     538                 :             :          */
     539         [ #  # ]:           0 :         exc = entry ? entry->exc : PLy_exc_spi_error;
     540                 :             :         /* Make Python raise the exception */
     541                 :           0 :         PLy_spi_exception_set(exc, edata);
     542                 :           0 :         FreeErrorData(edata);
     543                 :             : 
     544                 :           0 :         return NULL;
     545                 :             :     }
     546         [ -  + ]:          17 :     PG_END_TRY();
     547                 :             : 
     548                 :          17 :     Py_RETURN_NONE;
     549                 :             : }
     550                 :             : 
     551                 :             : /*
     552                 :             :  * Utilities for running SPI functions in subtransactions.
     553                 :             :  *
     554                 :             :  * Usage:
     555                 :             :  *
     556                 :             :  *  MemoryContext oldcontext = CurrentMemoryContext;
     557                 :             :  *  ResourceOwner oldowner = CurrentResourceOwner;
     558                 :             :  *
     559                 :             :  *  PLy_spi_subtransaction_begin(oldcontext, oldowner);
     560                 :             :  *  PG_TRY();
     561                 :             :  *  {
     562                 :             :  *      <call SPI functions>
     563                 :             :  *      PLy_spi_subtransaction_commit(oldcontext, oldowner);
     564                 :             :  *  }
     565                 :             :  *  PG_CATCH();
     566                 :             :  *  {
     567                 :             :  *      <do cleanup>
     568                 :             :  *      PLy_spi_subtransaction_abort(oldcontext, oldowner);
     569                 :             :  *      return NULL;
     570                 :             :  *  }
     571                 :             :  *  PG_END_TRY();
     572                 :             :  *
     573                 :             :  * These utilities take care of restoring connection to the SPI manager and
     574                 :             :  * setting a Python exception in case of an abort.
     575                 :             :  */
     576                 :             : void
     577                 :         262 : PLy_spi_subtransaction_begin(MemoryContext oldcontext, ResourceOwner oldowner)
     578                 :             : {
     579                 :         262 :     BeginInternalSubTransaction(NULL);
     580                 :             :     /* Want to run inside function's memory context */
     581                 :         262 :     MemoryContextSwitchTo(oldcontext);
     582                 :         262 : }
     583                 :             : 
     584                 :             : void
     585                 :         232 : PLy_spi_subtransaction_commit(MemoryContext oldcontext, ResourceOwner oldowner)
     586                 :             : {
     587                 :             :     /* Commit the inner transaction, return to outer xact context */
     588                 :         232 :     ReleaseCurrentSubTransaction();
     589                 :         232 :     MemoryContextSwitchTo(oldcontext);
     590                 :         232 :     CurrentResourceOwner = oldowner;
     591                 :         232 : }
     592                 :             : 
     593                 :             : void
     594                 :          30 : PLy_spi_subtransaction_abort(MemoryContext oldcontext, ResourceOwner oldowner)
     595                 :             : {
     596                 :             :     ErrorData  *edata;
     597                 :             :     PLyExceptionEntry *entry;
     598                 :             :     PyObject   *exc;
     599                 :             : 
     600                 :             :     /* Save error info */
     601                 :          30 :     MemoryContextSwitchTo(oldcontext);
     602                 :          30 :     edata = CopyErrorData();
     603                 :          30 :     FlushErrorState();
     604                 :             : 
     605                 :             :     /* Abort the inner transaction */
     606                 :          30 :     RollbackAndReleaseCurrentSubTransaction();
     607                 :          30 :     MemoryContextSwitchTo(oldcontext);
     608                 :          30 :     CurrentResourceOwner = oldowner;
     609                 :             : 
     610                 :             :     /* Look up the correct exception */
     611                 :          30 :     entry = hash_search(PLy_spi_exceptions, &(edata->sqlerrcode),
     612                 :             :                         HASH_FIND, NULL);
     613                 :             : 
     614                 :             :     /*
     615                 :             :      * This could be a custom error code, if that's the case fallback to
     616                 :             :      * SPIError
     617                 :             :      */
     618         [ +  + ]:          30 :     exc = entry ? entry->exc : PLy_exc_spi_error;
     619                 :             :     /* Make Python raise the exception */
     620                 :          30 :     PLy_spi_exception_set(exc, edata);
     621                 :          30 :     FreeErrorData(edata);
     622                 :          30 : }
     623                 :             : 
     624                 :             : /*
     625                 :             :  * Raise a SPIError, passing in it more error details, like the
     626                 :             :  * internal query and error position.
     627                 :             :  */
     628                 :             : static void
     629                 :          36 : PLy_spi_exception_set(PyObject *excclass, ErrorData *edata)
     630                 :             : {
     631                 :          36 :     PyObject   *args = NULL;
     632                 :          36 :     PyObject   *spierror = NULL;
     633                 :          36 :     PyObject   *spidata = NULL;
     634                 :             : 
     635                 :          36 :     args = Py_BuildValue("(s)", edata->message);
     636         [ -  + ]:          36 :     if (!args)
     637                 :           0 :         goto failure;
     638                 :             : 
     639                 :             :     /* create a new SPI exception with the error message as the parameter */
     640                 :          36 :     spierror = PyObject_CallObject(excclass, args);
     641         [ -  + ]:          36 :     if (!spierror)
     642                 :           0 :         goto failure;
     643                 :             : 
     644                 :          36 :     spidata = Py_BuildValue("(izzzizzzzz)", edata->sqlerrcode, edata->detail, edata->hint,
     645                 :             :                             edata->internalquery, edata->internalpos,
     646                 :             :                             edata->schema_name, edata->table_name, edata->column_name,
     647                 :             :                             edata->datatype_name, edata->constraint_name);
     648         [ -  + ]:          36 :     if (!spidata)
     649                 :           0 :         goto failure;
     650                 :             : 
     651         [ -  + ]:          36 :     if (PyObject_SetAttrString(spierror, "spidata", spidata) == -1)
     652                 :           0 :         goto failure;
     653                 :             : 
     654                 :          36 :     PyErr_SetObject(excclass, spierror);
     655                 :             : 
     656                 :             :     Py_DECREF(args);
     657                 :             :     Py_DECREF(spierror);
     658                 :             :     Py_DECREF(spidata);
     659                 :          36 :     return;
     660                 :             : 
     661                 :           0 : failure:
     662                 :           0 :     Py_XDECREF(args);
     663                 :           0 :     Py_XDECREF(spierror);
     664                 :           0 :     Py_XDECREF(spidata);
     665         [ #  # ]:           0 :     elog(ERROR, "could not convert SPI error to Python exception");
     666                 :             : }
        

Generated by: LCOV version 2.0-1