LCOV - code coverage report
Current view: top level - src/pl/tcl - pltcl.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 997 1090 91.5 %
Date: 2025-01-18 04:15:08 Functions: 41 47 87.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /**********************************************************************
       2             :  * pltcl.c      - PostgreSQL support for Tcl as
       3             :  *                procedural language (PL)
       4             :  *
       5             :  *    src/pl/tcl/pltcl.c
       6             :  *
       7             :  **********************************************************************/
       8             : 
       9             : #include "postgres.h"
      10             : 
      11             : #include <tcl.h>
      12             : 
      13             : #include <unistd.h>
      14             : #include <fcntl.h>
      15             : 
      16             : #include "access/htup_details.h"
      17             : #include "access/xact.h"
      18             : #include "catalog/objectaccess.h"
      19             : #include "catalog/pg_proc.h"
      20             : #include "catalog/pg_type.h"
      21             : #include "commands/event_trigger.h"
      22             : #include "commands/trigger.h"
      23             : #include "executor/spi.h"
      24             : #include "fmgr.h"
      25             : #include "funcapi.h"
      26             : #include "mb/pg_wchar.h"
      27             : #include "miscadmin.h"
      28             : #include "parser/parse_func.h"
      29             : #include "parser/parse_type.h"
      30             : #include "pgstat.h"
      31             : #include "utils/acl.h"
      32             : #include "utils/builtins.h"
      33             : #include "utils/guc.h"
      34             : #include "utils/lsyscache.h"
      35             : #include "utils/memutils.h"
      36             : #include "utils/regproc.h"
      37             : #include "utils/rel.h"
      38             : #include "utils/syscache.h"
      39             : #include "utils/typcache.h"
      40             : 
      41             : 
      42          18 : PG_MODULE_MAGIC;
      43             : 
      44             : #define HAVE_TCL_VERSION(maj,min) \
      45             :     ((TCL_MAJOR_VERSION > maj) || \
      46             :      (TCL_MAJOR_VERSION == maj && TCL_MINOR_VERSION >= min))
      47             : 
      48             : /* Insist on Tcl >= 8.4 */
      49             : #if !HAVE_TCL_VERSION(8,4)
      50             : #error PostgreSQL only supports Tcl 8.4 or later.
      51             : #endif
      52             : 
      53             : /* Hack to deal with Tcl 8.6 const-ification without losing compatibility */
      54             : #ifndef CONST86
      55             : #define CONST86
      56             : #endif
      57             : 
      58             : #if !HAVE_TCL_VERSION(8,7)
      59             : typedef int Tcl_Size;
      60             : #endif
      61             : 
      62             : /* define our text domain for translations */
      63             : #undef TEXTDOMAIN
      64             : #define TEXTDOMAIN PG_TEXTDOMAIN("pltcl")
      65             : 
      66             : 
      67             : /*
      68             :  * Support for converting between UTF8 (which is what all strings going into
      69             :  * or out of Tcl should be) and the database encoding.
      70             :  *
      71             :  * If you just use utf_u2e() or utf_e2u() directly, they will leak some
      72             :  * palloc'd space when doing a conversion.  This is not worth worrying about
      73             :  * if it only happens, say, once per PL/Tcl function call.  If it does seem
      74             :  * worth worrying about, use the wrapper macros.
      75             :  */
      76             : 
      77             : static inline char *
      78        1524 : utf_u2e(const char *src)
      79             : {
      80        1524 :     return pg_any_to_server(src, strlen(src), PG_UTF8);
      81             : }
      82             : 
      83             : static inline char *
      84        2702 : utf_e2u(const char *src)
      85             : {
      86        2702 :     return pg_server_to_any(src, strlen(src), PG_UTF8);
      87             : }
      88             : 
      89             : #define UTF_BEGIN \
      90             :     do { \
      91             :         const char *_pltcl_utf_src = NULL; \
      92             :         char *_pltcl_utf_dst = NULL
      93             : 
      94             : #define UTF_END \
      95             :     if (_pltcl_utf_src != (const char *) _pltcl_utf_dst) \
      96             :             pfree(_pltcl_utf_dst); \
      97             :     } while (0)
      98             : 
      99             : #define UTF_U2E(x) \
     100             :     (_pltcl_utf_dst = utf_u2e(_pltcl_utf_src = (x)))
     101             : 
     102             : #define UTF_E2U(x) \
     103             :     (_pltcl_utf_dst = utf_e2u(_pltcl_utf_src = (x)))
     104             : 
     105             : 
     106             : /**********************************************************************
     107             :  * Information associated with a Tcl interpreter.  We have one interpreter
     108             :  * that is used for all pltclu (untrusted) functions.  For pltcl (trusted)
     109             :  * functions, there is a separate interpreter for each effective SQL userid.
     110             :  * (This is needed to ensure that an unprivileged user can't inject Tcl code
     111             :  * that'll be executed with the privileges of some other SQL user.)
     112             :  *
     113             :  * The pltcl_interp_desc structs are kept in a Postgres hash table indexed
     114             :  * by userid OID, with OID 0 used for the single untrusted interpreter.
     115             :  **********************************************************************/
     116             : typedef struct pltcl_interp_desc
     117             : {
     118             :     Oid         user_id;        /* Hash key (must be first!) */
     119             :     Tcl_Interp *interp;         /* The interpreter */
     120             :     Tcl_HashTable query_hash;   /* pltcl_query_desc structs */
     121             : } pltcl_interp_desc;
     122             : 
     123             : 
     124             : /**********************************************************************
     125             :  * The information we cache about loaded procedures
     126             :  *
     127             :  * The pltcl_proc_desc struct itself, as well as all subsidiary data,
     128             :  * is stored in the memory context identified by the fn_cxt field.
     129             :  * We can reclaim all the data by deleting that context, and should do so
     130             :  * when the fn_refcount goes to zero.  That will happen if we build a new
     131             :  * pltcl_proc_desc following an update of the pg_proc row.  If that happens
     132             :  * while the old proc is being executed, we mustn't remove the struct until
     133             :  * execution finishes.  When building a new pltcl_proc_desc, we unlink
     134             :  * Tcl's copy of the old procedure definition, similarly relying on Tcl's
     135             :  * internal reference counting to prevent that structure from disappearing
     136             :  * while it's in use.
     137             :  *
     138             :  * Note that the data in this struct is shared across all active calls;
     139             :  * nothing except the fn_refcount should be changed by a call instance.
     140             :  **********************************************************************/
     141             : typedef struct pltcl_proc_desc
     142             : {
     143             :     char       *user_proname;   /* user's name (from format_procedure) */
     144             :     char       *internal_proname;   /* Tcl proc name (NULL if deleted) */
     145             :     MemoryContext fn_cxt;       /* memory context for this procedure */
     146             :     unsigned long fn_refcount;  /* number of active references */
     147             :     TransactionId fn_xmin;      /* xmin of pg_proc row */
     148             :     ItemPointerData fn_tid;     /* TID of pg_proc row */
     149             :     bool        fn_readonly;    /* is function readonly? */
     150             :     bool        lanpltrusted;   /* is it pltcl (vs. pltclu)? */
     151             :     pltcl_interp_desc *interp_desc; /* interpreter to use */
     152             :     Oid         result_typid;   /* OID of fn's result type */
     153             :     FmgrInfo    result_in_func; /* input function for fn's result type */
     154             :     Oid         result_typioparam;  /* param to pass to same */
     155             :     bool        fn_retisset;    /* true if function returns a set */
     156             :     bool        fn_retistuple;  /* true if function returns composite */
     157             :     bool        fn_retisdomain; /* true if function returns domain */
     158             :     void       *domain_info;    /* opaque cache for domain checks */
     159             :     int         nargs;          /* number of arguments */
     160             :     /* these arrays have nargs entries: */
     161             :     FmgrInfo   *arg_out_func;   /* output fns for arg types */
     162             :     bool       *arg_is_rowtype; /* is each arg composite? */
     163             : } pltcl_proc_desc;
     164             : 
     165             : 
     166             : /**********************************************************************
     167             :  * The information we cache about prepared and saved plans
     168             :  **********************************************************************/
     169             : typedef struct pltcl_query_desc
     170             : {
     171             :     char        qname[20];
     172             :     SPIPlanPtr  plan;
     173             :     int         nargs;
     174             :     Oid        *argtypes;
     175             :     FmgrInfo   *arginfuncs;
     176             :     Oid        *argtypioparams;
     177             : } pltcl_query_desc;
     178             : 
     179             : 
     180             : /**********************************************************************
     181             :  * For speedy lookup, we maintain a hash table mapping from
     182             :  * function OID + trigger flag + user OID to pltcl_proc_desc pointers.
     183             :  * The reason the pltcl_proc_desc struct isn't directly part of the hash
     184             :  * entry is to simplify recovery from errors during compile_pltcl_function.
     185             :  *
     186             :  * Note: if the same function is called by multiple userIDs within a session,
     187             :  * there will be a separate pltcl_proc_desc entry for each userID in the case
     188             :  * of pltcl functions, but only one entry for pltclu functions, because we
     189             :  * set user_id = 0 for that case.
     190             :  **********************************************************************/
     191             : typedef struct pltcl_proc_key
     192             : {
     193             :     Oid         proc_id;        /* Function OID */
     194             : 
     195             :     /*
     196             :      * is_trigger is really a bool, but declare as Oid to ensure this struct
     197             :      * contains no padding
     198             :      */
     199             :     Oid         is_trigger;     /* is it a trigger function? */
     200             :     Oid         user_id;        /* User calling the function, or 0 */
     201             : } pltcl_proc_key;
     202             : 
     203             : typedef struct pltcl_proc_ptr
     204             : {
     205             :     pltcl_proc_key proc_key;    /* Hash key (must be first!) */
     206             :     pltcl_proc_desc *proc_ptr;
     207             : } pltcl_proc_ptr;
     208             : 
     209             : 
     210             : /**********************************************************************
     211             :  * Per-call state
     212             :  **********************************************************************/
     213             : typedef struct pltcl_call_state
     214             : {
     215             :     /* Call info struct, or NULL in a trigger */
     216             :     FunctionCallInfo fcinfo;
     217             : 
     218             :     /* Trigger data, if we're in a normal (not event) trigger; else NULL */
     219             :     TriggerData *trigdata;
     220             : 
     221             :     /* Function we're executing (NULL if not yet identified) */
     222             :     pltcl_proc_desc *prodesc;
     223             : 
     224             :     /*
     225             :      * Information for SRFs and functions returning composite types.
     226             :      * ret_tupdesc and attinmeta are set up if either fn_retistuple or
     227             :      * fn_retisset, since even a scalar-returning SRF needs a tuplestore.
     228             :      */
     229             :     TupleDesc   ret_tupdesc;    /* return rowtype, if retistuple or retisset */
     230             :     AttInMetadata *attinmeta;   /* metadata for building tuples of that type */
     231             : 
     232             :     ReturnSetInfo *rsi;         /* passed-in ReturnSetInfo, if any */
     233             :     Tuplestorestate *tuple_store;   /* SRFs accumulate result here */
     234             :     MemoryContext tuple_store_cxt;  /* context and resowner for tuplestore */
     235             :     ResourceOwner tuple_store_owner;
     236             : } pltcl_call_state;
     237             : 
     238             : 
     239             : /**********************************************************************
     240             :  * Global data
     241             :  **********************************************************************/
     242             : static char *pltcl_start_proc = NULL;
     243             : static char *pltclu_start_proc = NULL;
     244             : static bool pltcl_pm_init_done = false;
     245             : static Tcl_Interp *pltcl_hold_interp = NULL;
     246             : static HTAB *pltcl_interp_htab = NULL;
     247             : static HTAB *pltcl_proc_htab = NULL;
     248             : 
     249             : /* this is saved and restored by pltcl_handler */
     250             : static pltcl_call_state *pltcl_current_call_state = NULL;
     251             : 
     252             : /**********************************************************************
     253             :  * Lookup table for SQLSTATE condition names
     254             :  **********************************************************************/
     255             : typedef struct
     256             : {
     257             :     const char *label;
     258             :     int         sqlerrstate;
     259             : } TclExceptionNameMap;
     260             : 
     261             : static const TclExceptionNameMap exception_name_map[] = {
     262             : #include "pltclerrcodes.h"
     263             :     {NULL, 0}
     264             : };
     265             : 
     266             : /**********************************************************************
     267             :  * Forward declarations
     268             :  **********************************************************************/
     269             : 
     270             : static void pltcl_init_interp(pltcl_interp_desc *interp_desc,
     271             :                               Oid prolang, bool pltrusted);
     272             : static pltcl_interp_desc *pltcl_fetch_interp(Oid prolang, bool pltrusted);
     273             : static void call_pltcl_start_proc(Oid prolang, bool pltrusted);
     274             : static void start_proc_error_callback(void *arg);
     275             : 
     276             : static Datum pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted);
     277             : 
     278             : static Datum pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
     279             :                                 bool pltrusted);
     280             : static HeapTuple pltcl_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
     281             :                                        bool pltrusted);
     282             : static void pltcl_event_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
     283             :                                         bool pltrusted);
     284             : 
     285             : static void throw_tcl_error(Tcl_Interp *interp, const char *proname);
     286             : 
     287             : static pltcl_proc_desc *compile_pltcl_function(Oid fn_oid, Oid tgreloid,
     288             :                                                bool is_event_trigger,
     289             :                                                bool pltrusted);
     290             : 
     291             : static int  pltcl_elog(ClientData cdata, Tcl_Interp *interp,
     292             :                        int objc, Tcl_Obj *const objv[]);
     293             : static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata);
     294             : static const char *pltcl_get_condition_name(int sqlstate);
     295             : static int  pltcl_quote(ClientData cdata, Tcl_Interp *interp,
     296             :                         int objc, Tcl_Obj *const objv[]);
     297             : static int  pltcl_argisnull(ClientData cdata, Tcl_Interp *interp,
     298             :                             int objc, Tcl_Obj *const objv[]);
     299             : static int  pltcl_returnnull(ClientData cdata, Tcl_Interp *interp,
     300             :                              int objc, Tcl_Obj *const objv[]);
     301             : static int  pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
     302             :                              int objc, Tcl_Obj *const objv[]);
     303             : static int  pltcl_SPI_execute(ClientData cdata, Tcl_Interp *interp,
     304             :                               int objc, Tcl_Obj *const objv[]);
     305             : static int  pltcl_process_SPI_result(Tcl_Interp *interp,
     306             :                                      const char *arrayname,
     307             :                                      Tcl_Obj *loop_body,
     308             :                                      int spi_rc,
     309             :                                      SPITupleTable *tuptable,
     310             :                                      uint64 ntuples);
     311             : static int  pltcl_SPI_prepare(ClientData cdata, Tcl_Interp *interp,
     312             :                               int objc, Tcl_Obj *const objv[]);
     313             : static int  pltcl_SPI_execute_plan(ClientData cdata, Tcl_Interp *interp,
     314             :                                    int objc, Tcl_Obj *const objv[]);
     315             : static int  pltcl_subtransaction(ClientData cdata, Tcl_Interp *interp,
     316             :                                  int objc, Tcl_Obj *const objv[]);
     317             : static int  pltcl_commit(ClientData cdata, Tcl_Interp *interp,
     318             :                          int objc, Tcl_Obj *const objv[]);
     319             : static int  pltcl_rollback(ClientData cdata, Tcl_Interp *interp,
     320             :                            int objc, Tcl_Obj *const objv[]);
     321             : 
     322             : static void pltcl_subtrans_begin(MemoryContext oldcontext,
     323             :                                  ResourceOwner oldowner);
     324             : static void pltcl_subtrans_commit(MemoryContext oldcontext,
     325             :                                   ResourceOwner oldowner);
     326             : static void pltcl_subtrans_abort(Tcl_Interp *interp,
     327             :                                  MemoryContext oldcontext,
     328             :                                  ResourceOwner oldowner);
     329             : 
     330             : static void pltcl_set_tuple_values(Tcl_Interp *interp, const char *arrayname,
     331             :                                    uint64 tupno, HeapTuple tuple, TupleDesc tupdesc);
     332             : static Tcl_Obj *pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated);
     333             : static HeapTuple pltcl_build_tuple_result(Tcl_Interp *interp,
     334             :                                           Tcl_Obj **kvObjv, int kvObjc,
     335             :                                           pltcl_call_state *call_state);
     336             : static void pltcl_init_tuple_store(pltcl_call_state *call_state);
     337             : 
     338             : 
     339             : /*
     340             :  * Hack to override Tcl's builtin Notifier subsystem.  This prevents the
     341             :  * backend from becoming multithreaded, which breaks all sorts of things.
     342             :  * That happens in the default version of Tcl_InitNotifier if the Tcl library
     343             :  * has been compiled with multithreading support (i.e. when TCL_THREADS is
     344             :  * defined under Unix, and in all cases under Windows).
     345             :  * It's okay to disable the notifier because we never enter the Tcl event loop
     346             :  * from Postgres, so the notifier capabilities are initialized, but never
     347             :  * used.  Only InitNotifier and DeleteFileHandler ever seem to get called
     348             :  * within Postgres, but we implement all the functions for completeness.
     349             :  */
     350             : static ClientData
     351          18 : pltcl_InitNotifier(void)
     352             : {
     353             :     static int  fakeThreadKey;  /* To give valid address for ClientData */
     354             : 
     355          18 :     return (ClientData) &(fakeThreadKey);
     356             : }
     357             : 
     358             : static void
     359           0 : pltcl_FinalizeNotifier(ClientData clientData)
     360             : {
     361           0 : }
     362             : 
     363             : static void
     364           2 : pltcl_SetTimer(CONST86 Tcl_Time *timePtr)
     365             : {
     366           2 : }
     367             : 
     368             : static void
     369           0 : pltcl_AlertNotifier(ClientData clientData)
     370             : {
     371           0 : }
     372             : 
     373             : static void
     374           0 : pltcl_CreateFileHandler(int fd, int mask,
     375             :                         Tcl_FileProc *proc, ClientData clientData)
     376             : {
     377           0 : }
     378             : 
     379             : static void
     380          88 : pltcl_DeleteFileHandler(int fd)
     381             : {
     382          88 : }
     383             : 
     384             : static void
     385           0 : pltcl_ServiceModeHook(int mode)
     386             : {
     387           0 : }
     388             : 
     389             : static int
     390      783862 : pltcl_WaitForEvent(CONST86 Tcl_Time *timePtr)
     391             : {
     392      783862 :     return 0;
     393             : }
     394             : 
     395             : 
     396             : /*
     397             :  * _PG_init()           - library load-time initialization
     398             :  *
     399             :  * DO NOT make this static nor change its name!
     400             :  *
     401             :  * The work done here must be safe to do in the postmaster process,
     402             :  * in case the pltcl library is preloaded in the postmaster.
     403             :  */
     404             : void
     405          18 : _PG_init(void)
     406             : {
     407             :     Tcl_NotifierProcs notifier;
     408             :     HASHCTL     hash_ctl;
     409             : 
     410             :     /* Be sure we do initialization only once (should be redundant now) */
     411          18 :     if (pltcl_pm_init_done)
     412           0 :         return;
     413             : 
     414          18 :     pg_bindtextdomain(TEXTDOMAIN);
     415             : 
     416             : #ifdef WIN32
     417             :     /* Required on win32 to prevent error loading init.tcl */
     418             :     Tcl_FindExecutable("");
     419             : #endif
     420             : 
     421             :     /*
     422             :      * Override the functions in the Notifier subsystem.  See comments above.
     423             :      */
     424          18 :     notifier.setTimerProc = pltcl_SetTimer;
     425          18 :     notifier.waitForEventProc = pltcl_WaitForEvent;
     426          18 :     notifier.createFileHandlerProc = pltcl_CreateFileHandler;
     427          18 :     notifier.deleteFileHandlerProc = pltcl_DeleteFileHandler;
     428          18 :     notifier.initNotifierProc = pltcl_InitNotifier;
     429          18 :     notifier.finalizeNotifierProc = pltcl_FinalizeNotifier;
     430          18 :     notifier.alertNotifierProc = pltcl_AlertNotifier;
     431          18 :     notifier.serviceModeHookProc = pltcl_ServiceModeHook;
     432          18 :     Tcl_SetNotifier(&notifier);
     433             : 
     434             :     /************************************************************
     435             :      * Create the dummy hold interpreter to prevent close of
     436             :      * stdout and stderr on DeleteInterp
     437             :      ************************************************************/
     438          18 :     if ((pltcl_hold_interp = Tcl_CreateInterp()) == NULL)
     439           0 :         elog(ERROR, "could not create dummy Tcl interpreter");
     440          18 :     if (Tcl_Init(pltcl_hold_interp) == TCL_ERROR)
     441           0 :         elog(ERROR, "could not initialize dummy Tcl interpreter");
     442             : 
     443             :     /************************************************************
     444             :      * Create the hash table for working interpreters
     445             :      ************************************************************/
     446          18 :     hash_ctl.keysize = sizeof(Oid);
     447          18 :     hash_ctl.entrysize = sizeof(pltcl_interp_desc);
     448          18 :     pltcl_interp_htab = hash_create("PL/Tcl interpreters",
     449             :                                     8,
     450             :                                     &hash_ctl,
     451             :                                     HASH_ELEM | HASH_BLOBS);
     452             : 
     453             :     /************************************************************
     454             :      * Create the hash table for function lookup
     455             :      ************************************************************/
     456          18 :     hash_ctl.keysize = sizeof(pltcl_proc_key);
     457          18 :     hash_ctl.entrysize = sizeof(pltcl_proc_ptr);
     458          18 :     pltcl_proc_htab = hash_create("PL/Tcl functions",
     459             :                                   100,
     460             :                                   &hash_ctl,
     461             :                                   HASH_ELEM | HASH_BLOBS);
     462             : 
     463             :     /************************************************************
     464             :      * Define PL/Tcl's custom GUCs
     465             :      ************************************************************/
     466          18 :     DefineCustomStringVariable("pltcl.start_proc",
     467             :                                gettext_noop("PL/Tcl function to call once when pltcl is first used."),
     468             :                                NULL,
     469             :                                &pltcl_start_proc,
     470             :                                NULL,
     471             :                                PGC_SUSET, 0,
     472             :                                NULL, NULL, NULL);
     473          18 :     DefineCustomStringVariable("pltclu.start_proc",
     474             :                                gettext_noop("PL/TclU function to call once when pltclu is first used."),
     475             :                                NULL,
     476             :                                &pltclu_start_proc,
     477             :                                NULL,
     478             :                                PGC_SUSET, 0,
     479             :                                NULL, NULL, NULL);
     480             : 
     481          18 :     MarkGUCPrefixReserved("pltcl");
     482          18 :     MarkGUCPrefixReserved("pltclu");
     483             : 
     484          18 :     pltcl_pm_init_done = true;
     485             : }
     486             : 
     487             : /**********************************************************************
     488             :  * pltcl_init_interp() - initialize a new Tcl interpreter
     489             :  **********************************************************************/
     490             : static void
     491          22 : pltcl_init_interp(pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
     492             : {
     493             :     Tcl_Interp *interp;
     494             :     char        interpname[32];
     495             : 
     496             :     /************************************************************
     497             :      * Create the Tcl interpreter subsidiary to pltcl_hold_interp.
     498             :      * Note: Tcl automatically does Tcl_Init in the untrusted case,
     499             :      * and it's not wanted in the trusted case.
     500             :      ************************************************************/
     501          22 :     snprintf(interpname, sizeof(interpname), "subsidiary_%u", interp_desc->user_id);
     502          22 :     if ((interp = Tcl_CreateSlave(pltcl_hold_interp, interpname,
     503             :                                   pltrusted ? 1 : 0)) == NULL)
     504           0 :         elog(ERROR, "could not create subsidiary Tcl interpreter");
     505             : 
     506             :     /************************************************************
     507             :      * Initialize the query hash table associated with interpreter
     508             :      ************************************************************/
     509          22 :     Tcl_InitHashTable(&interp_desc->query_hash, TCL_STRING_KEYS);
     510             : 
     511             :     /************************************************************
     512             :      * Install the commands for SPI support in the interpreter
     513             :      ************************************************************/
     514          22 :     Tcl_CreateObjCommand(interp, "elog",
     515             :                          pltcl_elog, NULL, NULL);
     516          22 :     Tcl_CreateObjCommand(interp, "quote",
     517             :                          pltcl_quote, NULL, NULL);
     518          22 :     Tcl_CreateObjCommand(interp, "argisnull",
     519             :                          pltcl_argisnull, NULL, NULL);
     520          22 :     Tcl_CreateObjCommand(interp, "return_null",
     521             :                          pltcl_returnnull, NULL, NULL);
     522          22 :     Tcl_CreateObjCommand(interp, "return_next",
     523             :                          pltcl_returnnext, NULL, NULL);
     524          22 :     Tcl_CreateObjCommand(interp, "spi_exec",
     525             :                          pltcl_SPI_execute, NULL, NULL);
     526          22 :     Tcl_CreateObjCommand(interp, "spi_prepare",
     527             :                          pltcl_SPI_prepare, NULL, NULL);
     528          22 :     Tcl_CreateObjCommand(interp, "spi_execp",
     529             :                          pltcl_SPI_execute_plan, NULL, NULL);
     530          22 :     Tcl_CreateObjCommand(interp, "subtransaction",
     531             :                          pltcl_subtransaction, NULL, NULL);
     532          22 :     Tcl_CreateObjCommand(interp, "commit",
     533             :                          pltcl_commit, NULL, NULL);
     534          22 :     Tcl_CreateObjCommand(interp, "rollback",
     535             :                          pltcl_rollback, NULL, NULL);
     536             : 
     537             :     /************************************************************
     538             :      * Call the appropriate start_proc, if there is one.
     539             :      *
     540             :      * We must set interp_desc->interp before the call, else the start_proc
     541             :      * won't find the interpreter it's supposed to use.  But, if the
     542             :      * start_proc fails, we want to abandon use of the interpreter.
     543             :      ************************************************************/
     544          22 :     PG_TRY();
     545             :     {
     546          22 :         interp_desc->interp = interp;
     547          22 :         call_pltcl_start_proc(prolang, pltrusted);
     548             :     }
     549           6 :     PG_CATCH();
     550             :     {
     551           6 :         interp_desc->interp = NULL;
     552           6 :         Tcl_DeleteInterp(interp);
     553           6 :         PG_RE_THROW();
     554             :     }
     555          16 :     PG_END_TRY();
     556          16 : }
     557             : 
     558             : /**********************************************************************
     559             :  * pltcl_fetch_interp() - fetch the Tcl interpreter to use for a function
     560             :  *
     561             :  * This also takes care of any on-first-use initialization required.
     562             :  **********************************************************************/
     563             : static pltcl_interp_desc *
     564         130 : pltcl_fetch_interp(Oid prolang, bool pltrusted)
     565             : {
     566             :     Oid         user_id;
     567             :     pltcl_interp_desc *interp_desc;
     568             :     bool        found;
     569             : 
     570             :     /* Find or create the interpreter hashtable entry for this userid */
     571         130 :     if (pltrusted)
     572         130 :         user_id = GetUserId();
     573             :     else
     574           0 :         user_id = InvalidOid;
     575             : 
     576         130 :     interp_desc = hash_search(pltcl_interp_htab, &user_id,
     577             :                               HASH_ENTER,
     578             :                               &found);
     579         130 :     if (!found)
     580          16 :         interp_desc->interp = NULL;
     581             : 
     582             :     /* If we haven't yet successfully made an interpreter, try to do that */
     583         130 :     if (!interp_desc->interp)
     584          22 :         pltcl_init_interp(interp_desc, prolang, pltrusted);
     585             : 
     586         124 :     return interp_desc;
     587             : }
     588             : 
     589             : 
     590             : /**********************************************************************
     591             :  * call_pltcl_start_proc()   - Call user-defined initialization proc, if any
     592             :  **********************************************************************/
     593             : static void
     594          22 : call_pltcl_start_proc(Oid prolang, bool pltrusted)
     595             : {
     596          22 :     LOCAL_FCINFO(fcinfo, 0);
     597             :     char       *start_proc;
     598             :     const char *gucname;
     599             :     ErrorContextCallback errcallback;
     600             :     List       *namelist;
     601             :     Oid         procOid;
     602             :     HeapTuple   procTup;
     603             :     Form_pg_proc procStruct;
     604             :     AclResult   aclresult;
     605             :     FmgrInfo    finfo;
     606             :     PgStat_FunctionCallUsage fcusage;
     607             : 
     608             :     /* select appropriate GUC */
     609          22 :     start_proc = pltrusted ? pltcl_start_proc : pltclu_start_proc;
     610          22 :     gucname = pltrusted ? "pltcl.start_proc" : "pltclu.start_proc";
     611             : 
     612             :     /* Nothing to do if it's empty or unset */
     613          22 :     if (start_proc == NULL || start_proc[0] == '\0')
     614          14 :         return;
     615             : 
     616             :     /* Set up errcontext callback to make errors more helpful */
     617           8 :     errcallback.callback = start_proc_error_callback;
     618           8 :     errcallback.arg = unconstify(char *, gucname);
     619           8 :     errcallback.previous = error_context_stack;
     620           8 :     error_context_stack = &errcallback;
     621             : 
     622             :     /* Parse possibly-qualified identifier and look up the function */
     623           8 :     namelist = stringToQualifiedNameList(start_proc, NULL);
     624           8 :     procOid = LookupFuncName(namelist, 0, NULL, false);
     625             : 
     626             :     /* Current user must have permission to call function */
     627           4 :     aclresult = object_aclcheck(ProcedureRelationId, procOid, GetUserId(), ACL_EXECUTE);
     628           4 :     if (aclresult != ACLCHECK_OK)
     629           0 :         aclcheck_error(aclresult, OBJECT_FUNCTION, start_proc);
     630             : 
     631             :     /* Get the function's pg_proc entry */
     632           4 :     procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(procOid));
     633           4 :     if (!HeapTupleIsValid(procTup))
     634           0 :         elog(ERROR, "cache lookup failed for function %u", procOid);
     635           4 :     procStruct = (Form_pg_proc) GETSTRUCT(procTup);
     636             : 
     637             :     /* It must be same language as the function we're currently calling */
     638           4 :     if (procStruct->prolang != prolang)
     639           0 :         ereport(ERROR,
     640             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     641             :                  errmsg("function \"%s\" is in the wrong language",
     642             :                         start_proc)));
     643             : 
     644             :     /*
     645             :      * It must not be SECURITY DEFINER, either.  This together with the
     646             :      * language match check ensures that the function will execute in the same
     647             :      * Tcl interpreter we just finished initializing.
     648             :      */
     649           4 :     if (procStruct->prosecdef)
     650           2 :         ereport(ERROR,
     651             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     652             :                  errmsg("function \"%s\" must not be SECURITY DEFINER",
     653             :                         start_proc)));
     654             : 
     655             :     /* A-OK */
     656           2 :     ReleaseSysCache(procTup);
     657             : 
     658             :     /*
     659             :      * Call the function using the normal SQL function call mechanism.  We
     660             :      * could perhaps cheat and jump directly to pltcl_handler(), but it seems
     661             :      * better to do it this way so that the call is exposed to, eg, call
     662             :      * statistics collection.
     663             :      */
     664           2 :     InvokeFunctionExecuteHook(procOid);
     665           2 :     fmgr_info(procOid, &finfo);
     666           2 :     InitFunctionCallInfoData(*fcinfo, &finfo,
     667             :                              0,
     668             :                              InvalidOid, NULL, NULL);
     669           2 :     pgstat_init_function_usage(fcinfo, &fcusage);
     670           2 :     (void) FunctionCallInvoke(fcinfo);
     671           2 :     pgstat_end_function_usage(&fcusage, true);
     672             : 
     673             :     /* Pop the error context stack */
     674           2 :     error_context_stack = errcallback.previous;
     675             : }
     676             : 
     677             : /*
     678             :  * Error context callback for errors occurring during start_proc processing.
     679             :  */
     680             : static void
     681           8 : start_proc_error_callback(void *arg)
     682             : {
     683           8 :     const char *gucname = (const char *) arg;
     684             : 
     685             :     /* translator: %s is "pltcl.start_proc" or "pltclu.start_proc" */
     686           8 :     errcontext("processing %s parameter", gucname);
     687           8 : }
     688             : 
     689             : 
     690             : /**********************************************************************
     691             :  * pltcl_call_handler       - This is the only visible function
     692             :  *                of the PL interpreter. The PostgreSQL
     693             :  *                function manager and trigger manager
     694             :  *                call this function for execution of
     695             :  *                PL/Tcl procedures.
     696             :  **********************************************************************/
     697          18 : PG_FUNCTION_INFO_V1(pltcl_call_handler);
     698             : 
     699             : /* keep non-static */
     700             : Datum
     701         446 : pltcl_call_handler(PG_FUNCTION_ARGS)
     702             : {
     703         446 :     return pltcl_handler(fcinfo, true);
     704             : }
     705             : 
     706             : /*
     707             :  * Alternative handler for unsafe functions
     708             :  */
     709           0 : PG_FUNCTION_INFO_V1(pltclu_call_handler);
     710             : 
     711             : /* keep non-static */
     712             : Datum
     713           0 : pltclu_call_handler(PG_FUNCTION_ARGS)
     714             : {
     715           0 :     return pltcl_handler(fcinfo, false);
     716             : }
     717             : 
     718             : 
     719             : /**********************************************************************
     720             :  * pltcl_handler()      - Handler for function and trigger calls, for
     721             :  *                        both trusted and untrusted interpreters.
     722             :  **********************************************************************/
     723             : static Datum
     724         446 : pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted)
     725             : {
     726         446 :     Datum       retval = (Datum) 0;
     727             :     pltcl_call_state current_call_state;
     728             :     pltcl_call_state *save_call_state;
     729             : 
     730             :     /*
     731             :      * Initialize current_call_state to nulls/zeroes; in particular, set its
     732             :      * prodesc pointer to null.  Anything that sets it non-null should
     733             :      * increase the prodesc's fn_refcount at the same time.  We'll decrease
     734             :      * the refcount, and then delete the prodesc if it's no longer referenced,
     735             :      * on the way out of this function.  This ensures that prodescs live as
     736             :      * long as needed even if somebody replaces the originating pg_proc row
     737             :      * while they're executing.
     738             :      */
     739         446 :     memset(&current_call_state, 0, sizeof(current_call_state));
     740             : 
     741             :     /*
     742             :      * Ensure that static pointer is saved/restored properly
     743             :      */
     744         446 :     save_call_state = pltcl_current_call_state;
     745         446 :     pltcl_current_call_state = &current_call_state;
     746             : 
     747         446 :     PG_TRY();
     748             :     {
     749             :         /*
     750             :          * Determine if called as function or trigger and call appropriate
     751             :          * subhandler
     752             :          */
     753         446 :         if (CALLED_AS_TRIGGER(fcinfo))
     754             :         {
     755             :             /* invoke the trigger handler */
     756         116 :             retval = PointerGetDatum(pltcl_trigger_handler(fcinfo,
     757             :                                                            &current_call_state,
     758             :                                                            pltrusted));
     759             :         }
     760         330 :         else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
     761             :         {
     762             :             /* invoke the event trigger handler */
     763          20 :             pltcl_event_trigger_handler(fcinfo, &current_call_state, pltrusted);
     764          20 :             retval = (Datum) 0;
     765             :         }
     766             :         else
     767             :         {
     768             :             /* invoke the regular function handler */
     769         310 :             current_call_state.fcinfo = fcinfo;
     770         310 :             retval = pltcl_func_handler(fcinfo, &current_call_state, pltrusted);
     771             :         }
     772             :     }
     773         110 :     PG_FINALLY();
     774             :     {
     775             :         /* Restore static pointer, then clean up the prodesc refcount if any */
     776             :         /*
     777             :          * (We're being paranoid in case an error is thrown in context
     778             :          * deletion)
     779             :          */
     780         446 :         pltcl_current_call_state = save_call_state;
     781         446 :         if (current_call_state.prodesc != NULL)
     782             :         {
     783             :             Assert(current_call_state.prodesc->fn_refcount > 0);
     784         440 :             if (--current_call_state.prodesc->fn_refcount == 0)
     785           2 :                 MemoryContextDelete(current_call_state.prodesc->fn_cxt);
     786             :         }
     787             :     }
     788         446 :     PG_END_TRY();
     789             : 
     790         336 :     return retval;
     791             : }
     792             : 
     793             : 
     794             : /**********************************************************************
     795             :  * pltcl_func_handler()     - Handler for regular function calls
     796             :  **********************************************************************/
     797             : static Datum
     798         310 : pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
     799             :                    bool pltrusted)
     800             : {
     801             :     bool        nonatomic;
     802             :     pltcl_proc_desc *prodesc;
     803             :     Tcl_Interp *volatile interp;
     804             :     Tcl_Obj    *tcl_cmd;
     805             :     int         i;
     806             :     int         tcl_rc;
     807             :     Datum       retval;
     808             : 
     809         692 :     nonatomic = fcinfo->context &&
     810         336 :         IsA(fcinfo->context, CallContext) &&
     811          26 :         !castNode(CallContext, fcinfo->context)->atomic;
     812             : 
     813             :     /* Connect to SPI manager */
     814         310 :     SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0);
     815             : 
     816             :     /* Find or compile the function */
     817         310 :     prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid, InvalidOid,
     818             :                                      false, pltrusted);
     819             : 
     820         304 :     call_state->prodesc = prodesc;
     821         304 :     prodesc->fn_refcount++;
     822             : 
     823         304 :     interp = prodesc->interp_desc->interp;
     824             : 
     825             :     /*
     826             :      * If we're a SRF, check caller can handle materialize mode, and save
     827             :      * relevant info into call_state.  We must ensure that the returned
     828             :      * tuplestore is owned by the caller's context, even if we first create it
     829             :      * inside a subtransaction.
     830             :      */
     831         304 :     if (prodesc->fn_retisset)
     832             :     {
     833          10 :         ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
     834             : 
     835          10 :         if (!rsi || !IsA(rsi, ReturnSetInfo))
     836           0 :             ereport(ERROR,
     837             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     838             :                      errmsg("set-valued function called in context that cannot accept a set")));
     839             : 
     840          10 :         if (!(rsi->allowedModes & SFRM_Materialize))
     841           0 :             ereport(ERROR,
     842             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     843             :                      errmsg("materialize mode required, but it is not allowed in this context")));
     844             : 
     845          10 :         call_state->rsi = rsi;
     846          10 :         call_state->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
     847          10 :         call_state->tuple_store_owner = CurrentResourceOwner;
     848             :     }
     849             : 
     850             :     /************************************************************
     851             :      * Create the tcl command to call the internal
     852             :      * proc in the Tcl interpreter
     853             :      ************************************************************/
     854         304 :     tcl_cmd = Tcl_NewObj();
     855         304 :     Tcl_ListObjAppendElement(NULL, tcl_cmd,
     856         304 :                              Tcl_NewStringObj(prodesc->internal_proname, -1));
     857             : 
     858             :     /* We hold a refcount on tcl_cmd just to be sure it stays around */
     859         304 :     Tcl_IncrRefCount(tcl_cmd);
     860             : 
     861             :     /************************************************************
     862             :      * Add all call arguments to the command
     863             :      ************************************************************/
     864         304 :     PG_TRY();
     865             :     {
     866         700 :         for (i = 0; i < prodesc->nargs; i++)
     867             :         {
     868         396 :             if (prodesc->arg_is_rowtype[i])
     869             :             {
     870             :                 /**************************************************
     871             :                  * For tuple values, add a list for 'array set ...'
     872             :                  **************************************************/
     873          14 :                 if (fcinfo->args[i].isnull)
     874           0 :                     Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
     875             :                 else
     876             :                 {
     877             :                     HeapTupleHeader td;
     878             :                     Oid         tupType;
     879             :                     int32       tupTypmod;
     880             :                     TupleDesc   tupdesc;
     881             :                     HeapTupleData tmptup;
     882             :                     Tcl_Obj    *list_tmp;
     883             : 
     884          14 :                     td = DatumGetHeapTupleHeader(fcinfo->args[i].value);
     885             :                     /* Extract rowtype info and find a tupdesc */
     886          14 :                     tupType = HeapTupleHeaderGetTypeId(td);
     887          14 :                     tupTypmod = HeapTupleHeaderGetTypMod(td);
     888          14 :                     tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
     889             :                     /* Build a temporary HeapTuple control structure */
     890          14 :                     tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
     891          14 :                     tmptup.t_data = td;
     892             : 
     893          14 :                     list_tmp = pltcl_build_tuple_argument(&tmptup, tupdesc, true);
     894          14 :                     Tcl_ListObjAppendElement(NULL, tcl_cmd, list_tmp);
     895             : 
     896          14 :                     ReleaseTupleDesc(tupdesc);
     897             :                 }
     898             :             }
     899             :             else
     900             :             {
     901             :                 /**************************************************
     902             :                  * Single values are added as string element
     903             :                  * of their external representation
     904             :                  **************************************************/
     905         382 :                 if (fcinfo->args[i].isnull)
     906           4 :                     Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
     907             :                 else
     908             :                 {
     909             :                     char       *tmp;
     910             : 
     911         378 :                     tmp = OutputFunctionCall(&prodesc->arg_out_func[i],
     912             :                                              fcinfo->args[i].value);
     913         378 :                     UTF_BEGIN;
     914         378 :                     Tcl_ListObjAppendElement(NULL, tcl_cmd,
     915         378 :                                              Tcl_NewStringObj(UTF_E2U(tmp), -1));
     916         378 :                     UTF_END;
     917         378 :                     pfree(tmp);
     918             :                 }
     919             :             }
     920             :         }
     921             :     }
     922           0 :     PG_CATCH();
     923             :     {
     924             :         /* Release refcount to free tcl_cmd */
     925           0 :         Tcl_DecrRefCount(tcl_cmd);
     926           0 :         PG_RE_THROW();
     927             :     }
     928         304 :     PG_END_TRY();
     929             : 
     930             :     /************************************************************
     931             :      * Call the Tcl function
     932             :      *
     933             :      * We assume no PG error can be thrown directly from this call.
     934             :      ************************************************************/
     935         304 :     tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
     936             : 
     937             :     /* Release refcount to free tcl_cmd (and all subsidiary objects) */
     938         304 :     Tcl_DecrRefCount(tcl_cmd);
     939             : 
     940             :     /************************************************************
     941             :      * Check for errors reported by Tcl.
     942             :      ************************************************************/
     943         304 :     if (tcl_rc != TCL_OK)
     944          76 :         throw_tcl_error(interp, prodesc->user_proname);
     945             : 
     946             :     /************************************************************
     947             :      * Disconnect from SPI manager and then create the return
     948             :      * value datum (if the input function does a palloc for it
     949             :      * this must not be allocated in the SPI memory context
     950             :      * because SPI_finish would free it).  But don't try to call
     951             :      * the result_in_func if we've been told to return a NULL;
     952             :      * the Tcl result may not be a valid value of the result type
     953             :      * in that case.
     954             :      ************************************************************/
     955         228 :     if (SPI_finish() != SPI_OK_FINISH)
     956           0 :         elog(ERROR, "SPI_finish() failed");
     957             : 
     958         228 :     if (prodesc->fn_retisset)
     959             :     {
     960           6 :         ReturnSetInfo *rsi = call_state->rsi;
     961             : 
     962             :         /* We already checked this is OK */
     963           6 :         rsi->returnMode = SFRM_Materialize;
     964             : 
     965             :         /* If we produced any tuples, send back the result */
     966           6 :         if (call_state->tuple_store)
     967             :         {
     968           6 :             rsi->setResult = call_state->tuple_store;
     969           6 :             if (call_state->ret_tupdesc)
     970             :             {
     971             :                 MemoryContext oldcxt;
     972             : 
     973           6 :                 oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
     974           6 :                 rsi->setDesc = CreateTupleDescCopy(call_state->ret_tupdesc);
     975           6 :                 MemoryContextSwitchTo(oldcxt);
     976             :             }
     977             :         }
     978           6 :         retval = (Datum) 0;
     979           6 :         fcinfo->isnull = true;
     980             :     }
     981         222 :     else if (fcinfo->isnull)
     982             :     {
     983           2 :         retval = InputFunctionCall(&prodesc->result_in_func,
     984             :                                    NULL,
     985             :                                    prodesc->result_typioparam,
     986             :                                    -1);
     987             :     }
     988         220 :     else if (prodesc->fn_retistuple)
     989             :     {
     990             :         TupleDesc   td;
     991             :         HeapTuple   tup;
     992             :         Tcl_Obj    *resultObj;
     993             :         Tcl_Obj   **resultObjv;
     994             :         Tcl_Size    resultObjc;
     995             : 
     996             :         /*
     997             :          * Set up data about result type.  XXX it's tempting to consider
     998             :          * caching this in the prodesc, in the common case where the rowtype
     999             :          * is determined by the function not the calling query.  But we'd have
    1000             :          * to be able to deal with ADD/DROP/ALTER COLUMN events when the
    1001             :          * result type is a named composite type, so it's not exactly trivial.
    1002             :          * Maybe worth improving someday.
    1003             :          */
    1004          32 :         switch (get_call_result_type(fcinfo, NULL, &td))
    1005             :         {
    1006          24 :             case TYPEFUNC_COMPOSITE:
    1007             :                 /* success */
    1008          24 :                 break;
    1009           6 :             case TYPEFUNC_COMPOSITE_DOMAIN:
    1010             :                 Assert(prodesc->fn_retisdomain);
    1011           6 :                 break;
    1012           2 :             case TYPEFUNC_RECORD:
    1013             :                 /* failed to determine actual type of RECORD */
    1014           2 :                 ereport(ERROR,
    1015             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1016             :                          errmsg("function returning record called in context "
    1017             :                                 "that cannot accept type record")));
    1018             :                 break;
    1019           0 :             default:
    1020             :                 /* result type isn't composite? */
    1021           0 :                 elog(ERROR, "return type must be a row type");
    1022             :                 break;
    1023             :         }
    1024             : 
    1025             :         Assert(!call_state->ret_tupdesc);
    1026             :         Assert(!call_state->attinmeta);
    1027          30 :         call_state->ret_tupdesc = td;
    1028          30 :         call_state->attinmeta = TupleDescGetAttInMetadata(td);
    1029             : 
    1030             :         /* Convert function result to tuple */
    1031          30 :         resultObj = Tcl_GetObjResult(interp);
    1032          30 :         if (Tcl_ListObjGetElements(interp, resultObj, &resultObjc, &resultObjv) == TCL_ERROR)
    1033           2 :             ereport(ERROR,
    1034             :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    1035             :                      errmsg("could not parse function return value: %s",
    1036             :                             utf_u2e(Tcl_GetStringResult(interp)))));
    1037             : 
    1038          28 :         tup = pltcl_build_tuple_result(interp, resultObjv, resultObjc,
    1039             :                                        call_state);
    1040          20 :         retval = HeapTupleGetDatum(tup);
    1041             :     }
    1042             :     else
    1043         188 :         retval = InputFunctionCall(&prodesc->result_in_func,
    1044             :                                    utf_u2e(Tcl_GetStringResult(interp)),
    1045             :                                    prodesc->result_typioparam,
    1046             :                                    -1);
    1047             : 
    1048         216 :     return retval;
    1049             : }
    1050             : 
    1051             : 
    1052             : /**********************************************************************
    1053             :  * pltcl_trigger_handler()  - Handler for trigger calls
    1054             :  **********************************************************************/
    1055             : static HeapTuple
    1056         116 : pltcl_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
    1057             :                       bool pltrusted)
    1058             : {
    1059             :     pltcl_proc_desc *prodesc;
    1060             :     Tcl_Interp *volatile interp;
    1061         116 :     TriggerData *trigdata = (TriggerData *) fcinfo->context;
    1062             :     char       *stroid;
    1063             :     TupleDesc   tupdesc;
    1064             :     volatile HeapTuple rettup;
    1065             :     Tcl_Obj    *tcl_cmd;
    1066             :     Tcl_Obj    *tcl_trigtup;
    1067             :     int         tcl_rc;
    1068             :     int         i;
    1069             :     const char *result;
    1070             :     Tcl_Size    result_Objc;
    1071             :     Tcl_Obj   **result_Objv;
    1072             :     int         rc PG_USED_FOR_ASSERTS_ONLY;
    1073             : 
    1074         116 :     call_state->trigdata = trigdata;
    1075             : 
    1076             :     /* Connect to SPI manager */
    1077         116 :     SPI_connect();
    1078             : 
    1079             :     /* Make transition tables visible to this SPI connection */
    1080         116 :     rc = SPI_register_trigger_data(trigdata);
    1081             :     Assert(rc >= 0);
    1082             : 
    1083             :     /* Find or compile the function */
    1084         232 :     prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
    1085         116 :                                      RelationGetRelid(trigdata->tg_relation),
    1086             :                                      false, /* not an event trigger */
    1087             :                                      pltrusted);
    1088             : 
    1089         116 :     call_state->prodesc = prodesc;
    1090         116 :     prodesc->fn_refcount++;
    1091             : 
    1092         116 :     interp = prodesc->interp_desc->interp;
    1093             : 
    1094         116 :     tupdesc = RelationGetDescr(trigdata->tg_relation);
    1095             : 
    1096             :     /************************************************************
    1097             :      * Create the tcl command to call the internal
    1098             :      * proc in the interpreter
    1099             :      ************************************************************/
    1100         116 :     tcl_cmd = Tcl_NewObj();
    1101         116 :     Tcl_IncrRefCount(tcl_cmd);
    1102             : 
    1103         116 :     PG_TRY();
    1104             :     {
    1105             :         /* The procedure name (note this is all ASCII, so no utf_e2u) */
    1106         116 :         Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1107         116 :                                  Tcl_NewStringObj(prodesc->internal_proname, -1));
    1108             : 
    1109             :         /* The trigger name for argument TG_name */
    1110         116 :         Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1111         116 :                                  Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgname), -1));
    1112             : 
    1113             :         /* The oid of the trigger relation for argument TG_relid */
    1114             :         /* Consider not converting to a string for more performance? */
    1115         116 :         stroid = DatumGetCString(DirectFunctionCall1(oidout,
    1116             :                                                      ObjectIdGetDatum(trigdata->tg_relation->rd_id)));
    1117         116 :         Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1118             :                                  Tcl_NewStringObj(stroid, -1));
    1119         116 :         pfree(stroid);
    1120             : 
    1121             :         /* The name of the table the trigger is acting on: TG_table_name */
    1122         116 :         stroid = SPI_getrelname(trigdata->tg_relation);
    1123         116 :         Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1124         116 :                                  Tcl_NewStringObj(utf_e2u(stroid), -1));
    1125         116 :         pfree(stroid);
    1126             : 
    1127             :         /* The schema of the table the trigger is acting on: TG_table_schema */
    1128         116 :         stroid = SPI_getnspname(trigdata->tg_relation);
    1129         116 :         Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1130         116 :                                  Tcl_NewStringObj(utf_e2u(stroid), -1));
    1131         116 :         pfree(stroid);
    1132             : 
    1133             :         /* A list of attribute names for argument TG_relatts */
    1134         116 :         tcl_trigtup = Tcl_NewObj();
    1135         116 :         Tcl_ListObjAppendElement(NULL, tcl_trigtup, Tcl_NewObj());
    1136         516 :         for (i = 0; i < tupdesc->natts; i++)
    1137             :         {
    1138         400 :             Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    1139             : 
    1140         400 :             if (att->attisdropped)
    1141          26 :                 Tcl_ListObjAppendElement(NULL, tcl_trigtup, Tcl_NewObj());
    1142             :             else
    1143         374 :                 Tcl_ListObjAppendElement(NULL, tcl_trigtup,
    1144         374 :                                          Tcl_NewStringObj(utf_e2u(NameStr(att->attname)), -1));
    1145             :         }
    1146         116 :         Tcl_ListObjAppendElement(NULL, tcl_cmd, tcl_trigtup);
    1147             : 
    1148             :         /* The when part of the event for TG_when */
    1149         116 :         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
    1150          94 :             Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1151             :                                      Tcl_NewStringObj("BEFORE", -1));
    1152          22 :         else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
    1153          16 :             Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1154             :                                      Tcl_NewStringObj("AFTER", -1));
    1155           6 :         else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
    1156           6 :             Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1157             :                                      Tcl_NewStringObj("INSTEAD OF", -1));
    1158             :         else
    1159           0 :             elog(ERROR, "unrecognized WHEN tg_event: %u", trigdata->tg_event);
    1160             : 
    1161             :         /* The level part of the event for TG_level */
    1162         116 :         if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
    1163             :         {
    1164         100 :             Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1165             :                                      Tcl_NewStringObj("ROW", -1));
    1166             : 
    1167             :             /*
    1168             :              * Now the command part of the event for TG_op and data for NEW
    1169             :              * and OLD
    1170             :              *
    1171             :              * Note: In BEFORE trigger, stored generated columns are not
    1172             :              * computed yet, so don't make them accessible in NEW row.
    1173             :              */
    1174         100 :             if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    1175             :             {
    1176          60 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1177             :                                          Tcl_NewStringObj("INSERT", -1));
    1178             : 
    1179          60 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1180             :                                          pltcl_build_tuple_argument(trigdata->tg_trigtuple,
    1181             :                                                                     tupdesc,
    1182          60 :                                                                     !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
    1183          60 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
    1184             : 
    1185          60 :                 rettup = trigdata->tg_trigtuple;
    1186             :             }
    1187          40 :             else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
    1188             :             {
    1189          16 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1190             :                                          Tcl_NewStringObj("DELETE", -1));
    1191             : 
    1192          16 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
    1193          16 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1194             :                                          pltcl_build_tuple_argument(trigdata->tg_trigtuple,
    1195             :                                                                     tupdesc,
    1196             :                                                                     true));
    1197             : 
    1198          16 :                 rettup = trigdata->tg_trigtuple;
    1199             :             }
    1200          24 :             else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    1201             :             {
    1202          24 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1203             :                                          Tcl_NewStringObj("UPDATE", -1));
    1204             : 
    1205          24 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1206             :                                          pltcl_build_tuple_argument(trigdata->tg_newtuple,
    1207             :                                                                     tupdesc,
    1208          24 :                                                                     !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
    1209          24 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1210             :                                          pltcl_build_tuple_argument(trigdata->tg_trigtuple,
    1211             :                                                                     tupdesc,
    1212             :                                                                     true));
    1213             : 
    1214          24 :                 rettup = trigdata->tg_newtuple;
    1215             :             }
    1216             :             else
    1217           0 :                 elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
    1218             :         }
    1219          16 :         else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
    1220             :         {
    1221          16 :             Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1222             :                                      Tcl_NewStringObj("STATEMENT", -1));
    1223             : 
    1224          16 :             if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    1225           6 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1226             :                                          Tcl_NewStringObj("INSERT", -1));
    1227          10 :             else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
    1228           2 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1229             :                                          Tcl_NewStringObj("DELETE", -1));
    1230           8 :             else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    1231           6 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1232             :                                          Tcl_NewStringObj("UPDATE", -1));
    1233           2 :             else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
    1234           2 :                 Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1235             :                                          Tcl_NewStringObj("TRUNCATE", -1));
    1236             :             else
    1237           0 :                 elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
    1238             : 
    1239          16 :             Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
    1240          16 :             Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
    1241             : 
    1242          16 :             rettup = (HeapTuple) NULL;
    1243             :         }
    1244             :         else
    1245           0 :             elog(ERROR, "unrecognized LEVEL tg_event: %u", trigdata->tg_event);
    1246             : 
    1247             :         /* Finally append the arguments from CREATE TRIGGER */
    1248         270 :         for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
    1249         154 :             Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1250         154 :                                      Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgargs[i]), -1));
    1251             :     }
    1252           0 :     PG_CATCH();
    1253             :     {
    1254           0 :         Tcl_DecrRefCount(tcl_cmd);
    1255           0 :         PG_RE_THROW();
    1256             :     }
    1257         116 :     PG_END_TRY();
    1258             : 
    1259             :     /************************************************************
    1260             :      * Call the Tcl function
    1261             :      *
    1262             :      * We assume no PG error can be thrown directly from this call.
    1263             :      ************************************************************/
    1264         116 :     tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
    1265             : 
    1266             :     /* Release refcount to free tcl_cmd (and all subsidiary objects) */
    1267         116 :     Tcl_DecrRefCount(tcl_cmd);
    1268             : 
    1269             :     /************************************************************
    1270             :      * Check for errors reported by Tcl.
    1271             :      ************************************************************/
    1272         116 :     if (tcl_rc != TCL_OK)
    1273          14 :         throw_tcl_error(interp, prodesc->user_proname);
    1274             : 
    1275             :     /************************************************************
    1276             :      * Exit SPI environment.
    1277             :      ************************************************************/
    1278         102 :     if (SPI_finish() != SPI_OK_FINISH)
    1279           0 :         elog(ERROR, "SPI_finish() failed");
    1280             : 
    1281             :     /************************************************************
    1282             :      * The return value from the procedure might be one of
    1283             :      * the magic strings OK or SKIP, or a list from array get.
    1284             :      * We can check for OK or SKIP without worrying about encoding.
    1285             :      ************************************************************/
    1286         102 :     result = Tcl_GetStringResult(interp);
    1287             : 
    1288         102 :     if (strcmp(result, "OK") == 0)
    1289          80 :         return rettup;
    1290          22 :     if (strcmp(result, "SKIP") == 0)
    1291           2 :         return (HeapTuple) NULL;
    1292             : 
    1293             :     /************************************************************
    1294             :      * Otherwise, the return value should be a column name/value list
    1295             :      * specifying the modified tuple to return.
    1296             :      ************************************************************/
    1297          20 :     if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
    1298             :                                &result_Objc, &result_Objv) != TCL_OK)
    1299           0 :         ereport(ERROR,
    1300             :                 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    1301             :                  errmsg("could not parse trigger return value: %s",
    1302             :                         utf_u2e(Tcl_GetStringResult(interp)))));
    1303             : 
    1304             :     /* Convert function result to tuple */
    1305          20 :     rettup = pltcl_build_tuple_result(interp, result_Objv, result_Objc,
    1306             :                                       call_state);
    1307             : 
    1308          18 :     return rettup;
    1309             : }
    1310             : 
    1311             : /**********************************************************************
    1312             :  * pltcl_event_trigger_handler()    - Handler for event trigger calls
    1313             :  **********************************************************************/
    1314             : static void
    1315          20 : pltcl_event_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
    1316             :                             bool pltrusted)
    1317             : {
    1318             :     pltcl_proc_desc *prodesc;
    1319             :     Tcl_Interp *volatile interp;
    1320          20 :     EventTriggerData *tdata = (EventTriggerData *) fcinfo->context;
    1321             :     Tcl_Obj    *tcl_cmd;
    1322             :     int         tcl_rc;
    1323             : 
    1324             :     /* Connect to SPI manager */
    1325          20 :     SPI_connect();
    1326             : 
    1327             :     /* Find or compile the function */
    1328          20 :     prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
    1329             :                                      InvalidOid, true, pltrusted);
    1330             : 
    1331          20 :     call_state->prodesc = prodesc;
    1332          20 :     prodesc->fn_refcount++;
    1333             : 
    1334          20 :     interp = prodesc->interp_desc->interp;
    1335             : 
    1336             :     /* Create the tcl command and call the internal proc */
    1337          20 :     tcl_cmd = Tcl_NewObj();
    1338          20 :     Tcl_IncrRefCount(tcl_cmd);
    1339          20 :     Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1340          20 :                              Tcl_NewStringObj(prodesc->internal_proname, -1));
    1341          20 :     Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1342          20 :                              Tcl_NewStringObj(utf_e2u(tdata->event), -1));
    1343          20 :     Tcl_ListObjAppendElement(NULL, tcl_cmd,
    1344          20 :                              Tcl_NewStringObj(utf_e2u(GetCommandTagName(tdata->tag)),
    1345             :                                               -1));
    1346             : 
    1347          20 :     tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
    1348             : 
    1349             :     /* Release refcount to free tcl_cmd (and all subsidiary objects) */
    1350          20 :     Tcl_DecrRefCount(tcl_cmd);
    1351             : 
    1352             :     /* Check for errors reported by Tcl. */
    1353          20 :     if (tcl_rc != TCL_OK)
    1354           0 :         throw_tcl_error(interp, prodesc->user_proname);
    1355             : 
    1356          20 :     if (SPI_finish() != SPI_OK_FINISH)
    1357           0 :         elog(ERROR, "SPI_finish() failed");
    1358          20 : }
    1359             : 
    1360             : 
    1361             : /**********************************************************************
    1362             :  * throw_tcl_error  - ereport an error returned from the Tcl interpreter
    1363             :  *
    1364             :  * Caution: use this only to report errors returned by Tcl_EvalObjEx() or
    1365             :  * other variants of Tcl_Eval().  Other functions may not fill "errorInfo",
    1366             :  * so it could be unset or even contain details from some previous error.
    1367             :  **********************************************************************/
    1368             : static void
    1369          90 : throw_tcl_error(Tcl_Interp *interp, const char *proname)
    1370             : {
    1371             :     /*
    1372             :      * Caution is needed here because Tcl_GetVar could overwrite the
    1373             :      * interpreter result (even though it's not really supposed to), and we
    1374             :      * can't control the order of evaluation of ereport arguments. Hence, make
    1375             :      * real sure we have our own copy of the result string before invoking
    1376             :      * Tcl_GetVar.
    1377             :      */
    1378             :     char       *emsg;
    1379             :     char       *econtext;
    1380             :     int         emsglen;
    1381             : 
    1382          90 :     emsg = pstrdup(utf_u2e(Tcl_GetStringResult(interp)));
    1383          90 :     econtext = utf_u2e(Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY));
    1384             : 
    1385             :     /*
    1386             :      * Typically, the first line of errorInfo matches the primary error
    1387             :      * message (the interpreter result); don't print that twice if so.
    1388             :      */
    1389          90 :     emsglen = strlen(emsg);
    1390          90 :     if (strncmp(emsg, econtext, emsglen) == 0 &&
    1391          90 :         econtext[emsglen] == '\n')
    1392          90 :         econtext += emsglen + 1;
    1393             : 
    1394             :     /* Tcl likes to prefix the next line with some spaces, too */
    1395         450 :     while (*econtext == ' ')
    1396         360 :         econtext++;
    1397             : 
    1398             :     /* Note: proname will already contain quoting if any is needed */
    1399          90 :     ereport(ERROR,
    1400             :             (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    1401             :              errmsg("%s", emsg),
    1402             :              errcontext("%s\nin PL/Tcl function %s",
    1403             :                         econtext, proname)));
    1404             : }
    1405             : 
    1406             : 
    1407             : /**********************************************************************
    1408             :  * compile_pltcl_function   - compile (or hopefully just look up) function
    1409             :  *
    1410             :  * tgreloid is the OID of the relation when compiling a trigger, or zero
    1411             :  * (InvalidOid) when compiling a plain function.
    1412             :  **********************************************************************/
    1413             : static pltcl_proc_desc *
    1414         446 : compile_pltcl_function(Oid fn_oid, Oid tgreloid,
    1415             :                        bool is_event_trigger, bool pltrusted)
    1416             : {
    1417             :     HeapTuple   procTup;
    1418             :     Form_pg_proc procStruct;
    1419             :     pltcl_proc_key proc_key;
    1420             :     pltcl_proc_ptr *proc_ptr;
    1421             :     bool        found;
    1422             :     pltcl_proc_desc *prodesc;
    1423             :     pltcl_proc_desc *old_prodesc;
    1424         446 :     volatile MemoryContext proc_cxt = NULL;
    1425             :     Tcl_DString proc_internal_def;
    1426             :     Tcl_DString proc_internal_name;
    1427             :     Tcl_DString proc_internal_body;
    1428             : 
    1429             :     /* We'll need the pg_proc tuple in any case... */
    1430         446 :     procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
    1431         446 :     if (!HeapTupleIsValid(procTup))
    1432           0 :         elog(ERROR, "cache lookup failed for function %u", fn_oid);
    1433         446 :     procStruct = (Form_pg_proc) GETSTRUCT(procTup);
    1434             : 
    1435             :     /*
    1436             :      * Look up function in pltcl_proc_htab; if it's not there, create an entry
    1437             :      * and set the entry's proc_ptr to NULL.
    1438             :      */
    1439         446 :     proc_key.proc_id = fn_oid;
    1440         446 :     proc_key.is_trigger = OidIsValid(tgreloid);
    1441         446 :     proc_key.user_id = pltrusted ? GetUserId() : InvalidOid;
    1442             : 
    1443         446 :     proc_ptr = hash_search(pltcl_proc_htab, &proc_key,
    1444             :                            HASH_ENTER,
    1445             :                            &found);
    1446         446 :     if (!found)
    1447         120 :         proc_ptr->proc_ptr = NULL;
    1448             : 
    1449         446 :     prodesc = proc_ptr->proc_ptr;
    1450             : 
    1451             :     /************************************************************
    1452             :      * If it's present, must check whether it's still up to date.
    1453             :      * This is needed because CREATE OR REPLACE FUNCTION can modify the
    1454             :      * function's pg_proc entry without changing its OID.
    1455             :      ************************************************************/
    1456         446 :     if (prodesc != NULL &&
    1457         320 :         prodesc->internal_proname != NULL &&
    1458         320 :         prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
    1459         316 :         ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self))
    1460             :     {
    1461             :         /* It's still up-to-date, so we can use it */
    1462         316 :         ReleaseSysCache(procTup);
    1463         316 :         return prodesc;
    1464             :     }
    1465             : 
    1466             :     /************************************************************
    1467             :      * If we haven't found it in the hashtable, we analyze
    1468             :      * the functions arguments and returntype and store
    1469             :      * the in-/out-functions in the prodesc block and create
    1470             :      * a new hashtable entry for it.
    1471             :      *
    1472             :      * Then we load the procedure into the Tcl interpreter.
    1473             :      ************************************************************/
    1474         130 :     Tcl_DStringInit(&proc_internal_def);
    1475         130 :     Tcl_DStringInit(&proc_internal_name);
    1476         130 :     Tcl_DStringInit(&proc_internal_body);
    1477         130 :     PG_TRY();
    1478             :     {
    1479         130 :         bool        is_trigger = OidIsValid(tgreloid);
    1480             :         Tcl_CmdInfo cmdinfo;
    1481             :         const char *user_proname;
    1482             :         const char *internal_proname;
    1483             :         bool        need_underscore;
    1484             :         HeapTuple   typeTup;
    1485             :         Form_pg_type typeStruct;
    1486             :         char        proc_internal_args[33 * FUNC_MAX_ARGS];
    1487             :         Datum       prosrcdatum;
    1488             :         char       *proc_source;
    1489             :         char        buf[48];
    1490             :         pltcl_interp_desc *interp_desc;
    1491             :         Tcl_Interp *interp;
    1492             :         int         i;
    1493             :         int         tcl_rc;
    1494             :         MemoryContext oldcontext;
    1495             : 
    1496             :         /************************************************************
    1497             :          * Identify the interpreter to use for the function
    1498             :          ************************************************************/
    1499         130 :         interp_desc = pltcl_fetch_interp(procStruct->prolang, pltrusted);
    1500         124 :         interp = interp_desc->interp;
    1501             : 
    1502             :         /************************************************************
    1503             :          * If redefining the function, try to remove the old internal
    1504             :          * procedure from Tcl's namespace.  The point of this is partly to
    1505             :          * allow re-use of the same internal proc name, and partly to avoid
    1506             :          * leaking the Tcl procedure object if we end up not choosing the same
    1507             :          * name.  We assume that Tcl is smart enough to not physically delete
    1508             :          * the procedure object if it's currently being executed.
    1509             :          ************************************************************/
    1510         124 :         if (prodesc != NULL &&
    1511           4 :             prodesc->internal_proname != NULL)
    1512             :         {
    1513             :             /* We simply ignore any error */
    1514           4 :             (void) Tcl_DeleteCommand(interp, prodesc->internal_proname);
    1515             :             /* Don't do this more than once */
    1516           4 :             prodesc->internal_proname = NULL;
    1517             :         }
    1518             : 
    1519             :         /************************************************************
    1520             :          * Build the proc name we'll use in error messages.
    1521             :          ************************************************************/
    1522         124 :         user_proname = format_procedure(fn_oid);
    1523             : 
    1524             :         /************************************************************
    1525             :          * Build the internal proc name from the user_proname and/or OID.
    1526             :          * The internal name must be all-ASCII since we don't want to deal
    1527             :          * with encoding conversions.  We don't want to worry about Tcl
    1528             :          * quoting rules either, so use only the characters of the function
    1529             :          * name that are ASCII alphanumerics, plus underscores to separate
    1530             :          * function name and arguments.  If what we end up with isn't
    1531             :          * unique (that is, it matches some existing Tcl command name),
    1532             :          * append the function OID (perhaps repeatedly) so that it is unique.
    1533             :          ************************************************************/
    1534             : 
    1535             :         /* For historical reasons, use a function-type-specific prefix */
    1536         124 :         if (is_event_trigger)
    1537           2 :             Tcl_DStringAppend(&proc_internal_name,
    1538             :                               "__PLTcl_evttrigger_", -1);
    1539         122 :         else if (is_trigger)
    1540          16 :             Tcl_DStringAppend(&proc_internal_name,
    1541             :                               "__PLTcl_trigger_", -1);
    1542             :         else
    1543         106 :             Tcl_DStringAppend(&proc_internal_name,
    1544             :                               "__PLTcl_proc_", -1);
    1545             :         /* Now add what we can from the user_proname */
    1546         124 :         need_underscore = false;
    1547        2830 :         for (const char *ptr = user_proname; *ptr; ptr++)
    1548             :         {
    1549        2706 :             if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    1550             :                        "abcdefghijklmnopqrstuvwxyz"
    1551        2706 :                        "0123456789_", *ptr) != NULL)
    1552             :             {
    1553             :                 /* Done this way to avoid adding a trailing underscore */
    1554        2422 :                 if (need_underscore)
    1555             :                 {
    1556          96 :                     Tcl_DStringAppend(&proc_internal_name, "_", 1);
    1557          96 :                     need_underscore = false;
    1558             :                 }
    1559        2422 :                 Tcl_DStringAppend(&proc_internal_name, ptr, 1);
    1560             :             }
    1561         284 :             else if (strchr("(, ", *ptr) != NULL)
    1562         152 :                 need_underscore = true;
    1563             :         }
    1564             :         /* If this name already exists, append fn_oid; repeat as needed */
    1565         250 :         while (Tcl_GetCommandInfo(interp,
    1566         126 :                                   Tcl_DStringValue(&proc_internal_name),
    1567             :                                   &cmdinfo))
    1568             :         {
    1569           2 :             snprintf(buf, sizeof(buf), "_%u", fn_oid);
    1570           2 :             Tcl_DStringAppend(&proc_internal_name, buf, -1);
    1571             :         }
    1572         124 :         internal_proname = Tcl_DStringValue(&proc_internal_name);
    1573             : 
    1574             :         /************************************************************
    1575             :          * Allocate a context that will hold all PG data for the procedure.
    1576             :          ************************************************************/
    1577         124 :         proc_cxt = AllocSetContextCreate(TopMemoryContext,
    1578             :                                          "PL/Tcl function",
    1579             :                                          ALLOCSET_SMALL_SIZES);
    1580             : 
    1581             :         /************************************************************
    1582             :          * Allocate and fill a new procedure description block.
    1583             :          * struct prodesc and subsidiary data must all live in proc_cxt.
    1584             :          ************************************************************/
    1585         124 :         oldcontext = MemoryContextSwitchTo(proc_cxt);
    1586         124 :         prodesc = (pltcl_proc_desc *) palloc0(sizeof(pltcl_proc_desc));
    1587         124 :         prodesc->user_proname = pstrdup(user_proname);
    1588         124 :         MemoryContextSetIdentifier(proc_cxt, prodesc->user_proname);
    1589         124 :         prodesc->internal_proname = pstrdup(internal_proname);
    1590         124 :         prodesc->fn_cxt = proc_cxt;
    1591         124 :         prodesc->fn_refcount = 0;
    1592         124 :         prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
    1593         124 :         prodesc->fn_tid = procTup->t_self;
    1594         124 :         prodesc->nargs = procStruct->pronargs;
    1595         124 :         prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
    1596         124 :         prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
    1597         124 :         MemoryContextSwitchTo(oldcontext);
    1598             : 
    1599             :         /* Remember if function is STABLE/IMMUTABLE */
    1600         124 :         prodesc->fn_readonly =
    1601         124 :             (procStruct->provolatile != PROVOLATILE_VOLATILE);
    1602             :         /* And whether it is trusted */
    1603         124 :         prodesc->lanpltrusted = pltrusted;
    1604             :         /* Save the associated interpreter, too */
    1605         124 :         prodesc->interp_desc = interp_desc;
    1606             : 
    1607             :         /************************************************************
    1608             :          * Get the required information for input conversion of the
    1609             :          * return value.
    1610             :          ************************************************************/
    1611         124 :         if (!is_trigger && !is_event_trigger)
    1612             :         {
    1613         106 :             Oid         rettype = procStruct->prorettype;
    1614             : 
    1615         106 :             typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
    1616         106 :             if (!HeapTupleIsValid(typeTup))
    1617           0 :                 elog(ERROR, "cache lookup failed for type %u", rettype);
    1618         106 :             typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
    1619             : 
    1620             :             /* Disallow pseudotype result, except VOID and RECORD */
    1621         106 :             if (typeStruct->typtype == TYPTYPE_PSEUDO)
    1622             :             {
    1623          48 :                 if (rettype == VOIDOID ||
    1624             :                     rettype == RECORDOID)
    1625             :                      /* okay */ ;
    1626           0 :                 else if (rettype == TRIGGEROID ||
    1627             :                          rettype == EVENT_TRIGGEROID)
    1628           0 :                     ereport(ERROR,
    1629             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1630             :                              errmsg("trigger functions can only be called as triggers")));
    1631             :                 else
    1632           0 :                     ereport(ERROR,
    1633             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1634             :                              errmsg("PL/Tcl functions cannot return type %s",
    1635             :                                     format_type_be(rettype))));
    1636             :             }
    1637             : 
    1638         106 :             prodesc->result_typid = rettype;
    1639         106 :             fmgr_info_cxt(typeStruct->typinput,
    1640             :                           &(prodesc->result_in_func),
    1641             :                           proc_cxt);
    1642         106 :             prodesc->result_typioparam = getTypeIOParam(typeTup);
    1643             : 
    1644         106 :             prodesc->fn_retisset = procStruct->proretset;
    1645         106 :             prodesc->fn_retistuple = type_is_rowtype(rettype);
    1646         106 :             prodesc->fn_retisdomain = (typeStruct->typtype == TYPTYPE_DOMAIN);
    1647         106 :             prodesc->domain_info = NULL;
    1648             : 
    1649         106 :             ReleaseSysCache(typeTup);
    1650             :         }
    1651             : 
    1652             :         /************************************************************
    1653             :          * Get the required information for output conversion
    1654             :          * of all procedure arguments, and set up argument naming info.
    1655             :          ************************************************************/
    1656         124 :         if (!is_trigger && !is_event_trigger)
    1657             :         {
    1658         106 :             proc_internal_args[0] = '\0';
    1659         202 :             for (i = 0; i < prodesc->nargs; i++)
    1660             :             {
    1661          96 :                 Oid         argtype = procStruct->proargtypes.values[i];
    1662             : 
    1663          96 :                 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
    1664          96 :                 if (!HeapTupleIsValid(typeTup))
    1665           0 :                     elog(ERROR, "cache lookup failed for type %u", argtype);
    1666          96 :                 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
    1667             : 
    1668             :                 /* Disallow pseudotype argument, except RECORD */
    1669          96 :                 if (typeStruct->typtype == TYPTYPE_PSEUDO &&
    1670             :                     argtype != RECORDOID)
    1671           0 :                     ereport(ERROR,
    1672             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1673             :                              errmsg("PL/Tcl functions cannot accept type %s",
    1674             :                                     format_type_be(argtype))));
    1675             : 
    1676          96 :                 if (type_is_rowtype(argtype))
    1677             :                 {
    1678           8 :                     prodesc->arg_is_rowtype[i] = true;
    1679           8 :                     snprintf(buf, sizeof(buf), "__PLTcl_Tup_%d", i + 1);
    1680             :                 }
    1681             :                 else
    1682             :                 {
    1683          88 :                     prodesc->arg_is_rowtype[i] = false;
    1684          88 :                     fmgr_info_cxt(typeStruct->typoutput,
    1685          88 :                                   &(prodesc->arg_out_func[i]),
    1686             :                                   proc_cxt);
    1687          88 :                     snprintf(buf, sizeof(buf), "%d", i + 1);
    1688             :                 }
    1689             : 
    1690          96 :                 if (i > 0)
    1691          28 :                     strcat(proc_internal_args, " ");
    1692          96 :                 strcat(proc_internal_args, buf);
    1693             : 
    1694          96 :                 ReleaseSysCache(typeTup);
    1695             :             }
    1696             :         }
    1697          18 :         else if (is_trigger)
    1698             :         {
    1699             :             /* trigger procedure has fixed args */
    1700          16 :             strcpy(proc_internal_args,
    1701             :                    "TG_name TG_relid TG_table_name TG_table_schema TG_relatts TG_when TG_level TG_op __PLTcl_Tup_NEW __PLTcl_Tup_OLD args");
    1702             :         }
    1703           2 :         else if (is_event_trigger)
    1704             :         {
    1705             :             /* event trigger procedure has fixed args */
    1706           2 :             strcpy(proc_internal_args, "TG_event TG_tag");
    1707             :         }
    1708             : 
    1709             :         /************************************************************
    1710             :          * Create the tcl command to define the internal
    1711             :          * procedure
    1712             :          *
    1713             :          * Leave this code as DString - performance is not critical here,
    1714             :          * and we don't want to duplicate the knowledge of the Tcl quoting
    1715             :          * rules that's embedded in Tcl_DStringAppendElement.
    1716             :          ************************************************************/
    1717         124 :         Tcl_DStringAppendElement(&proc_internal_def, "proc");
    1718         124 :         Tcl_DStringAppendElement(&proc_internal_def, internal_proname);
    1719         124 :         Tcl_DStringAppendElement(&proc_internal_def, proc_internal_args);
    1720             : 
    1721             :         /************************************************************
    1722             :          * prefix procedure body with
    1723             :          * upvar #0 <internal_proname> GD
    1724             :          * and with appropriate setting of arguments
    1725             :          ************************************************************/
    1726         124 :         Tcl_DStringAppend(&proc_internal_body, "upvar #0 ", -1);
    1727         124 :         Tcl_DStringAppend(&proc_internal_body, internal_proname, -1);
    1728         124 :         Tcl_DStringAppend(&proc_internal_body, " GD\n", -1);
    1729         124 :         if (is_trigger)
    1730             :         {
    1731          16 :             Tcl_DStringAppend(&proc_internal_body,
    1732             :                               "array set NEW $__PLTcl_Tup_NEW\n", -1);
    1733          16 :             Tcl_DStringAppend(&proc_internal_body,
    1734             :                               "array set OLD $__PLTcl_Tup_OLD\n", -1);
    1735          16 :             Tcl_DStringAppend(&proc_internal_body,
    1736             :                               "set i 0\n"
    1737             :                               "set v 0\n"
    1738             :                               "foreach v $args {\n"
    1739             :                               "  incr i\n"
    1740             :                               "  set $i $v\n"
    1741             :                               "}\n"
    1742             :                               "unset i v\n\n", -1);
    1743             :         }
    1744         108 :         else if (is_event_trigger)
    1745             :         {
    1746             :             /* no argument support for event triggers */
    1747             :         }
    1748             :         else
    1749             :         {
    1750         202 :             for (i = 0; i < prodesc->nargs; i++)
    1751             :             {
    1752          96 :                 if (prodesc->arg_is_rowtype[i])
    1753             :                 {
    1754           8 :                     snprintf(buf, sizeof(buf),
    1755             :                              "array set %d $__PLTcl_Tup_%d\n",
    1756             :                              i + 1, i + 1);
    1757           8 :                     Tcl_DStringAppend(&proc_internal_body, buf, -1);
    1758             :                 }
    1759             :             }
    1760             :         }
    1761             : 
    1762             :         /************************************************************
    1763             :          * Add user's function definition to proc body
    1764             :          ************************************************************/
    1765         124 :         prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup,
    1766             :                                              Anum_pg_proc_prosrc);
    1767         124 :         proc_source = TextDatumGetCString(prosrcdatum);
    1768         124 :         UTF_BEGIN;
    1769         124 :         Tcl_DStringAppend(&proc_internal_body, UTF_E2U(proc_source), -1);
    1770         124 :         UTF_END;
    1771         124 :         pfree(proc_source);
    1772         124 :         Tcl_DStringAppendElement(&proc_internal_def,
    1773         124 :                                  Tcl_DStringValue(&proc_internal_body));
    1774             : 
    1775             :         /************************************************************
    1776             :          * Create the procedure in the interpreter
    1777             :          ************************************************************/
    1778         248 :         tcl_rc = Tcl_EvalEx(interp,
    1779         124 :                             Tcl_DStringValue(&proc_internal_def),
    1780             :                             Tcl_DStringLength(&proc_internal_def),
    1781             :                             TCL_EVAL_GLOBAL);
    1782         124 :         if (tcl_rc != TCL_OK)
    1783           0 :             ereport(ERROR,
    1784             :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    1785             :                      errmsg("could not create internal procedure \"%s\": %s",
    1786             :                             internal_proname,
    1787             :                             utf_u2e(Tcl_GetStringResult(interp)))));
    1788             :     }
    1789           6 :     PG_CATCH();
    1790             :     {
    1791             :         /*
    1792             :          * If we failed anywhere above, clean up whatever got allocated.  It
    1793             :          * should all be in the proc_cxt, except for the DStrings.
    1794             :          */
    1795           6 :         if (proc_cxt)
    1796           0 :             MemoryContextDelete(proc_cxt);
    1797           6 :         Tcl_DStringFree(&proc_internal_def);
    1798           6 :         Tcl_DStringFree(&proc_internal_name);
    1799           6 :         Tcl_DStringFree(&proc_internal_body);
    1800           6 :         PG_RE_THROW();
    1801             :     }
    1802         124 :     PG_END_TRY();
    1803             : 
    1804             :     /*
    1805             :      * Install the new proc description block in the hashtable, incrementing
    1806             :      * its refcount (the hashtable link counts as a reference).  Then, if
    1807             :      * there was a previous definition of the function, decrement that one's
    1808             :      * refcount, and delete it if no longer referenced.  The order of
    1809             :      * operations here is important: if something goes wrong during the
    1810             :      * MemoryContextDelete, leaking some memory for the old definition is OK,
    1811             :      * but we don't want to corrupt the live hashtable entry.  (Likewise,
    1812             :      * freeing the DStrings is pretty low priority if that happens.)
    1813             :      */
    1814         124 :     old_prodesc = proc_ptr->proc_ptr;
    1815             : 
    1816         124 :     proc_ptr->proc_ptr = prodesc;
    1817         124 :     prodesc->fn_refcount++;
    1818             : 
    1819         124 :     if (old_prodesc != NULL)
    1820             :     {
    1821             :         Assert(old_prodesc->fn_refcount > 0);
    1822           4 :         if (--old_prodesc->fn_refcount == 0)
    1823           2 :             MemoryContextDelete(old_prodesc->fn_cxt);
    1824             :     }
    1825             : 
    1826         124 :     Tcl_DStringFree(&proc_internal_def);
    1827         124 :     Tcl_DStringFree(&proc_internal_name);
    1828         124 :     Tcl_DStringFree(&proc_internal_body);
    1829             : 
    1830         124 :     ReleaseSysCache(procTup);
    1831             : 
    1832         124 :     return prodesc;
    1833             : }
    1834             : 
    1835             : 
    1836             : /**********************************************************************
    1837             :  * pltcl_elog()     - elog() support for PLTcl
    1838             :  **********************************************************************/
    1839             : static int
    1840         532 : pltcl_elog(ClientData cdata, Tcl_Interp *interp,
    1841             :            int objc, Tcl_Obj *const objv[])
    1842             : {
    1843             :     volatile int level;
    1844             :     MemoryContext oldcontext;
    1845             :     int         priIndex;
    1846             : 
    1847             :     static const char *logpriorities[] = {
    1848             :         "DEBUG", "LOG", "INFO", "NOTICE",
    1849             :         "WARNING", "ERROR", "FATAL", (const char *) NULL
    1850             :     };
    1851             : 
    1852             :     static const int loglevels[] = {
    1853             :         DEBUG2, LOG, INFO, NOTICE,
    1854             :         WARNING, ERROR, FATAL
    1855             :     };
    1856             : 
    1857         532 :     if (objc != 3)
    1858             :     {
    1859           2 :         Tcl_WrongNumArgs(interp, 1, objv, "level msg");
    1860           2 :         return TCL_ERROR;
    1861             :     }
    1862             : 
    1863         530 :     if (Tcl_GetIndexFromObj(interp, objv[1], logpriorities, "priority",
    1864             :                             TCL_EXACT, &priIndex) != TCL_OK)
    1865           2 :         return TCL_ERROR;
    1866             : 
    1867         528 :     level = loglevels[priIndex];
    1868             : 
    1869         528 :     if (level == ERROR)
    1870             :     {
    1871             :         /*
    1872             :          * We just pass the error back to Tcl.  If it's not caught, it'll
    1873             :          * eventually get converted to a PG error when we reach the call
    1874             :          * handler.
    1875             :          */
    1876          12 :         Tcl_SetObjResult(interp, objv[2]);
    1877          12 :         return TCL_ERROR;
    1878             :     }
    1879             : 
    1880             :     /*
    1881             :      * For non-error messages, just pass 'em to ereport().  We do not expect
    1882             :      * that this will fail, but just on the off chance it does, report the
    1883             :      * error back to Tcl.  Note we are assuming that ereport() can't have any
    1884             :      * internal failures that are so bad as to require a transaction abort.
    1885             :      *
    1886             :      * This path is also used for FATAL errors, which aren't going to come
    1887             :      * back to us at all.
    1888             :      */
    1889         516 :     oldcontext = CurrentMemoryContext;
    1890         516 :     PG_TRY();
    1891             :     {
    1892         516 :         UTF_BEGIN;
    1893         516 :         ereport(level,
    1894             :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    1895             :                  errmsg("%s", UTF_U2E(Tcl_GetString(objv[2])))));
    1896         516 :         UTF_END;
    1897             :     }
    1898           0 :     PG_CATCH();
    1899             :     {
    1900             :         ErrorData  *edata;
    1901             : 
    1902             :         /* Must reset elog.c's state */
    1903           0 :         MemoryContextSwitchTo(oldcontext);
    1904           0 :         edata = CopyErrorData();
    1905           0 :         FlushErrorState();
    1906             : 
    1907             :         /* Pass the error data to Tcl */
    1908           0 :         pltcl_construct_errorCode(interp, edata);
    1909           0 :         UTF_BEGIN;
    1910           0 :         Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
    1911           0 :         UTF_END;
    1912           0 :         FreeErrorData(edata);
    1913             : 
    1914           0 :         return TCL_ERROR;
    1915             :     }
    1916         516 :     PG_END_TRY();
    1917             : 
    1918         516 :     return TCL_OK;
    1919             : }
    1920             : 
    1921             : 
    1922             : /**********************************************************************
    1923             :  * pltcl_construct_errorCode()      - construct a Tcl errorCode
    1924             :  *      list with detailed information from the PostgreSQL server
    1925             :  **********************************************************************/
    1926             : static void
    1927          36 : pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
    1928             : {
    1929          36 :     Tcl_Obj    *obj = Tcl_NewObj();
    1930             : 
    1931          36 :     Tcl_ListObjAppendElement(interp, obj,
    1932             :                              Tcl_NewStringObj("POSTGRES", -1));
    1933          36 :     Tcl_ListObjAppendElement(interp, obj,
    1934             :                              Tcl_NewStringObj(PG_VERSION, -1));
    1935          36 :     Tcl_ListObjAppendElement(interp, obj,
    1936             :                              Tcl_NewStringObj("SQLSTATE", -1));
    1937          36 :     Tcl_ListObjAppendElement(interp, obj,
    1938          36 :                              Tcl_NewStringObj(unpack_sql_state(edata->sqlerrcode), -1));
    1939          36 :     Tcl_ListObjAppendElement(interp, obj,
    1940             :                              Tcl_NewStringObj("condition", -1));
    1941          36 :     Tcl_ListObjAppendElement(interp, obj,
    1942             :                              Tcl_NewStringObj(pltcl_get_condition_name(edata->sqlerrcode), -1));
    1943          36 :     Tcl_ListObjAppendElement(interp, obj,
    1944             :                              Tcl_NewStringObj("message", -1));
    1945          36 :     UTF_BEGIN;
    1946          36 :     Tcl_ListObjAppendElement(interp, obj,
    1947          36 :                              Tcl_NewStringObj(UTF_E2U(edata->message), -1));
    1948          36 :     UTF_END;
    1949          36 :     if (edata->detail)
    1950             :     {
    1951           6 :         Tcl_ListObjAppendElement(interp, obj,
    1952             :                                  Tcl_NewStringObj("detail", -1));
    1953           6 :         UTF_BEGIN;
    1954           6 :         Tcl_ListObjAppendElement(interp, obj,
    1955           6 :                                  Tcl_NewStringObj(UTF_E2U(edata->detail), -1));
    1956           6 :         UTF_END;
    1957             :     }
    1958          36 :     if (edata->hint)
    1959             :     {
    1960           2 :         Tcl_ListObjAppendElement(interp, obj,
    1961             :                                  Tcl_NewStringObj("hint", -1));
    1962           2 :         UTF_BEGIN;
    1963           2 :         Tcl_ListObjAppendElement(interp, obj,
    1964           2 :                                  Tcl_NewStringObj(UTF_E2U(edata->hint), -1));
    1965           2 :         UTF_END;
    1966             :     }
    1967          36 :     if (edata->context)
    1968             :     {
    1969          18 :         Tcl_ListObjAppendElement(interp, obj,
    1970             :                                  Tcl_NewStringObj("context", -1));
    1971          18 :         UTF_BEGIN;
    1972          18 :         Tcl_ListObjAppendElement(interp, obj,
    1973          18 :                                  Tcl_NewStringObj(UTF_E2U(edata->context), -1));
    1974          18 :         UTF_END;
    1975             :     }
    1976          36 :     if (edata->schema_name)
    1977             :     {
    1978           6 :         Tcl_ListObjAppendElement(interp, obj,
    1979             :                                  Tcl_NewStringObj("schema", -1));
    1980           6 :         UTF_BEGIN;
    1981           6 :         Tcl_ListObjAppendElement(interp, obj,
    1982           6 :                                  Tcl_NewStringObj(UTF_E2U(edata->schema_name), -1));
    1983           6 :         UTF_END;
    1984             :     }
    1985          36 :     if (edata->table_name)
    1986             :     {
    1987           6 :         Tcl_ListObjAppendElement(interp, obj,
    1988             :                                  Tcl_NewStringObj("table", -1));
    1989           6 :         UTF_BEGIN;
    1990           6 :         Tcl_ListObjAppendElement(interp, obj,
    1991           6 :                                  Tcl_NewStringObj(UTF_E2U(edata->table_name), -1));
    1992           6 :         UTF_END;
    1993             :     }
    1994          36 :     if (edata->column_name)
    1995             :     {
    1996           2 :         Tcl_ListObjAppendElement(interp, obj,
    1997             :                                  Tcl_NewStringObj("column", -1));
    1998           2 :         UTF_BEGIN;
    1999           2 :         Tcl_ListObjAppendElement(interp, obj,
    2000           2 :                                  Tcl_NewStringObj(UTF_E2U(edata->column_name), -1));
    2001           2 :         UTF_END;
    2002             :     }
    2003          36 :     if (edata->datatype_name)
    2004             :     {
    2005           2 :         Tcl_ListObjAppendElement(interp, obj,
    2006             :                                  Tcl_NewStringObj("datatype", -1));
    2007           2 :         UTF_BEGIN;
    2008           2 :         Tcl_ListObjAppendElement(interp, obj,
    2009           2 :                                  Tcl_NewStringObj(UTF_E2U(edata->datatype_name), -1));
    2010           2 :         UTF_END;
    2011             :     }
    2012          36 :     if (edata->constraint_name)
    2013             :     {
    2014           6 :         Tcl_ListObjAppendElement(interp, obj,
    2015             :                                  Tcl_NewStringObj("constraint", -1));
    2016           6 :         UTF_BEGIN;
    2017           6 :         Tcl_ListObjAppendElement(interp, obj,
    2018           6 :                                  Tcl_NewStringObj(UTF_E2U(edata->constraint_name), -1));
    2019           6 :         UTF_END;
    2020             :     }
    2021             :     /* cursorpos is never interesting here; report internal query/pos */
    2022          36 :     if (edata->internalquery)
    2023             :     {
    2024           8 :         Tcl_ListObjAppendElement(interp, obj,
    2025             :                                  Tcl_NewStringObj("statement", -1));
    2026           8 :         UTF_BEGIN;
    2027           8 :         Tcl_ListObjAppendElement(interp, obj,
    2028           8 :                                  Tcl_NewStringObj(UTF_E2U(edata->internalquery), -1));
    2029           8 :         UTF_END;
    2030             :     }
    2031          36 :     if (edata->internalpos > 0)
    2032             :     {
    2033           8 :         Tcl_ListObjAppendElement(interp, obj,
    2034             :                                  Tcl_NewStringObj("cursor_position", -1));
    2035           8 :         Tcl_ListObjAppendElement(interp, obj,
    2036             :                                  Tcl_NewIntObj(edata->internalpos));
    2037             :     }
    2038          36 :     if (edata->filename)
    2039             :     {
    2040          36 :         Tcl_ListObjAppendElement(interp, obj,
    2041             :                                  Tcl_NewStringObj("filename", -1));
    2042          36 :         UTF_BEGIN;
    2043          36 :         Tcl_ListObjAppendElement(interp, obj,
    2044          36 :                                  Tcl_NewStringObj(UTF_E2U(edata->filename), -1));
    2045          36 :         UTF_END;
    2046             :     }
    2047          36 :     if (edata->lineno > 0)
    2048             :     {
    2049          36 :         Tcl_ListObjAppendElement(interp, obj,
    2050             :                                  Tcl_NewStringObj("lineno", -1));
    2051          36 :         Tcl_ListObjAppendElement(interp, obj,
    2052             :                                  Tcl_NewIntObj(edata->lineno));
    2053             :     }
    2054          36 :     if (edata->funcname)
    2055             :     {
    2056          36 :         Tcl_ListObjAppendElement(interp, obj,
    2057             :                                  Tcl_NewStringObj("funcname", -1));
    2058          36 :         UTF_BEGIN;
    2059          36 :         Tcl_ListObjAppendElement(interp, obj,
    2060          36 :                                  Tcl_NewStringObj(UTF_E2U(edata->funcname), -1));
    2061          36 :         UTF_END;
    2062             :     }
    2063             : 
    2064          36 :     Tcl_SetObjErrorCode(interp, obj);
    2065          36 : }
    2066             : 
    2067             : 
    2068             : /**********************************************************************
    2069             :  * pltcl_get_condition_name()   - find name for SQLSTATE
    2070             :  **********************************************************************/
    2071             : static const char *
    2072          36 : pltcl_get_condition_name(int sqlstate)
    2073             : {
    2074             :     int         i;
    2075             : 
    2076        4558 :     for (i = 0; exception_name_map[i].label != NULL; i++)
    2077             :     {
    2078        4558 :         if (exception_name_map[i].sqlerrstate == sqlstate)
    2079          36 :             return exception_name_map[i].label;
    2080             :     }
    2081           0 :     return "unrecognized_sqlstate";
    2082             : }
    2083             : 
    2084             : 
    2085             : /**********************************************************************
    2086             :  * pltcl_quote()    - quote literal strings that are to
    2087             :  *            be used in SPI_execute query strings
    2088             :  **********************************************************************/
    2089             : static int
    2090          22 : pltcl_quote(ClientData cdata, Tcl_Interp *interp,
    2091             :             int objc, Tcl_Obj *const objv[])
    2092             : {
    2093             :     char       *tmp;
    2094             :     const char *cp1;
    2095             :     char       *cp2;
    2096             :     Tcl_Size    length;
    2097             : 
    2098             :     /************************************************************
    2099             :      * Check call syntax
    2100             :      ************************************************************/
    2101          22 :     if (objc != 2)
    2102             :     {
    2103           2 :         Tcl_WrongNumArgs(interp, 1, objv, "string");
    2104           2 :         return TCL_ERROR;
    2105             :     }
    2106             : 
    2107             :     /************************************************************
    2108             :      * Allocate space for the maximum the string can
    2109             :      * grow to and initialize pointers
    2110             :      ************************************************************/
    2111          20 :     cp1 = Tcl_GetStringFromObj(objv[1], &length);
    2112          20 :     tmp = palloc(length * 2 + 1);
    2113          20 :     cp2 = tmp;
    2114             : 
    2115             :     /************************************************************
    2116             :      * Walk through string and double every quote and backslash
    2117             :      ************************************************************/
    2118         112 :     while (*cp1)
    2119             :     {
    2120          92 :         if (*cp1 == '\'')
    2121           2 :             *cp2++ = '\'';
    2122             :         else
    2123             :         {
    2124          90 :             if (*cp1 == '\\')
    2125           2 :                 *cp2++ = '\\';
    2126             :         }
    2127          92 :         *cp2++ = *cp1++;
    2128             :     }
    2129             : 
    2130             :     /************************************************************
    2131             :      * Terminate the string and set it as result
    2132             :      ************************************************************/
    2133          20 :     *cp2 = '\0';
    2134          20 :     Tcl_SetObjResult(interp, Tcl_NewStringObj(tmp, -1));
    2135          20 :     pfree(tmp);
    2136          20 :     return TCL_OK;
    2137             : }
    2138             : 
    2139             : 
    2140             : /**********************************************************************
    2141             :  * pltcl_argisnull()    - determine if a specific argument is NULL
    2142             :  **********************************************************************/
    2143             : static int
    2144          14 : pltcl_argisnull(ClientData cdata, Tcl_Interp *interp,
    2145             :                 int objc, Tcl_Obj *const objv[])
    2146             : {
    2147             :     int         argno;
    2148          14 :     FunctionCallInfo fcinfo = pltcl_current_call_state->fcinfo;
    2149             : 
    2150             :     /************************************************************
    2151             :      * Check call syntax
    2152             :      ************************************************************/
    2153          14 :     if (objc != 2)
    2154             :     {
    2155           2 :         Tcl_WrongNumArgs(interp, 1, objv, "argno");
    2156           2 :         return TCL_ERROR;
    2157             :     }
    2158             : 
    2159             :     /************************************************************
    2160             :      * Check that we're called as a normal function
    2161             :      ************************************************************/
    2162          12 :     if (fcinfo == NULL)
    2163             :     {
    2164           2 :         Tcl_SetObjResult(interp,
    2165             :                          Tcl_NewStringObj("argisnull cannot be used in triggers", -1));
    2166           2 :         return TCL_ERROR;
    2167             :     }
    2168             : 
    2169             :     /************************************************************
    2170             :      * Get the argument number
    2171             :      ************************************************************/
    2172          10 :     if (Tcl_GetIntFromObj(interp, objv[1], &argno) != TCL_OK)
    2173           2 :         return TCL_ERROR;
    2174             : 
    2175             :     /************************************************************
    2176             :      * Check that the argno is valid
    2177             :      ************************************************************/
    2178           8 :     argno--;
    2179           8 :     if (argno < 0 || argno >= fcinfo->nargs)
    2180             :     {
    2181           2 :         Tcl_SetObjResult(interp,
    2182             :                          Tcl_NewStringObj("argno out of range", -1));
    2183           2 :         return TCL_ERROR;
    2184             :     }
    2185             : 
    2186             :     /************************************************************
    2187             :      * Get the requested NULL state
    2188             :      ************************************************************/
    2189           6 :     Tcl_SetObjResult(interp, Tcl_NewBooleanObj(PG_ARGISNULL(argno)));
    2190           6 :     return TCL_OK;
    2191             : }
    2192             : 
    2193             : 
    2194             : /**********************************************************************
    2195             :  * pltcl_returnnull()   - Cause a NULL return from the current function
    2196             :  **********************************************************************/
    2197             : static int
    2198           6 : pltcl_returnnull(ClientData cdata, Tcl_Interp *interp,
    2199             :                  int objc, Tcl_Obj *const objv[])
    2200             : {
    2201           6 :     FunctionCallInfo fcinfo = pltcl_current_call_state->fcinfo;
    2202             : 
    2203             :     /************************************************************
    2204             :      * Check call syntax
    2205             :      ************************************************************/
    2206           6 :     if (objc != 1)
    2207             :     {
    2208           2 :         Tcl_WrongNumArgs(interp, 1, objv, "");
    2209           2 :         return TCL_ERROR;
    2210             :     }
    2211             : 
    2212             :     /************************************************************
    2213             :      * Check that we're called as a normal function
    2214             :      ************************************************************/
    2215           4 :     if (fcinfo == NULL)
    2216             :     {
    2217           2 :         Tcl_SetObjResult(interp,
    2218             :                          Tcl_NewStringObj("return_null cannot be used in triggers", -1));
    2219           2 :         return TCL_ERROR;
    2220             :     }
    2221             : 
    2222             :     /************************************************************
    2223             :      * Set the NULL return flag and cause Tcl to return from the
    2224             :      * procedure.
    2225             :      ************************************************************/
    2226           2 :     fcinfo->isnull = true;
    2227             : 
    2228           2 :     return TCL_RETURN;
    2229             : }
    2230             : 
    2231             : 
    2232             : /**********************************************************************
    2233             :  * pltcl_returnnext()   - Add a row to the result tuplestore in a SRF.
    2234             :  **********************************************************************/
    2235             : static int
    2236          36 : pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
    2237             :                  int objc, Tcl_Obj *const objv[])
    2238             : {
    2239          36 :     pltcl_call_state *call_state = pltcl_current_call_state;
    2240          36 :     FunctionCallInfo fcinfo = call_state->fcinfo;
    2241          36 :     pltcl_proc_desc *prodesc = call_state->prodesc;
    2242          36 :     MemoryContext oldcontext = CurrentMemoryContext;
    2243          36 :     ResourceOwner oldowner = CurrentResourceOwner;
    2244          36 :     volatile int result = TCL_OK;
    2245             : 
    2246             :     /*
    2247             :      * Check that we're called as a set-returning function
    2248             :      */
    2249          36 :     if (fcinfo == NULL)
    2250             :     {
    2251           0 :         Tcl_SetObjResult(interp,
    2252             :                          Tcl_NewStringObj("return_next cannot be used in triggers", -1));
    2253           0 :         return TCL_ERROR;
    2254             :     }
    2255             : 
    2256          36 :     if (!prodesc->fn_retisset)
    2257             :     {
    2258           2 :         Tcl_SetObjResult(interp,
    2259             :                          Tcl_NewStringObj("return_next cannot be used in non-set-returning functions", -1));
    2260           2 :         return TCL_ERROR;
    2261             :     }
    2262             : 
    2263             :     /*
    2264             :      * Check call syntax
    2265             :      */
    2266          34 :     if (objc != 2)
    2267             :     {
    2268           0 :         Tcl_WrongNumArgs(interp, 1, objv, "result");
    2269           0 :         return TCL_ERROR;
    2270             :     }
    2271             : 
    2272             :     /*
    2273             :      * The rest might throw elog(ERROR), so must run in a subtransaction.
    2274             :      *
    2275             :      * A small advantage of using a subtransaction is that it provides a
    2276             :      * short-lived memory context for free, so we needn't worry about leaking
    2277             :      * memory here.  To use that context, call BeginInternalSubTransaction
    2278             :      * directly instead of going through pltcl_subtrans_begin.
    2279             :      */
    2280          34 :     BeginInternalSubTransaction(NULL);
    2281          34 :     PG_TRY();
    2282             :     {
    2283             :         /* Set up tuple store if first output row */
    2284          34 :         if (call_state->tuple_store == NULL)
    2285          10 :             pltcl_init_tuple_store(call_state);
    2286             : 
    2287          34 :         if (prodesc->fn_retistuple)
    2288             :         {
    2289             :             Tcl_Obj   **rowObjv;
    2290             :             Tcl_Size    rowObjc;
    2291             : 
    2292             :             /* result should be a list, so break it down */
    2293          14 :             if (Tcl_ListObjGetElements(interp, objv[1], &rowObjc, &rowObjv) == TCL_ERROR)
    2294           0 :                 result = TCL_ERROR;
    2295             :             else
    2296             :             {
    2297             :                 HeapTuple   tuple;
    2298             : 
    2299          14 :                 tuple = pltcl_build_tuple_result(interp, rowObjv, rowObjc,
    2300             :                                                  call_state);
    2301          10 :                 tuplestore_puttuple(call_state->tuple_store, tuple);
    2302             :             }
    2303             :         }
    2304             :         else
    2305             :         {
    2306             :             Datum       retval;
    2307          20 :             bool        isNull = false;
    2308             : 
    2309             :             /* for paranoia's sake, check that tupdesc has exactly one column */
    2310          20 :             if (call_state->ret_tupdesc->natts != 1)
    2311           0 :                 elog(ERROR, "wrong result type supplied in return_next");
    2312             : 
    2313          20 :             retval = InputFunctionCall(&prodesc->result_in_func,
    2314          20 :                                        utf_u2e((char *) Tcl_GetString(objv[1])),
    2315             :                                        prodesc->result_typioparam,
    2316             :                                        -1);
    2317          20 :             tuplestore_putvalues(call_state->tuple_store, call_state->ret_tupdesc,
    2318             :                                  &retval, &isNull);
    2319             :         }
    2320             : 
    2321          30 :         pltcl_subtrans_commit(oldcontext, oldowner);
    2322             :     }
    2323           4 :     PG_CATCH();
    2324             :     {
    2325           4 :         pltcl_subtrans_abort(interp, oldcontext, oldowner);
    2326           4 :         return TCL_ERROR;
    2327             :     }
    2328          30 :     PG_END_TRY();
    2329             : 
    2330          30 :     return result;
    2331             : }
    2332             : 
    2333             : 
    2334             : /*----------
    2335             :  * Support for running SPI operations inside subtransactions
    2336             :  *
    2337             :  * Intended usage pattern is:
    2338             :  *
    2339             :  *  MemoryContext oldcontext = CurrentMemoryContext;
    2340             :  *  ResourceOwner oldowner = CurrentResourceOwner;
    2341             :  *
    2342             :  *  ...
    2343             :  *  pltcl_subtrans_begin(oldcontext, oldowner);
    2344             :  *  PG_TRY();
    2345             :  *  {
    2346             :  *      do something risky;
    2347             :  *      pltcl_subtrans_commit(oldcontext, oldowner);
    2348             :  *  }
    2349             :  *  PG_CATCH();
    2350             :  *  {
    2351             :  *      pltcl_subtrans_abort(interp, oldcontext, oldowner);
    2352             :  *      return TCL_ERROR;
    2353             :  *  }
    2354             :  *  PG_END_TRY();
    2355             :  *  return TCL_OK;
    2356             :  *----------
    2357             :  */
    2358             : static void
    2359         248 : pltcl_subtrans_begin(MemoryContext oldcontext, ResourceOwner oldowner)
    2360             : {
    2361         248 :     BeginInternalSubTransaction(NULL);
    2362             : 
    2363             :     /* Want to run inside function's memory context */
    2364         248 :     MemoryContextSwitchTo(oldcontext);
    2365         248 : }
    2366             : 
    2367             : static void
    2368         258 : pltcl_subtrans_commit(MemoryContext oldcontext, ResourceOwner oldowner)
    2369             : {
    2370             :     /* Commit the inner transaction, return to outer xact context */
    2371         258 :     ReleaseCurrentSubTransaction();
    2372         258 :     MemoryContextSwitchTo(oldcontext);
    2373         258 :     CurrentResourceOwner = oldowner;
    2374         258 : }
    2375             : 
    2376             : static void
    2377          24 : pltcl_subtrans_abort(Tcl_Interp *interp,
    2378             :                      MemoryContext oldcontext, ResourceOwner oldowner)
    2379             : {
    2380             :     ErrorData  *edata;
    2381             : 
    2382             :     /* Save error info */
    2383          24 :     MemoryContextSwitchTo(oldcontext);
    2384          24 :     edata = CopyErrorData();
    2385          24 :     FlushErrorState();
    2386             : 
    2387             :     /* Abort the inner transaction */
    2388          24 :     RollbackAndReleaseCurrentSubTransaction();
    2389          24 :     MemoryContextSwitchTo(oldcontext);
    2390          24 :     CurrentResourceOwner = oldowner;
    2391             : 
    2392             :     /* Pass the error data to Tcl */
    2393          24 :     pltcl_construct_errorCode(interp, edata);
    2394          24 :     UTF_BEGIN;
    2395          24 :     Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
    2396          24 :     UTF_END;
    2397          24 :     FreeErrorData(edata);
    2398          24 : }
    2399             : 
    2400             : 
    2401             : /**********************************************************************
    2402             :  * pltcl_SPI_execute()      - The builtin SPI_execute command
    2403             :  *                for the Tcl interpreter
    2404             :  **********************************************************************/
    2405             : static int
    2406         130 : pltcl_SPI_execute(ClientData cdata, Tcl_Interp *interp,
    2407             :                   int objc, Tcl_Obj *const objv[])
    2408             : {
    2409             :     int         my_rc;
    2410             :     int         spi_rc;
    2411             :     int         query_idx;
    2412             :     int         i;
    2413             :     int         optIndex;
    2414         130 :     int         count = 0;
    2415         130 :     const char *volatile arrayname = NULL;
    2416         130 :     Tcl_Obj    *volatile loop_body = NULL;
    2417         130 :     MemoryContext oldcontext = CurrentMemoryContext;
    2418         130 :     ResourceOwner oldowner = CurrentResourceOwner;
    2419             : 
    2420             :     enum options
    2421             :     {
    2422             :         OPT_ARRAY, OPT_COUNT
    2423             :     };
    2424             : 
    2425             :     static const char *options[] = {
    2426             :         "-array", "-count", (const char *) NULL
    2427             :     };
    2428             : 
    2429             :     /************************************************************
    2430             :      * Check the call syntax and get the options
    2431             :      ************************************************************/
    2432         130 :     if (objc < 2)
    2433             :     {
    2434           2 :         Tcl_WrongNumArgs(interp, 1, objv,
    2435             :                          "?-count n? ?-array name? query ?loop body?");
    2436           2 :         return TCL_ERROR;
    2437             :     }
    2438             : 
    2439         128 :     i = 1;
    2440         128 :     while (i < objc)
    2441             :     {
    2442         144 :         if (Tcl_GetIndexFromObj(NULL, objv[i], options, NULL,
    2443             :                                 TCL_EXACT, &optIndex) != TCL_OK)
    2444         122 :             break;
    2445             : 
    2446          22 :         if (++i >= objc)
    2447             :         {
    2448           4 :             Tcl_SetObjResult(interp,
    2449             :                              Tcl_NewStringObj("missing argument to -count or -array", -1));
    2450           4 :             return TCL_ERROR;
    2451             :         }
    2452             : 
    2453          18 :         switch ((enum options) optIndex)
    2454             :         {
    2455          16 :             case OPT_ARRAY:
    2456          16 :                 arrayname = Tcl_GetString(objv[i++]);
    2457          16 :                 break;
    2458             : 
    2459           2 :             case OPT_COUNT:
    2460           2 :                 if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
    2461           2 :                     return TCL_ERROR;
    2462           0 :                 break;
    2463             :         }
    2464         144 :     }
    2465             : 
    2466         122 :     query_idx = i;
    2467         122 :     if (query_idx >= objc || query_idx + 2 < objc)
    2468             :     {
    2469           2 :         Tcl_WrongNumArgs(interp, query_idx - 1, objv, "query ?loop body?");
    2470           2 :         return TCL_ERROR;
    2471             :     }
    2472             : 
    2473         120 :     if (query_idx + 1 < objc)
    2474          16 :         loop_body = objv[query_idx + 1];
    2475             : 
    2476             :     /************************************************************
    2477             :      * Execute the query inside a sub-transaction, so we can cope with
    2478             :      * errors sanely
    2479             :      ************************************************************/
    2480             : 
    2481         120 :     pltcl_subtrans_begin(oldcontext, oldowner);
    2482             : 
    2483         120 :     PG_TRY();
    2484             :     {
    2485         120 :         UTF_BEGIN;
    2486         120 :         spi_rc = SPI_execute(UTF_U2E(Tcl_GetString(objv[query_idx])),
    2487         120 :                              pltcl_current_call_state->prodesc->fn_readonly, count);
    2488         104 :         UTF_END;
    2489             : 
    2490         104 :         my_rc = pltcl_process_SPI_result(interp,
    2491             :                                          arrayname,
    2492             :                                          loop_body,
    2493             :                                          spi_rc,
    2494             :                                          SPI_tuptable,
    2495             :                                          SPI_processed);
    2496             : 
    2497         104 :         pltcl_subtrans_commit(oldcontext, oldowner);
    2498             :     }
    2499          16 :     PG_CATCH();
    2500             :     {
    2501          16 :         pltcl_subtrans_abort(interp, oldcontext, oldowner);
    2502          16 :         return TCL_ERROR;
    2503             :     }
    2504         104 :     PG_END_TRY();
    2505             : 
    2506         104 :     return my_rc;
    2507             : }
    2508             : 
    2509             : /*
    2510             :  * Process the result from SPI_execute or SPI_execute_plan
    2511             :  *
    2512             :  * Shared code between pltcl_SPI_execute and pltcl_SPI_execute_plan
    2513             :  */
    2514             : static int
    2515         202 : pltcl_process_SPI_result(Tcl_Interp *interp,
    2516             :                          const char *arrayname,
    2517             :                          Tcl_Obj *loop_body,
    2518             :                          int spi_rc,
    2519             :                          SPITupleTable *tuptable,
    2520             :                          uint64 ntuples)
    2521             : {
    2522         202 :     int         my_rc = TCL_OK;
    2523             :     int         loop_rc;
    2524             :     HeapTuple  *tuples;
    2525             :     TupleDesc   tupdesc;
    2526             : 
    2527         202 :     switch (spi_rc)
    2528             :     {
    2529          74 :         case SPI_OK_SELINTO:
    2530             :         case SPI_OK_INSERT:
    2531             :         case SPI_OK_DELETE:
    2532             :         case SPI_OK_UPDATE:
    2533             :         case SPI_OK_MERGE:
    2534          74 :             Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
    2535          74 :             break;
    2536             : 
    2537           2 :         case SPI_OK_UTILITY:
    2538             :         case SPI_OK_REWRITTEN:
    2539           2 :             if (tuptable == NULL)
    2540             :             {
    2541           2 :                 Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
    2542           2 :                 break;
    2543             :             }
    2544             :             /* fall through for utility returning tuples */
    2545             :             /* FALLTHROUGH */
    2546             : 
    2547             :         case SPI_OK_SELECT:
    2548             :         case SPI_OK_INSERT_RETURNING:
    2549             :         case SPI_OK_DELETE_RETURNING:
    2550             :         case SPI_OK_UPDATE_RETURNING:
    2551             :         case SPI_OK_MERGE_RETURNING:
    2552             : 
    2553             :             /*
    2554             :              * Process the tuples we got
    2555             :              */
    2556         124 :             tuples = tuptable->vals;
    2557         124 :             tupdesc = tuptable->tupdesc;
    2558             : 
    2559         124 :             if (loop_body == NULL)
    2560             :             {
    2561             :                 /*
    2562             :                  * If there is no loop body given, just set the variables from
    2563             :                  * the first tuple (if any)
    2564             :                  */
    2565         100 :                 if (ntuples > 0)
    2566          58 :                     pltcl_set_tuple_values(interp, arrayname, 0,
    2567             :                                            tuples[0], tupdesc);
    2568             :             }
    2569             :             else
    2570             :             {
    2571             :                 /*
    2572             :                  * There is a loop body - process all tuples and evaluate the
    2573             :                  * body on each
    2574             :                  */
    2575             :                 uint64      i;
    2576             : 
    2577          52 :                 for (i = 0; i < ntuples; i++)
    2578             :                 {
    2579          44 :                     pltcl_set_tuple_values(interp, arrayname, i,
    2580          44 :                                            tuples[i], tupdesc);
    2581             : 
    2582          44 :                     loop_rc = Tcl_EvalObjEx(interp, loop_body, 0);
    2583             : 
    2584          44 :                     if (loop_rc == TCL_OK)
    2585          24 :                         continue;
    2586          20 :                     if (loop_rc == TCL_CONTINUE)
    2587           4 :                         continue;
    2588          16 :                     if (loop_rc == TCL_RETURN)
    2589             :                     {
    2590           4 :                         my_rc = TCL_RETURN;
    2591           4 :                         break;
    2592             :                     }
    2593          12 :                     if (loop_rc == TCL_BREAK)
    2594           4 :                         break;
    2595           8 :                     my_rc = TCL_ERROR;
    2596           8 :                     break;
    2597             :                 }
    2598             :             }
    2599             : 
    2600         124 :             if (my_rc == TCL_OK)
    2601             :             {
    2602         112 :                 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
    2603             :             }
    2604         124 :             break;
    2605             : 
    2606           2 :         default:
    2607           2 :             Tcl_AppendResult(interp, "pltcl: SPI_execute failed: ",
    2608             :                              SPI_result_code_string(spi_rc), NULL);
    2609           2 :             my_rc = TCL_ERROR;
    2610           2 :             break;
    2611             :     }
    2612             : 
    2613         202 :     SPI_freetuptable(tuptable);
    2614             : 
    2615         202 :     return my_rc;
    2616             : }
    2617             : 
    2618             : 
    2619             : /**********************************************************************
    2620             :  * pltcl_SPI_prepare()      - Builtin support for prepared plans
    2621             :  *                The Tcl command SPI_prepare
    2622             :  *                always saves the plan using
    2623             :  *                SPI_keepplan and returns a key for
    2624             :  *                access. There is no chance to prepare
    2625             :  *                and not save the plan currently.
    2626             :  **********************************************************************/
    2627             : static int
    2628          34 : pltcl_SPI_prepare(ClientData cdata, Tcl_Interp *interp,
    2629             :                   int objc, Tcl_Obj *const objv[])
    2630             : {
    2631          34 :     volatile MemoryContext plan_cxt = NULL;
    2632             :     Tcl_Size    nargs;
    2633             :     Tcl_Obj   **argsObj;
    2634             :     pltcl_query_desc *qdesc;
    2635             :     int         i;
    2636             :     Tcl_HashEntry *hashent;
    2637             :     int         hashnew;
    2638             :     Tcl_HashTable *query_hash;
    2639          34 :     MemoryContext oldcontext = CurrentMemoryContext;
    2640          34 :     ResourceOwner oldowner = CurrentResourceOwner;
    2641             : 
    2642             :     /************************************************************
    2643             :      * Check the call syntax
    2644             :      ************************************************************/
    2645          34 :     if (objc != 3)
    2646             :     {
    2647           2 :         Tcl_WrongNumArgs(interp, 1, objv, "query argtypes");
    2648           2 :         return TCL_ERROR;
    2649             :     }
    2650             : 
    2651             :     /************************************************************
    2652             :      * Split the argument type list
    2653             :      ************************************************************/
    2654          32 :     if (Tcl_ListObjGetElements(interp, objv[2], &nargs, &argsObj) != TCL_OK)
    2655           2 :         return TCL_ERROR;
    2656             : 
    2657             :     /************************************************************
    2658             :      * Allocate the new querydesc structure
    2659             :      *
    2660             :      * struct qdesc and subsidiary data all live in plan_cxt.  Note that if the
    2661             :      * function is recompiled for whatever reason, permanent memory leaks
    2662             :      * occur.  FIXME someday.
    2663             :      ************************************************************/
    2664          30 :     plan_cxt = AllocSetContextCreate(TopMemoryContext,
    2665             :                                      "PL/Tcl spi_prepare query",
    2666             :                                      ALLOCSET_SMALL_SIZES);
    2667          30 :     MemoryContextSwitchTo(plan_cxt);
    2668          30 :     qdesc = (pltcl_query_desc *) palloc0(sizeof(pltcl_query_desc));
    2669          30 :     snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
    2670          30 :     qdesc->nargs = nargs;
    2671          30 :     qdesc->argtypes = (Oid *) palloc(nargs * sizeof(Oid));
    2672          30 :     qdesc->arginfuncs = (FmgrInfo *) palloc(nargs * sizeof(FmgrInfo));
    2673          30 :     qdesc->argtypioparams = (Oid *) palloc(nargs * sizeof(Oid));
    2674          30 :     MemoryContextSwitchTo(oldcontext);
    2675             : 
    2676             :     /************************************************************
    2677             :      * Execute the prepare inside a sub-transaction, so we can cope with
    2678             :      * errors sanely
    2679             :      ************************************************************/
    2680             : 
    2681          30 :     pltcl_subtrans_begin(oldcontext, oldowner);
    2682             : 
    2683          30 :     PG_TRY();
    2684             :     {
    2685             :         /************************************************************
    2686             :          * Resolve argument type names and then look them up by oid
    2687             :          * in the system cache, and remember the required information
    2688             :          * for input conversion.
    2689             :          ************************************************************/
    2690          68 :         for (i = 0; i < nargs; i++)
    2691             :         {
    2692             :             Oid         typId,
    2693             :                         typInput,
    2694             :                         typIOParam;
    2695             :             int32       typmod;
    2696             : 
    2697          40 :             (void) parseTypeString(Tcl_GetString(argsObj[i]),
    2698             :                                    &typId, &typmod, NULL);
    2699             : 
    2700          38 :             getTypeInputInfo(typId, &typInput, &typIOParam);
    2701             : 
    2702          38 :             qdesc->argtypes[i] = typId;
    2703          38 :             fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
    2704          38 :             qdesc->argtypioparams[i] = typIOParam;
    2705             :         }
    2706             : 
    2707             :         /************************************************************
    2708             :          * Prepare the plan and check for errors
    2709             :          ************************************************************/
    2710          28 :         UTF_BEGIN;
    2711          28 :         qdesc->plan = SPI_prepare(UTF_U2E(Tcl_GetString(objv[1])),
    2712             :                                   nargs, qdesc->argtypes);
    2713          26 :         UTF_END;
    2714             : 
    2715          26 :         if (qdesc->plan == NULL)
    2716           0 :             elog(ERROR, "SPI_prepare() failed");
    2717             : 
    2718             :         /************************************************************
    2719             :          * Save the plan into permanent memory (right now it's in the
    2720             :          * SPI procCxt, which will go away at function end).
    2721             :          ************************************************************/
    2722          26 :         if (SPI_keepplan(qdesc->plan))
    2723           0 :             elog(ERROR, "SPI_keepplan() failed");
    2724             : 
    2725          26 :         pltcl_subtrans_commit(oldcontext, oldowner);
    2726             :     }
    2727           4 :     PG_CATCH();
    2728             :     {
    2729           4 :         pltcl_subtrans_abort(interp, oldcontext, oldowner);
    2730             : 
    2731           4 :         MemoryContextDelete(plan_cxt);
    2732             : 
    2733           4 :         return TCL_ERROR;
    2734             :     }
    2735          26 :     PG_END_TRY();
    2736             : 
    2737             :     /************************************************************
    2738             :      * Insert a hashtable entry for the plan and return
    2739             :      * the key to the caller
    2740             :      ************************************************************/
    2741          26 :     query_hash = &pltcl_current_call_state->prodesc->interp_desc->query_hash;
    2742             : 
    2743          26 :     hashent = Tcl_CreateHashEntry(query_hash, qdesc->qname, &hashnew);
    2744          26 :     Tcl_SetHashValue(hashent, (ClientData) qdesc);
    2745             : 
    2746             :     /* qname is ASCII, so no need for encoding conversion */
    2747          26 :     Tcl_SetObjResult(interp, Tcl_NewStringObj(qdesc->qname, -1));
    2748          26 :     return TCL_OK;
    2749             : }
    2750             : 
    2751             : 
    2752             : /**********************************************************************
    2753             :  * pltcl_SPI_execute_plan()     - Execute a prepared plan
    2754             :  **********************************************************************/
    2755             : static int
    2756         110 : pltcl_SPI_execute_plan(ClientData cdata, Tcl_Interp *interp,
    2757             :                        int objc, Tcl_Obj *const objv[])
    2758             : {
    2759             :     int         my_rc;
    2760             :     int         spi_rc;
    2761             :     int         i;
    2762             :     int         j;
    2763             :     int         optIndex;
    2764             :     Tcl_HashEntry *hashent;
    2765             :     pltcl_query_desc *qdesc;
    2766         110 :     const char *nulls = NULL;
    2767         110 :     const char *arrayname = NULL;
    2768         110 :     Tcl_Obj    *loop_body = NULL;
    2769         110 :     int         count = 0;
    2770             :     Tcl_Size    callObjc;
    2771         110 :     Tcl_Obj   **callObjv = NULL;
    2772             :     Datum      *argvalues;
    2773         110 :     MemoryContext oldcontext = CurrentMemoryContext;
    2774         110 :     ResourceOwner oldowner = CurrentResourceOwner;
    2775             :     Tcl_HashTable *query_hash;
    2776             : 
    2777             :     enum options
    2778             :     {
    2779             :         OPT_ARRAY, OPT_COUNT, OPT_NULLS
    2780             :     };
    2781             : 
    2782             :     static const char *options[] = {
    2783             :         "-array", "-count", "-nulls", (const char *) NULL
    2784             :     };
    2785             : 
    2786             :     /************************************************************
    2787             :      * Get the options and check syntax
    2788             :      ************************************************************/
    2789         110 :     i = 1;
    2790         110 :     while (i < objc)
    2791             :     {
    2792         196 :         if (Tcl_GetIndexFromObj(NULL, objv[i], options, NULL,
    2793             :                                 TCL_EXACT, &optIndex) != TCL_OK)
    2794         100 :             break;
    2795             : 
    2796          96 :         if (++i >= objc)
    2797             :         {
    2798           6 :             Tcl_SetObjResult(interp,
    2799             :                              Tcl_NewStringObj("missing argument to -array, -count or -nulls", -1));
    2800           6 :             return TCL_ERROR;
    2801             :         }
    2802             : 
    2803          90 :         switch ((enum options) optIndex)
    2804             :         {
    2805           8 :             case OPT_ARRAY:
    2806           8 :                 arrayname = Tcl_GetString(objv[i++]);
    2807           8 :                 break;
    2808             : 
    2809          82 :             case OPT_COUNT:
    2810          82 :                 if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
    2811           2 :                     return TCL_ERROR;
    2812          80 :                 break;
    2813             : 
    2814           0 :             case OPT_NULLS:
    2815           0 :                 nulls = Tcl_GetString(objv[i++]);
    2816           0 :                 break;
    2817             :         }
    2818         198 :     }
    2819             : 
    2820             :     /************************************************************
    2821             :      * Get the prepared plan descriptor by its key
    2822             :      ************************************************************/
    2823         102 :     if (i >= objc)
    2824             :     {
    2825           2 :         Tcl_SetObjResult(interp,
    2826             :                          Tcl_NewStringObj("missing argument to -count or -array", -1));
    2827           2 :         return TCL_ERROR;
    2828             :     }
    2829             : 
    2830         100 :     query_hash = &pltcl_current_call_state->prodesc->interp_desc->query_hash;
    2831             : 
    2832         100 :     hashent = Tcl_FindHashEntry(query_hash, Tcl_GetString(objv[i]));
    2833         100 :     if (hashent == NULL)
    2834             :     {
    2835           2 :         Tcl_AppendResult(interp, "invalid queryid '", Tcl_GetString(objv[i]), "'", NULL);
    2836           2 :         return TCL_ERROR;
    2837             :     }
    2838          98 :     qdesc = (pltcl_query_desc *) Tcl_GetHashValue(hashent);
    2839          98 :     i++;
    2840             : 
    2841             :     /************************************************************
    2842             :      * If a nulls string is given, check for correct length
    2843             :      ************************************************************/
    2844          98 :     if (nulls != NULL)
    2845             :     {
    2846           0 :         if (strlen(nulls) != qdesc->nargs)
    2847             :         {
    2848           0 :             Tcl_SetObjResult(interp,
    2849             :                              Tcl_NewStringObj("length of nulls string doesn't match number of arguments",
    2850             :                                               -1));
    2851           0 :             return TCL_ERROR;
    2852             :         }
    2853             :     }
    2854             : 
    2855             :     /************************************************************
    2856             :      * If there was an argtype list on preparation, we need
    2857             :      * an argument value list now
    2858             :      ************************************************************/
    2859          98 :     if (qdesc->nargs > 0)
    2860             :     {
    2861          90 :         if (i >= objc)
    2862             :         {
    2863           0 :             Tcl_SetObjResult(interp,
    2864             :                              Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
    2865             :                                               -1));
    2866           0 :             return TCL_ERROR;
    2867             :         }
    2868             : 
    2869             :         /************************************************************
    2870             :          * Split the argument values
    2871             :          ************************************************************/
    2872          90 :         if (Tcl_ListObjGetElements(interp, objv[i++], &callObjc, &callObjv) != TCL_OK)
    2873           0 :             return TCL_ERROR;
    2874             : 
    2875             :         /************************************************************
    2876             :          * Check that the number of arguments matches
    2877             :          ************************************************************/
    2878          90 :         if (callObjc != qdesc->nargs)
    2879             :         {
    2880           0 :             Tcl_SetObjResult(interp,
    2881             :                              Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
    2882             :                                               -1));
    2883           0 :             return TCL_ERROR;
    2884             :         }
    2885             :     }
    2886             :     else
    2887           8 :         callObjc = 0;
    2888             : 
    2889             :     /************************************************************
    2890             :      * Get loop body if present
    2891             :      ************************************************************/
    2892          98 :     if (i < objc)
    2893           8 :         loop_body = objv[i++];
    2894             : 
    2895          98 :     if (i != objc)
    2896             :     {
    2897           0 :         Tcl_WrongNumArgs(interp, 1, objv,
    2898             :                          "?-count n? ?-array name? ?-nulls string? "
    2899             :                          "query ?args? ?loop body?");
    2900           0 :         return TCL_ERROR;
    2901             :     }
    2902             : 
    2903             :     /************************************************************
    2904             :      * Execute the plan inside a sub-transaction, so we can cope with
    2905             :      * errors sanely
    2906             :      ************************************************************/
    2907             : 
    2908          98 :     pltcl_subtrans_begin(oldcontext, oldowner);
    2909             : 
    2910          98 :     PG_TRY();
    2911             :     {
    2912             :         /************************************************************
    2913             :          * Setup the value array for SPI_execute_plan() using
    2914             :          * the type specific input functions
    2915             :          ************************************************************/
    2916          98 :         argvalues = (Datum *) palloc(callObjc * sizeof(Datum));
    2917             : 
    2918         284 :         for (j = 0; j < callObjc; j++)
    2919             :         {
    2920         186 :             if (nulls && nulls[j] == 'n')
    2921             :             {
    2922           0 :                 argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
    2923             :                                                  NULL,
    2924           0 :                                                  qdesc->argtypioparams[j],
    2925             :                                                  -1);
    2926             :             }
    2927             :             else
    2928             :             {
    2929         186 :                 UTF_BEGIN;
    2930         558 :                 argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
    2931         186 :                                                  UTF_U2E(Tcl_GetString(callObjv[j])),
    2932         186 :                                                  qdesc->argtypioparams[j],
    2933             :                                                  -1);
    2934         186 :                 UTF_END;
    2935             :             }
    2936             :         }
    2937             : 
    2938             :         /************************************************************
    2939             :          * Execute the plan
    2940             :          ************************************************************/
    2941         196 :         spi_rc = SPI_execute_plan(qdesc->plan, argvalues, nulls,
    2942          98 :                                   pltcl_current_call_state->prodesc->fn_readonly,
    2943             :                                   count);
    2944             : 
    2945          98 :         my_rc = pltcl_process_SPI_result(interp,
    2946             :                                          arrayname,
    2947             :                                          loop_body,
    2948             :                                          spi_rc,
    2949             :                                          SPI_tuptable,
    2950             :                                          SPI_processed);
    2951             : 
    2952          98 :         pltcl_subtrans_commit(oldcontext, oldowner);
    2953             :     }
    2954           0 :     PG_CATCH();
    2955             :     {
    2956           0 :         pltcl_subtrans_abort(interp, oldcontext, oldowner);
    2957           0 :         return TCL_ERROR;
    2958             :     }
    2959          98 :     PG_END_TRY();
    2960             : 
    2961          98 :     return my_rc;
    2962             : }
    2963             : 
    2964             : 
    2965             : /**********************************************************************
    2966             :  * pltcl_subtransaction()   - Execute some Tcl code in a subtransaction
    2967             :  *
    2968             :  * The subtransaction is aborted if the Tcl code fragment returns TCL_ERROR,
    2969             :  * otherwise it's subcommitted.
    2970             :  **********************************************************************/
    2971             : static int
    2972          16 : pltcl_subtransaction(ClientData cdata, Tcl_Interp *interp,
    2973             :                      int objc, Tcl_Obj *const objv[])
    2974             : {
    2975          16 :     MemoryContext oldcontext = CurrentMemoryContext;
    2976          16 :     ResourceOwner oldowner = CurrentResourceOwner;
    2977             :     int         retcode;
    2978             : 
    2979          16 :     if (objc != 2)
    2980             :     {
    2981           0 :         Tcl_WrongNumArgs(interp, 1, objv, "command");
    2982           0 :         return TCL_ERROR;
    2983             :     }
    2984             : 
    2985             :     /*
    2986             :      * Note: we don't use pltcl_subtrans_begin and friends here because we
    2987             :      * don't want the error handling in pltcl_subtrans_abort.  But otherwise
    2988             :      * the processing should be about the same as in those functions.
    2989             :      */
    2990          16 :     BeginInternalSubTransaction(NULL);
    2991          16 :     MemoryContextSwitchTo(oldcontext);
    2992             : 
    2993          16 :     retcode = Tcl_EvalObjEx(interp, objv[1], 0);
    2994             : 
    2995          16 :     if (retcode == TCL_ERROR)
    2996             :     {
    2997             :         /* Rollback the subtransaction */
    2998          10 :         RollbackAndReleaseCurrentSubTransaction();
    2999             :     }
    3000             :     else
    3001             :     {
    3002             :         /* Commit the subtransaction */
    3003           6 :         ReleaseCurrentSubTransaction();
    3004             :     }
    3005             : 
    3006             :     /* In either case, restore previous memory context and resource owner */
    3007          16 :     MemoryContextSwitchTo(oldcontext);
    3008          16 :     CurrentResourceOwner = oldowner;
    3009             : 
    3010          16 :     return retcode;
    3011             : }
    3012             : 
    3013             : 
    3014             : /**********************************************************************
    3015             :  * pltcl_commit()
    3016             :  *
    3017             :  * Commit the transaction and start a new one.
    3018             :  **********************************************************************/
    3019             : static int
    3020          20 : pltcl_commit(ClientData cdata, Tcl_Interp *interp,
    3021             :              int objc, Tcl_Obj *const objv[])
    3022             : {
    3023          20 :     MemoryContext oldcontext = CurrentMemoryContext;
    3024             : 
    3025          20 :     PG_TRY();
    3026             :     {
    3027          20 :         SPI_commit();
    3028             :     }
    3029          10 :     PG_CATCH();
    3030             :     {
    3031             :         ErrorData  *edata;
    3032             : 
    3033             :         /* Save error info */
    3034          10 :         MemoryContextSwitchTo(oldcontext);
    3035          10 :         edata = CopyErrorData();
    3036          10 :         FlushErrorState();
    3037             : 
    3038             :         /* Pass the error data to Tcl */
    3039          10 :         pltcl_construct_errorCode(interp, edata);
    3040          10 :         UTF_BEGIN;
    3041          10 :         Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
    3042          10 :         UTF_END;
    3043          10 :         FreeErrorData(edata);
    3044             : 
    3045          10 :         return TCL_ERROR;
    3046             :     }
    3047          10 :     PG_END_TRY();
    3048             : 
    3049          10 :     return TCL_OK;
    3050             : }
    3051             : 
    3052             : 
    3053             : /**********************************************************************
    3054             :  * pltcl_rollback()
    3055             :  *
    3056             :  * Abort the transaction and start a new one.
    3057             :  **********************************************************************/
    3058             : static int
    3059          12 : pltcl_rollback(ClientData cdata, Tcl_Interp *interp,
    3060             :                int objc, Tcl_Obj *const objv[])
    3061             : {
    3062          12 :     MemoryContext oldcontext = CurrentMemoryContext;
    3063             : 
    3064          12 :     PG_TRY();
    3065             :     {
    3066          12 :         SPI_rollback();
    3067             :     }
    3068           2 :     PG_CATCH();
    3069             :     {
    3070             :         ErrorData  *edata;
    3071             : 
    3072             :         /* Save error info */
    3073           2 :         MemoryContextSwitchTo(oldcontext);
    3074           2 :         edata = CopyErrorData();
    3075           2 :         FlushErrorState();
    3076             : 
    3077             :         /* Pass the error data to Tcl */
    3078           2 :         pltcl_construct_errorCode(interp, edata);
    3079           2 :         UTF_BEGIN;
    3080           2 :         Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
    3081           2 :         UTF_END;
    3082           2 :         FreeErrorData(edata);
    3083             : 
    3084           2 :         return TCL_ERROR;
    3085             :     }
    3086          10 :     PG_END_TRY();
    3087             : 
    3088          10 :     return TCL_OK;
    3089             : }
    3090             : 
    3091             : 
    3092             : /**********************************************************************
    3093             :  * pltcl_set_tuple_values() - Set variables for all attributes
    3094             :  *                of a given tuple
    3095             :  *
    3096             :  * Note: arrayname is presumed to be UTF8; it usually came from Tcl
    3097             :  **********************************************************************/
    3098             : static void
    3099         102 : pltcl_set_tuple_values(Tcl_Interp *interp, const char *arrayname,
    3100             :                        uint64 tupno, HeapTuple tuple, TupleDesc tupdesc)
    3101             : {
    3102             :     int         i;
    3103             :     char       *outputstr;
    3104             :     Datum       attr;
    3105             :     bool        isnull;
    3106             :     const char *attname;
    3107             :     Oid         typoutput;
    3108             :     bool        typisvarlena;
    3109             :     const char **arrptr;
    3110             :     const char **nameptr;
    3111         102 :     const char *nullname = NULL;
    3112             : 
    3113             :     /************************************************************
    3114             :      * Prepare pointers for Tcl_SetVar2Ex() below
    3115             :      ************************************************************/
    3116         102 :     if (arrayname == NULL)
    3117             :     {
    3118          58 :         arrptr = &attname;
    3119          58 :         nameptr = &nullname;
    3120             :     }
    3121             :     else
    3122             :     {
    3123          44 :         arrptr = &arrayname;
    3124          44 :         nameptr = &attname;
    3125             : 
    3126             :         /*
    3127             :          * When outputting to an array, fill the ".tupno" element with the
    3128             :          * current tuple number.  This will be overridden below if ".tupno" is
    3129             :          * in use as an actual field name in the rowtype.
    3130             :          */
    3131          44 :         Tcl_SetVar2Ex(interp, arrayname, ".tupno", Tcl_NewWideIntObj(tupno), 0);
    3132             :     }
    3133             : 
    3134         244 :     for (i = 0; i < tupdesc->natts; i++)
    3135             :     {
    3136         142 :         Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    3137             : 
    3138             :         /* ignore dropped attributes */
    3139         142 :         if (att->attisdropped)
    3140           0 :             continue;
    3141             : 
    3142             :         /************************************************************
    3143             :          * Get the attribute name
    3144             :          ************************************************************/
    3145         142 :         UTF_BEGIN;
    3146         142 :         attname = pstrdup(UTF_E2U(NameStr(att->attname)));
    3147         142 :         UTF_END;
    3148             : 
    3149             :         /************************************************************
    3150             :          * Get the attributes value
    3151             :          ************************************************************/
    3152         142 :         attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
    3153             : 
    3154             :         /************************************************************
    3155             :          * If there is a value, set the variable
    3156             :          * If not, unset it
    3157             :          *
    3158             :          * Hmmm - Null attributes will cause functions to
    3159             :          *        crash if they don't expect them - need something
    3160             :          *        smarter here.
    3161             :          ************************************************************/
    3162         142 :         if (!isnull)
    3163             :         {
    3164         142 :             getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
    3165         142 :             outputstr = OidOutputFunctionCall(typoutput, attr);
    3166         142 :             UTF_BEGIN;
    3167         142 :             Tcl_SetVar2Ex(interp, *arrptr, *nameptr,
    3168         142 :                           Tcl_NewStringObj(UTF_E2U(outputstr), -1), 0);
    3169         142 :             UTF_END;
    3170         142 :             pfree(outputstr);
    3171             :         }
    3172             :         else
    3173           0 :             Tcl_UnsetVar2(interp, *arrptr, *nameptr, 0);
    3174             : 
    3175         142 :         pfree(unconstify(char *, attname));
    3176             :     }
    3177         102 : }
    3178             : 
    3179             : 
    3180             : /**********************************************************************
    3181             :  * pltcl_build_tuple_argument() - Build a list object usable for 'array set'
    3182             :  *                from all attributes of a given tuple
    3183             :  **********************************************************************/
    3184             : static Tcl_Obj *
    3185         138 : pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
    3186             : {
    3187         138 :     Tcl_Obj    *retobj = Tcl_NewObj();
    3188             :     int         i;
    3189             :     char       *outputstr;
    3190             :     Datum       attr;
    3191             :     bool        isnull;
    3192             :     char       *attname;
    3193             :     Oid         typoutput;
    3194             :     bool        typisvarlena;
    3195             : 
    3196         568 :     for (i = 0; i < tupdesc->natts; i++)
    3197             :     {
    3198         430 :         Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    3199             : 
    3200             :         /* ignore dropped attributes */
    3201         430 :         if (att->attisdropped)
    3202          16 :             continue;
    3203             : 
    3204         414 :         if (att->attgenerated)
    3205             :         {
    3206             :             /* don't include unless requested */
    3207          18 :             if (!include_generated)
    3208           6 :                 continue;
    3209             :         }
    3210             : 
    3211             :         /************************************************************
    3212             :          * Get the attribute name
    3213             :          ************************************************************/
    3214         408 :         attname = NameStr(att->attname);
    3215             : 
    3216             :         /************************************************************
    3217             :          * Get the attributes value
    3218             :          ************************************************************/
    3219         408 :         attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
    3220             : 
    3221             :         /************************************************************
    3222             :          * If there is a value, append the attribute name and the
    3223             :          * value to the list
    3224             :          *
    3225             :          * Hmmm - Null attributes will cause functions to
    3226             :          *        crash if they don't expect them - need something
    3227             :          *        smarter here.
    3228             :          ************************************************************/
    3229         408 :         if (!isnull)
    3230             :         {
    3231         400 :             getTypeOutputInfo(att->atttypid,
    3232             :                               &typoutput, &typisvarlena);
    3233         400 :             outputstr = OidOutputFunctionCall(typoutput, attr);
    3234         400 :             UTF_BEGIN;
    3235         400 :             Tcl_ListObjAppendElement(NULL, retobj,
    3236         400 :                                      Tcl_NewStringObj(UTF_E2U(attname), -1));
    3237         400 :             UTF_END;
    3238         400 :             UTF_BEGIN;
    3239         400 :             Tcl_ListObjAppendElement(NULL, retobj,
    3240         400 :                                      Tcl_NewStringObj(UTF_E2U(outputstr), -1));
    3241         400 :             UTF_END;
    3242         400 :             pfree(outputstr);
    3243             :         }
    3244             :     }
    3245             : 
    3246         138 :     return retobj;
    3247             : }
    3248             : 
    3249             : /**********************************************************************
    3250             :  * pltcl_build_tuple_result() - Build a tuple of function's result rowtype
    3251             :  *                from a Tcl list of column names and values
    3252             :  *
    3253             :  * In a trigger function, we build a tuple of the trigger table's rowtype.
    3254             :  *
    3255             :  * Note: this function leaks memory.  Even if we made it clean up its own
    3256             :  * mess, there's no way to prevent the datatype input functions it calls
    3257             :  * from leaking.  Run it in a short-lived context, unless we're about to
    3258             :  * exit the procedure anyway.
    3259             :  **********************************************************************/
    3260             : static HeapTuple
    3261          62 : pltcl_build_tuple_result(Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc,
    3262             :                          pltcl_call_state *call_state)
    3263             : {
    3264             :     HeapTuple   tuple;
    3265             :     TupleDesc   tupdesc;
    3266             :     AttInMetadata *attinmeta;
    3267             :     char      **values;
    3268             :     int         i;
    3269             : 
    3270          62 :     if (call_state->ret_tupdesc)
    3271             :     {
    3272          42 :         tupdesc = call_state->ret_tupdesc;
    3273          42 :         attinmeta = call_state->attinmeta;
    3274             :     }
    3275          20 :     else if (call_state->trigdata)
    3276             :     {
    3277          20 :         tupdesc = RelationGetDescr(call_state->trigdata->tg_relation);
    3278          20 :         attinmeta = TupleDescGetAttInMetadata(tupdesc);
    3279             :     }
    3280             :     else
    3281             :     {
    3282           0 :         elog(ERROR, "PL/Tcl function does not return a tuple");
    3283             :         tupdesc = NULL;         /* keep compiler quiet */
    3284             :         attinmeta = NULL;
    3285             :     }
    3286             : 
    3287          62 :     values = (char **) palloc0(tupdesc->natts * sizeof(char *));
    3288             : 
    3289          62 :     if (kvObjc % 2 != 0)
    3290           4 :         ereport(ERROR,
    3291             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3292             :                  errmsg("column name/value list must have even number of elements")));
    3293             : 
    3294         196 :     for (i = 0; i < kvObjc; i += 2)
    3295             :     {
    3296         146 :         char       *fieldName = utf_u2e(Tcl_GetString(kvObjv[i]));
    3297         146 :         int         attn = SPI_fnumber(tupdesc, fieldName);
    3298             : 
    3299             :         /*
    3300             :          * We silently ignore ".tupno", if it's present but doesn't match any
    3301             :          * actual output column.  This allows direct use of a row returned by
    3302             :          * pltcl_set_tuple_values().
    3303             :          */
    3304         146 :         if (attn == SPI_ERROR_NOATTRIBUTE)
    3305             :         {
    3306           6 :             if (strcmp(fieldName, ".tupno") == 0)
    3307           0 :                 continue;
    3308           6 :             ereport(ERROR,
    3309             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    3310             :                      errmsg("column name/value list contains nonexistent column name \"%s\"",
    3311             :                             fieldName)));
    3312             :         }
    3313             : 
    3314         140 :         if (attn <= 0)
    3315           0 :             ereport(ERROR,
    3316             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3317             :                      errmsg("cannot set system attribute \"%s\"",
    3318             :                             fieldName)));
    3319             : 
    3320         140 :         if (TupleDescAttr(tupdesc, attn - 1)->attgenerated)
    3321           2 :             ereport(ERROR,
    3322             :                     (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    3323             :                      errmsg("cannot set generated column \"%s\"",
    3324             :                             fieldName)));
    3325             : 
    3326         138 :         values[attn - 1] = utf_u2e(Tcl_GetString(kvObjv[i + 1]));
    3327             :     }
    3328             : 
    3329          50 :     tuple = BuildTupleFromCStrings(attinmeta, values);
    3330             : 
    3331             :     /* if result type is domain-over-composite, check domain constraints */
    3332          50 :     if (call_state->prodesc->fn_retisdomain)
    3333           6 :         domain_check(HeapTupleGetDatum(tuple), false,
    3334           6 :                      call_state->prodesc->result_typid,
    3335           6 :                      &call_state->prodesc->domain_info,
    3336           6 :                      call_state->prodesc->fn_cxt);
    3337             : 
    3338          48 :     return tuple;
    3339             : }
    3340             : 
    3341             : /**********************************************************************
    3342             :  * pltcl_init_tuple_store() - Initialize the result tuplestore for a SRF
    3343             :  **********************************************************************/
    3344             : static void
    3345          10 : pltcl_init_tuple_store(pltcl_call_state *call_state)
    3346             : {
    3347          10 :     ReturnSetInfo *rsi = call_state->rsi;
    3348             :     MemoryContext oldcxt;
    3349             :     ResourceOwner oldowner;
    3350             : 
    3351             :     /* Should be in a SRF */
    3352             :     Assert(rsi);
    3353             :     /* Should be first time through */
    3354             :     Assert(!call_state->tuple_store);
    3355             :     Assert(!call_state->attinmeta);
    3356             : 
    3357             :     /* We expect caller to provide an appropriate result tupdesc */
    3358             :     Assert(rsi->expectedDesc);
    3359          10 :     call_state->ret_tupdesc = rsi->expectedDesc;
    3360             : 
    3361             :     /*
    3362             :      * Switch to the right memory context and resource owner for storing the
    3363             :      * tuplestore. If we're within a subtransaction opened for an exception
    3364             :      * block, for example, we must still create the tuplestore in the resource
    3365             :      * owner that was active when this function was entered, and not in the
    3366             :      * subtransaction's resource owner.
    3367             :      */
    3368          10 :     oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
    3369          10 :     oldowner = CurrentResourceOwner;
    3370          10 :     CurrentResourceOwner = call_state->tuple_store_owner;
    3371             : 
    3372          10 :     call_state->tuple_store =
    3373          10 :         tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
    3374             :                               false, work_mem);
    3375             : 
    3376             :     /* Build attinmeta in this context, too */
    3377          10 :     call_state->attinmeta = TupleDescGetAttInMetadata(call_state->ret_tupdesc);
    3378             : 
    3379          10 :     CurrentResourceOwner = oldowner;
    3380          10 :     MemoryContextSwitchTo(oldcxt);
    3381          10 : }

Generated by: LCOV version 1.14