PostgreSQL Source Code  git master
pltcl.c File Reference
#include "postgres.h"
#include <tcl.h>
#include <unistd.h>
#include <fcntl.h>
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "parser/parse_func.h"
#include "parser/parse_type.h"
#include "pgstat.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/regproc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "pltclerrcodes.h"
Include dependency graph for pltcl.c:

Go to the source code of this file.

Data Structures

struct  pltcl_interp_desc
 
struct  pltcl_proc_desc
 
struct  pltcl_query_desc
 
struct  pltcl_proc_key
 
struct  pltcl_proc_ptr
 
struct  pltcl_call_state
 
struct  TclExceptionNameMap
 

Macros

#define HAVE_TCL_VERSION(maj, min)
 
#define CONST86
 
#define TEXTDOMAIN   PG_TEXTDOMAIN("pltcl")
 
#define UTF_BEGIN
 
#define UTF_END
 
#define UTF_U2E(x)   (_pltcl_utf_dst = utf_u2e(_pltcl_utf_src = (x)))
 
#define UTF_E2U(x)   (_pltcl_utf_dst = utf_e2u(_pltcl_utf_src = (x)))
 

Typedefs

typedef struct pltcl_interp_desc pltcl_interp_desc
 
typedef struct pltcl_proc_desc pltcl_proc_desc
 
typedef struct pltcl_query_desc pltcl_query_desc
 
typedef struct pltcl_proc_key pltcl_proc_key
 
typedef struct pltcl_proc_ptr pltcl_proc_ptr
 
typedef struct pltcl_call_state pltcl_call_state
 

Functions

static char * utf_u2e (const char *src)
 
static char * utf_e2u (const char *src)
 
void _PG_init (void)
 
static void pltcl_init_interp (pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
 
static pltcl_interp_descpltcl_fetch_interp (Oid prolang, bool pltrusted)
 
static void call_pltcl_start_proc (Oid prolang, bool pltrusted)
 
static void start_proc_error_callback (void *arg)
 
static Datum pltcl_handler (PG_FUNCTION_ARGS, bool pltrusted)
 
static Datum pltcl_func_handler (PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
 
static HeapTuple pltcl_trigger_handler (PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
 
static void pltcl_event_trigger_handler (PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
 
static void throw_tcl_error (Tcl_Interp *interp, const char *proname)
 
static pltcl_proc_desccompile_pltcl_function (Oid fn_oid, Oid tgreloid, bool is_event_trigger, bool pltrusted)
 
static int pltcl_elog (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static void pltcl_construct_errorCode (Tcl_Interp *interp, ErrorData *edata)
 
static const char * pltcl_get_condition_name (int sqlstate)
 
static int pltcl_quote (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_argisnull (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_returnnull (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_returnnext (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_SPI_execute (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_process_SPI_result (Tcl_Interp *interp, const char *arrayname, Tcl_Obj *loop_body, int spi_rc, SPITupleTable *tuptable, uint64 ntuples)
 
static int pltcl_SPI_prepare (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_SPI_execute_plan (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_subtransaction (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_commit (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_rollback (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static void pltcl_subtrans_begin (MemoryContext oldcontext, ResourceOwner oldowner)
 
static void pltcl_subtrans_commit (MemoryContext oldcontext, ResourceOwner oldowner)
 
static void pltcl_subtrans_abort (Tcl_Interp *interp, MemoryContext oldcontext, ResourceOwner oldowner)
 
static void pltcl_set_tuple_values (Tcl_Interp *interp, const char *arrayname, uint64 tupno, HeapTuple tuple, TupleDesc tupdesc)
 
static Tcl_Obj * pltcl_build_tuple_argument (HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
 
static HeapTuple pltcl_build_tuple_result (Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc, pltcl_call_state *call_state)
 
static void pltcl_init_tuple_store (pltcl_call_state *call_state)
 
static ClientData pltcl_InitNotifier (void)
 
static void pltcl_FinalizeNotifier (ClientData clientData)
 
static void pltcl_SetTimer (CONST86 Tcl_Time *timePtr)
 
static void pltcl_AlertNotifier (ClientData clientData)
 
static void pltcl_CreateFileHandler (int fd, int mask, Tcl_FileProc *proc, ClientData clientData)
 
static void pltcl_DeleteFileHandler (int fd)
 
static void pltcl_ServiceModeHook (int mode)
 
static int pltcl_WaitForEvent (CONST86 Tcl_Time *timePtr)
 
 PG_FUNCTION_INFO_V1 (pltcl_call_handler)
 
Datum pltcl_call_handler (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (pltclu_call_handler)
 
Datum pltclu_call_handler (PG_FUNCTION_ARGS)
 

Variables

 PG_MODULE_MAGIC
 
static char * pltcl_start_proc = NULL
 
static char * pltclu_start_proc = NULL
 
static bool pltcl_pm_init_done = false
 
static Tcl_Interp * pltcl_hold_interp = NULL
 
static HTABpltcl_interp_htab = NULL
 
static HTABpltcl_proc_htab = NULL
 
static pltcl_call_statepltcl_current_call_state = NULL
 
static const TclExceptionNameMap exception_name_map []
 

Macro Definition Documentation

◆ CONST86

#define CONST86

Definition at line 56 of file pltcl.c.

◆ HAVE_TCL_VERSION

#define HAVE_TCL_VERSION (   maj,
  min 
)
Value:
((TCL_MAJOR_VERSION > maj) || \
(TCL_MAJOR_VERSION == maj && TCL_MINOR_VERSION >= min))

Definition at line 45 of file pltcl.c.

◆ TEXTDOMAIN

#define TEXTDOMAIN   PG_TEXTDOMAIN("pltcl")

Definition at line 61 of file pltcl.c.

Referenced by _PG_init().

◆ UTF_BEGIN

◆ UTF_E2U

#define UTF_E2U (   x)    (_pltcl_utf_dst = utf_e2u(_pltcl_utf_src = (x)))

◆ UTF_END

#define UTF_END

◆ UTF_U2E

#define UTF_U2E (   x)    (_pltcl_utf_dst = utf_u2e(_pltcl_utf_src = (x)))

Definition at line 96 of file pltcl.c.

Referenced by pltcl_elog(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

Typedef Documentation

◆ pltcl_call_state

◆ pltcl_interp_desc

◆ pltcl_proc_desc

◆ pltcl_proc_key

◆ pltcl_proc_ptr

◆ pltcl_query_desc

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 401 of file pltcl.c.

References DefineCustomStringVariable(), elog, HASHCTL::entrysize, ERROR, gettext_noop, HASH_BLOBS, hash_create(), HASH_ELEM, HASHCTL::keysize, pg_bindtextdomain(), PGC_SUSET, pltcl_AlertNotifier(), pltcl_CreateFileHandler(), pltcl_DeleteFileHandler(), pltcl_FinalizeNotifier(), pltcl_hold_interp, pltcl_InitNotifier(), pltcl_pm_init_done, pltcl_ServiceModeHook(), pltcl_SetTimer(), pltcl_start_proc, pltcl_WaitForEvent(), pltclu_start_proc, and TEXTDOMAIN.

402 {
403  Tcl_NotifierProcs notifier;
404  HASHCTL hash_ctl;
405 
406  /* Be sure we do initialization only once (should be redundant now) */
407  if (pltcl_pm_init_done)
408  return;
409 
411 
412 #ifdef WIN32
413  /* Required on win32 to prevent error loading init.tcl */
414  Tcl_FindExecutable("");
415 #endif
416 
417  /*
418  * Override the functions in the Notifier subsystem. See comments above.
419  */
420  notifier.setTimerProc = pltcl_SetTimer;
421  notifier.waitForEventProc = pltcl_WaitForEvent;
422  notifier.createFileHandlerProc = pltcl_CreateFileHandler;
423  notifier.deleteFileHandlerProc = pltcl_DeleteFileHandler;
424  notifier.initNotifierProc = pltcl_InitNotifier;
425  notifier.finalizeNotifierProc = pltcl_FinalizeNotifier;
426  notifier.alertNotifierProc = pltcl_AlertNotifier;
427  notifier.serviceModeHookProc = pltcl_ServiceModeHook;
428  Tcl_SetNotifier(&notifier);
429 
430  /************************************************************
431  * Create the dummy hold interpreter to prevent close of
432  * stdout and stderr on DeleteInterp
433  ************************************************************/
434  if ((pltcl_hold_interp = Tcl_CreateInterp()) == NULL)
435  elog(ERROR, "could not create dummy Tcl interpreter");
436  if (Tcl_Init(pltcl_hold_interp) == TCL_ERROR)
437  elog(ERROR, "could not initialize dummy Tcl interpreter");
438 
439  /************************************************************
440  * Create the hash table for working interpreters
441  ************************************************************/
442  memset(&hash_ctl, 0, sizeof(hash_ctl));
443  hash_ctl.keysize = sizeof(Oid);
444  hash_ctl.entrysize = sizeof(pltcl_interp_desc);
445  pltcl_interp_htab = hash_create("PL/Tcl interpreters",
446  8,
447  &hash_ctl,
449 
450  /************************************************************
451  * Create the hash table for function lookup
452  ************************************************************/
453  memset(&hash_ctl, 0, sizeof(hash_ctl));
454  hash_ctl.keysize = sizeof(pltcl_proc_key);
455  hash_ctl.entrysize = sizeof(pltcl_proc_ptr);
456  pltcl_proc_htab = hash_create("PL/Tcl functions",
457  100,
458  &hash_ctl,
460 
461  /************************************************************
462  * Define PL/Tcl's custom GUCs
463  ************************************************************/
464  DefineCustomStringVariable("pltcl.start_proc",
465  gettext_noop("PL/Tcl function to call once when pltcl is first used."),
466  NULL,
468  NULL,
469  PGC_SUSET, 0,
470  NULL, NULL, NULL);
471  DefineCustomStringVariable("pltclu.start_proc",
472  gettext_noop("PL/TclU function to call once when pltclu is first used."),
473  NULL,
475  NULL,
476  PGC_SUSET, 0,
477  NULL, NULL, NULL);
478 
479  pltcl_pm_init_done = true;
480 }
#define TEXTDOMAIN
Definition: pltcl.c:61
struct pltcl_proc_ptr pltcl_proc_ptr
#define HASH_ELEM
Definition: hsearch.h:85
struct pltcl_proc_key pltcl_proc_key
static void pltcl_DeleteFileHandler(int fd)
Definition: pltcl.c:376
Size entrysize
Definition: hsearch.h:72
#define gettext_noop(x)
Definition: c.h:1139
static void pltcl_ServiceModeHook(int mode)
Definition: pltcl.c:381
struct pltcl_interp_desc pltcl_interp_desc
unsigned int Oid
Definition: postgres_ext.h:31
static void pltcl_CreateFileHandler(int fd, int mask, Tcl_FileProc *proc, ClientData clientData)
Definition: pltcl.c:370
static void pltcl_AlertNotifier(ClientData clientData)
Definition: pltcl.c:365
static bool pltcl_pm_init_done
Definition: pltcl.c:239
static char * pltcl_start_proc
Definition: pltcl.c:237
static int pltcl_WaitForEvent(CONST86 Tcl_Time *timePtr)
Definition: pltcl.c:386
#define ERROR
Definition: elog.h:43
static ClientData pltcl_InitNotifier(void)
Definition: pltcl.c:347
Definition: guc.h:75
static void pltcl_SetTimer(CONST86 Tcl_Time *timePtr)
Definition: pltcl.c:360
static Tcl_Interp * pltcl_hold_interp
Definition: pltcl.c:240
#define HASH_BLOBS
Definition: hsearch.h:86
void DefineCustomStringVariable(const char *name, const char *short_desc, const char *long_desc, char **valueAddr, const char *bootValue, GucContext context, int flags, GucStringCheckHook check_hook, GucStringAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:8914
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:326
Size keysize
Definition: hsearch.h:71
static HTAB * pltcl_proc_htab
Definition: pltcl.c:242
static void pltcl_FinalizeNotifier(ClientData clientData)
Definition: pltcl.c:355
#define elog(elevel,...)
Definition: elog.h:214
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1681
static HTAB * pltcl_interp_htab
Definition: pltcl.c:241
static char * pltclu_start_proc
Definition: pltcl.c:238

◆ call_pltcl_start_proc()

static void call_pltcl_start_proc ( Oid  prolang,
bool  pltrusted 
)
static

Definition at line 589 of file pltcl.c.

References ACL_EXECUTE, aclcheck_error(), ACLCHECK_OK, ErrorContextCallback::arg, ErrorContextCallback::callback, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, fmgr_info(), FunctionCallInvoke, GETSTRUCT, GetUserId(), HeapTupleIsValid, InitFunctionCallInfoData, InvalidOid, InvokeFunctionExecuteHook, LOCAL_FCINFO, LookupFuncName(), OBJECT_FUNCTION, ObjectIdGetDatum, pg_proc_aclcheck(), pgstat_end_function_usage(), pgstat_init_function_usage(), pltcl_start_proc, pltclu_start_proc, ErrorContextCallback::previous, PROCOID, ReleaseSysCache(), SearchSysCache1(), start_proc_error_callback(), stringToQualifiedNameList(), and unconstify.

Referenced by pltcl_init_interp().

590 {
591  LOCAL_FCINFO(fcinfo, 0);
592  char *start_proc;
593  const char *gucname;
594  ErrorContextCallback errcallback;
595  List *namelist;
596  Oid procOid;
597  HeapTuple procTup;
598  Form_pg_proc procStruct;
599  AclResult aclresult;
600  FmgrInfo finfo;
601  PgStat_FunctionCallUsage fcusage;
602 
603  /* select appropriate GUC */
604  start_proc = pltrusted ? pltcl_start_proc : pltclu_start_proc;
605  gucname = pltrusted ? "pltcl.start_proc" : "pltclu.start_proc";
606 
607  /* Nothing to do if it's empty or unset */
608  if (start_proc == NULL || start_proc[0] == '\0')
609  return;
610 
611  /* Set up errcontext callback to make errors more helpful */
612  errcallback.callback = start_proc_error_callback;
613  errcallback.arg = unconstify(char *, gucname);
614  errcallback.previous = error_context_stack;
615  error_context_stack = &errcallback;
616 
617  /* Parse possibly-qualified identifier and look up the function */
618  namelist = stringToQualifiedNameList(start_proc);
619  procOid = LookupFuncName(namelist, 0, NULL, false);
620 
621  /* Current user must have permission to call function */
622  aclresult = pg_proc_aclcheck(procOid, GetUserId(), ACL_EXECUTE);
623  if (aclresult != ACLCHECK_OK)
624  aclcheck_error(aclresult, OBJECT_FUNCTION, start_proc);
625 
626  /* Get the function's pg_proc entry */
627  procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(procOid));
628  if (!HeapTupleIsValid(procTup))
629  elog(ERROR, "cache lookup failed for function %u", procOid);
630  procStruct = (Form_pg_proc) GETSTRUCT(procTup);
631 
632  /* It must be same language as the function we're currently calling */
633  if (procStruct->prolang != prolang)
634  ereport(ERROR,
635  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
636  errmsg("function \"%s\" is in the wrong language",
637  start_proc)));
638 
639  /*
640  * It must not be SECURITY DEFINER, either. This together with the
641  * language match check ensures that the function will execute in the same
642  * Tcl interpreter we just finished initializing.
643  */
644  if (procStruct->prosecdef)
645  ereport(ERROR,
646  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
647  errmsg("function \"%s\" must not be SECURITY DEFINER",
648  start_proc)));
649 
650  /* A-OK */
651  ReleaseSysCache(procTup);
652 
653  /*
654  * Call the function using the normal SQL function call mechanism. We
655  * could perhaps cheat and jump directly to pltcl_handler(), but it seems
656  * better to do it this way so that the call is exposed to, eg, call
657  * statistics collection.
658  */
659  InvokeFunctionExecuteHook(procOid);
660  fmgr_info(procOid, &finfo);
661  InitFunctionCallInfoData(*fcinfo, &finfo,
662  0,
663  InvalidOid, NULL, NULL);
664  pgstat_init_function_usage(fcinfo, &fcusage);
665  (void) FunctionCallInvoke(fcinfo);
666  pgstat_end_function_usage(&fcusage, true);
667 
668  /* Pop the error context stack */
669  error_context_stack = errcallback.previous;
670 }
Definition: fmgr.h:56
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:476
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
static char * pltcl_start_proc
Definition: pltcl.c:237
ErrorContextCallback * error_context_stack
Definition: elog.c:92
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
void pgstat_init_function_usage(FunctionCallInfo fcinfo, PgStat_FunctionCallUsage *fcu)
Definition: pgstat.c:1786
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2103
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
#define InvokeFunctionExecuteHook(objectId)
Definition: objectaccess.h:191
#define unconstify(underlying_type, expr)
Definition: c.h:1185
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
AclResult
Definition: acl.h:177
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
static void start_proc_error_callback(void *arg)
Definition: pltcl.c:676
void pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
Definition: pgstat.c:1858
List * stringToQualifiedNameList(const char *string)
Definition: regproc.c:1876
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define ACL_EXECUTE
Definition: parsenodes.h:81
#define elog(elevel,...)
Definition: elog.h:214
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4587
static char * pltclu_start_proc
Definition: pltcl.c:238
Definition: pg_list.h:50

◆ compile_pltcl_function()

static pltcl_proc_desc * compile_pltcl_function ( Oid  fn_oid,
Oid  tgreloid,
bool  is_event_trigger,
bool  pltrusted 
)
static

Definition at line 1386 of file pltcl.c.

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, pltcl_proc_desc::arg_is_rowtype, pltcl_proc_desc::arg_out_func, Assert, buf, pltcl_proc_desc::domain_info, elog, ereport, errcode(), errmsg(), ERROR, fmgr_info_cxt(), pltcl_proc_desc::fn_cxt, pltcl_proc_desc::fn_readonly, pltcl_proc_desc::fn_refcount, pltcl_proc_desc::fn_retisdomain, pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, pltcl_proc_desc::fn_tid, pltcl_proc_desc::fn_xmin, format_type_be(), FUNC_MAX_ARGS, GETSTRUCT, getTypeIOParam(), GetUserId(), HASH_ENTER, hash_search(), HeapTupleHeaderGetRawXmin, HeapTupleIsValid, i, pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, InvalidOid, pltcl_proc_key::is_trigger, ItemPointerEquals(), pltcl_proc_desc::lanpltrusted, MemoryContextDelete(), MemoryContextSetIdentifier(), MemoryContextSwitchTo(), NameStr, pltcl_proc_desc::nargs, ObjectIdGetDatum, OidIsValid, palloc0(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pltcl_fetch_interp(), pltcl_proc_key::proc_id, pltcl_proc_ptr::proc_ptr, PROCOID, pstrdup(), ReleaseSysCache(), pltcl_proc_desc::result_in_func, pltcl_proc_desc::result_typid, pltcl_proc_desc::result_typioparam, SearchSysCache1(), snprintf, SysCacheGetAttr(), HeapTupleData::t_data, HeapTupleData::t_self, TextDatumGetCString, TopMemoryContext, type_is_rowtype(), TYPEOID, pltcl_proc_key::user_id, pltcl_proc_desc::user_proname, UTF_BEGIN, UTF_E2U, UTF_END, and utf_u2e().

Referenced by pltcl_event_trigger_handler(), pltcl_func_handler(), and pltcl_trigger_handler().

1388 {
1389  HeapTuple procTup;
1390  Form_pg_proc procStruct;
1391  pltcl_proc_key proc_key;
1392  pltcl_proc_ptr *proc_ptr;
1393  bool found;
1394  pltcl_proc_desc *prodesc;
1395  pltcl_proc_desc *old_prodesc;
1396  volatile MemoryContext proc_cxt = NULL;
1397  Tcl_DString proc_internal_def;
1398  Tcl_DString proc_internal_body;
1399 
1400  /* We'll need the pg_proc tuple in any case... */
1401  procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
1402  if (!HeapTupleIsValid(procTup))
1403  elog(ERROR, "cache lookup failed for function %u", fn_oid);
1404  procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1405 
1406  /*
1407  * Look up function in pltcl_proc_htab; if it's not there, create an entry
1408  * and set the entry's proc_ptr to NULL.
1409  */
1410  proc_key.proc_id = fn_oid;
1411  proc_key.is_trigger = OidIsValid(tgreloid);
1412  proc_key.user_id = pltrusted ? GetUserId() : InvalidOid;
1413 
1414  proc_ptr = hash_search(pltcl_proc_htab, &proc_key,
1415  HASH_ENTER,
1416  &found);
1417  if (!found)
1418  proc_ptr->proc_ptr = NULL;
1419 
1420  prodesc = proc_ptr->proc_ptr;
1421 
1422  /************************************************************
1423  * If it's present, must check whether it's still up to date.
1424  * This is needed because CREATE OR REPLACE FUNCTION can modify the
1425  * function's pg_proc entry without changing its OID.
1426  ************************************************************/
1427  if (prodesc != NULL &&
1428  prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
1429  ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self))
1430  {
1431  /* It's still up-to-date, so we can use it */
1432  ReleaseSysCache(procTup);
1433  return prodesc;
1434  }
1435 
1436  /************************************************************
1437  * If we haven't found it in the hashtable, we analyze
1438  * the functions arguments and returntype and store
1439  * the in-/out-functions in the prodesc block and create
1440  * a new hashtable entry for it.
1441  *
1442  * Then we load the procedure into the Tcl interpreter.
1443  ************************************************************/
1444  Tcl_DStringInit(&proc_internal_def);
1445  Tcl_DStringInit(&proc_internal_body);
1446  PG_TRY();
1447  {
1448  bool is_trigger = OidIsValid(tgreloid);
1449  char internal_proname[128];
1450  HeapTuple typeTup;
1451  Form_pg_type typeStruct;
1452  char proc_internal_args[33 * FUNC_MAX_ARGS];
1453  Datum prosrcdatum;
1454  bool isnull;
1455  char *proc_source;
1456  char buf[48];
1457  Tcl_Interp *interp;
1458  int i;
1459  int tcl_rc;
1460  MemoryContext oldcontext;
1461 
1462  /************************************************************
1463  * Build our internal proc name from the function's Oid. Append
1464  * "_trigger" when appropriate to ensure the normal and trigger
1465  * cases are kept separate. Note name must be all-ASCII.
1466  ************************************************************/
1467  if (is_event_trigger)
1468  snprintf(internal_proname, sizeof(internal_proname),
1469  "__PLTcl_proc_%u_evttrigger", fn_oid);
1470  else if (is_trigger)
1471  snprintf(internal_proname, sizeof(internal_proname),
1472  "__PLTcl_proc_%u_trigger", fn_oid);
1473  else
1474  snprintf(internal_proname, sizeof(internal_proname),
1475  "__PLTcl_proc_%u", fn_oid);
1476 
1477  /************************************************************
1478  * Allocate a context that will hold all PG data for the procedure.
1479  ************************************************************/
1481  "PL/Tcl function",
1483 
1484  /************************************************************
1485  * Allocate and fill a new procedure description block.
1486  * struct prodesc and subsidiary data must all live in proc_cxt.
1487  ************************************************************/
1488  oldcontext = MemoryContextSwitchTo(proc_cxt);
1489  prodesc = (pltcl_proc_desc *) palloc0(sizeof(pltcl_proc_desc));
1490  prodesc->user_proname = pstrdup(NameStr(procStruct->proname));
1491  MemoryContextSetIdentifier(proc_cxt, prodesc->user_proname);
1492  prodesc->internal_proname = pstrdup(internal_proname);
1493  prodesc->fn_cxt = proc_cxt;
1494  prodesc->fn_refcount = 0;
1495  prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
1496  prodesc->fn_tid = procTup->t_self;
1497  prodesc->nargs = procStruct->pronargs;
1498  prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
1499  prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
1500  MemoryContextSwitchTo(oldcontext);
1501 
1502  /* Remember if function is STABLE/IMMUTABLE */
1503  prodesc->fn_readonly =
1504  (procStruct->provolatile != PROVOLATILE_VOLATILE);
1505  /* And whether it is trusted */
1506  prodesc->lanpltrusted = pltrusted;
1507 
1508  /************************************************************
1509  * Identify the interpreter to use for the function
1510  ************************************************************/
1511  prodesc->interp_desc = pltcl_fetch_interp(procStruct->prolang,
1512  prodesc->lanpltrusted);
1513  interp = prodesc->interp_desc->interp;
1514 
1515  /************************************************************
1516  * Get the required information for input conversion of the
1517  * return value.
1518  ************************************************************/
1519  if (!is_trigger && !is_event_trigger)
1520  {
1521  Oid rettype = procStruct->prorettype;
1522 
1523  typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
1524  if (!HeapTupleIsValid(typeTup))
1525  elog(ERROR, "cache lookup failed for type %u", rettype);
1526  typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1527 
1528  /* Disallow pseudotype result, except VOID and RECORD */
1529  if (typeStruct->typtype == TYPTYPE_PSEUDO)
1530  {
1531  if (rettype == VOIDOID ||
1532  rettype == RECORDOID)
1533  /* okay */ ;
1534  else if (rettype == TRIGGEROID ||
1535  rettype == EVTTRIGGEROID)
1536  ereport(ERROR,
1537  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1538  errmsg("trigger functions can only be called as triggers")));
1539  else
1540  ereport(ERROR,
1541  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1542  errmsg("PL/Tcl functions cannot return type %s",
1543  format_type_be(rettype))));
1544  }
1545 
1546  prodesc->result_typid = rettype;
1547  fmgr_info_cxt(typeStruct->typinput,
1548  &(prodesc->result_in_func),
1549  proc_cxt);
1550  prodesc->result_typioparam = getTypeIOParam(typeTup);
1551 
1552  prodesc->fn_retisset = procStruct->proretset;
1553  prodesc->fn_retistuple = type_is_rowtype(rettype);
1554  prodesc->fn_retisdomain = (typeStruct->typtype == TYPTYPE_DOMAIN);
1555  prodesc->domain_info = NULL;
1556 
1557  ReleaseSysCache(typeTup);
1558  }
1559 
1560  /************************************************************
1561  * Get the required information for output conversion
1562  * of all procedure arguments, and set up argument naming info.
1563  ************************************************************/
1564  if (!is_trigger && !is_event_trigger)
1565  {
1566  proc_internal_args[0] = '\0';
1567  for (i = 0; i < prodesc->nargs; i++)
1568  {
1569  Oid argtype = procStruct->proargtypes.values[i];
1570 
1571  typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
1572  if (!HeapTupleIsValid(typeTup))
1573  elog(ERROR, "cache lookup failed for type %u", argtype);
1574  typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1575 
1576  /* Disallow pseudotype argument, except RECORD */
1577  if (typeStruct->typtype == TYPTYPE_PSEUDO &&
1578  argtype != RECORDOID)
1579  ereport(ERROR,
1580  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1581  errmsg("PL/Tcl functions cannot accept type %s",
1582  format_type_be(argtype))));
1583 
1584  if (type_is_rowtype(argtype))
1585  {
1586  prodesc->arg_is_rowtype[i] = true;
1587  snprintf(buf, sizeof(buf), "__PLTcl_Tup_%d", i + 1);
1588  }
1589  else
1590  {
1591  prodesc->arg_is_rowtype[i] = false;
1592  fmgr_info_cxt(typeStruct->typoutput,
1593  &(prodesc->arg_out_func[i]),
1594  proc_cxt);
1595  snprintf(buf, sizeof(buf), "%d", i + 1);
1596  }
1597 
1598  if (i > 0)
1599  strcat(proc_internal_args, " ");
1600  strcat(proc_internal_args, buf);
1601 
1602  ReleaseSysCache(typeTup);
1603  }
1604  }
1605  else if (is_trigger)
1606  {
1607  /* trigger procedure has fixed args */
1608  strcpy(proc_internal_args,
1609  "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");
1610  }
1611  else if (is_event_trigger)
1612  {
1613  /* event trigger procedure has fixed args */
1614  strcpy(proc_internal_args, "TG_event TG_tag");
1615  }
1616 
1617  /************************************************************
1618  * Create the tcl command to define the internal
1619  * procedure
1620  *
1621  * Leave this code as DString - performance is not critical here,
1622  * and we don't want to duplicate the knowledge of the Tcl quoting
1623  * rules that's embedded in Tcl_DStringAppendElement.
1624  ************************************************************/
1625  Tcl_DStringAppendElement(&proc_internal_def, "proc");
1626  Tcl_DStringAppendElement(&proc_internal_def, internal_proname);
1627  Tcl_DStringAppendElement(&proc_internal_def, proc_internal_args);
1628 
1629  /************************************************************
1630  * prefix procedure body with
1631  * upvar #0 <internal_proname> GD
1632  * and with appropriate setting of arguments
1633  ************************************************************/
1634  Tcl_DStringAppend(&proc_internal_body, "upvar #0 ", -1);
1635  Tcl_DStringAppend(&proc_internal_body, internal_proname, -1);
1636  Tcl_DStringAppend(&proc_internal_body, " GD\n", -1);
1637  if (is_trigger)
1638  {
1639  Tcl_DStringAppend(&proc_internal_body,
1640  "array set NEW $__PLTcl_Tup_NEW\n", -1);
1641  Tcl_DStringAppend(&proc_internal_body,
1642  "array set OLD $__PLTcl_Tup_OLD\n", -1);
1643  Tcl_DStringAppend(&proc_internal_body,
1644  "set i 0\n"
1645  "set v 0\n"
1646  "foreach v $args {\n"
1647  " incr i\n"
1648  " set $i $v\n"
1649  "}\n"
1650  "unset i v\n\n", -1);
1651  }
1652  else if (is_event_trigger)
1653  {
1654  /* no argument support for event triggers */
1655  }
1656  else
1657  {
1658  for (i = 0; i < prodesc->nargs; i++)
1659  {
1660  if (prodesc->arg_is_rowtype[i])
1661  {
1662  snprintf(buf, sizeof(buf),
1663  "array set %d $__PLTcl_Tup_%d\n",
1664  i + 1, i + 1);
1665  Tcl_DStringAppend(&proc_internal_body, buf, -1);
1666  }
1667  }
1668  }
1669 
1670  /************************************************************
1671  * Add user's function definition to proc body
1672  ************************************************************/
1673  prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1674  Anum_pg_proc_prosrc, &isnull);
1675  if (isnull)
1676  elog(ERROR, "null prosrc");
1677  proc_source = TextDatumGetCString(prosrcdatum);
1678  UTF_BEGIN;
1679  Tcl_DStringAppend(&proc_internal_body, UTF_E2U(proc_source), -1);
1680  UTF_END;
1681  pfree(proc_source);
1682  Tcl_DStringAppendElement(&proc_internal_def,
1683  Tcl_DStringValue(&proc_internal_body));
1684 
1685  /************************************************************
1686  * Create the procedure in the interpreter
1687  ************************************************************/
1688  tcl_rc = Tcl_EvalEx(interp,
1689  Tcl_DStringValue(&proc_internal_def),
1690  Tcl_DStringLength(&proc_internal_def),
1691  TCL_EVAL_GLOBAL);
1692  if (tcl_rc != TCL_OK)
1693  ereport(ERROR,
1694  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1695  errmsg("could not create internal procedure \"%s\": %s",
1696  internal_proname,
1697  utf_u2e(Tcl_GetStringResult(interp)))));
1698  }
1699  PG_CATCH();
1700  {
1701  /*
1702  * If we failed anywhere above, clean up whatever got allocated. It
1703  * should all be in the proc_cxt, except for the DStrings.
1704  */
1705  if (proc_cxt)
1706  MemoryContextDelete(proc_cxt);
1707  Tcl_DStringFree(&proc_internal_def);
1708  Tcl_DStringFree(&proc_internal_body);
1709  PG_RE_THROW();
1710  }
1711  PG_END_TRY();
1712 
1713  /*
1714  * Install the new proc description block in the hashtable, incrementing
1715  * its refcount (the hashtable link counts as a reference). Then, if
1716  * there was a previous definition of the function, decrement that one's
1717  * refcount, and delete it if no longer referenced. The order of
1718  * operations here is important: if something goes wrong during the
1719  * MemoryContextDelete, leaking some memory for the old definition is OK,
1720  * but we don't want to corrupt the live hashtable entry. (Likewise,
1721  * freeing the DStrings is pretty low priority if that happens.)
1722  */
1723  old_prodesc = proc_ptr->proc_ptr;
1724 
1725  proc_ptr->proc_ptr = prodesc;
1726  prodesc->fn_refcount++;
1727 
1728  if (old_prodesc != NULL)
1729  {
1730  Assert(old_prodesc->fn_refcount > 0);
1731  if (--old_prodesc->fn_refcount == 0)
1732  MemoryContextDelete(old_prodesc->fn_cxt);
1733  }
1734 
1735  Tcl_DStringFree(&proc_internal_def);
1736  Tcl_DStringFree(&proc_internal_body);
1737 
1738  ReleaseSysCache(procTup);
1739 
1740  return prodesc;
1741 }
bool lanpltrusted
Definition: pltcl.c:145
Definition: fmgr.h:56
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
bool fn_retistuple
Definition: pltcl.c:151
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:476
FmgrInfo result_in_func
Definition: pltcl.c:148
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
char * user_proname
Definition: pltcl.c:138
void * domain_info
Definition: pltcl.c:153
int errcode(int sqlerrcode)
Definition: elog.c:610
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
Oid proc_id
Definition: pltcl.c:188
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:652
bool fn_retisdomain
Definition: pltcl.c:152
HeapTupleHeader t_data
Definition: htup.h:68
#define FUNC_MAX_ARGS
void pfree(void *pointer)
Definition: mcxt.c:1057
#define UTF_E2U(x)
Definition: pltcl.c:99
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
FmgrInfo * arg_out_func
Definition: pltcl.c:156
ItemPointerData t_self
Definition: htup.h:65
pltcl_interp_desc * interp_desc
Definition: pltcl.c:146
static char * buf
Definition: pg_test_fsync.c:68
#define UTF_END
Definition: pltcl.c:91
static char * utf_u2e(const char *src)
Definition: pltcl.c:75
ItemPointerData fn_tid
Definition: pltcl.c:143
unsigned long fn_refcount
Definition: pltcl.c:141
Tcl_Interp * interp
Definition: pltcl.c:116
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2543
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
MemoryContext TopMemoryContext
Definition: mcxt.c:44
bool fn_readonly
Definition: pltcl.c:144
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define TextDatumGetCString(d)
Definition: builtins.h:87
void * palloc0(Size size)
Definition: mcxt.c:981
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
Oid result_typioparam
Definition: pltcl.c:149
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define UTF_BEGIN
Definition: pltcl.c:86
char * internal_proname
Definition: pltcl.c:139
#define PG_CATCH()
Definition: elog.h:305
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:746
pltcl_proc_desc * proc_ptr
Definition: pltcl.c:201
Oid is_trigger
Definition: pltcl.c:194
FormData_pg_type * Form_pg_type
Definition: pg_type.h:255
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:330
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:308
#define PG_RE_THROW()
Definition: elog.h:336
static pltcl_interp_desc * pltcl_fetch_interp(Oid prolang, bool pltrusted)
Definition: pltcl.c:559
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
TransactionId fn_xmin
Definition: pltcl.c:142
static HTAB * pltcl_proc_htab
Definition: pltcl.c:242
Oid result_typid
Definition: pltcl.c:147
MemoryContext fn_cxt
Definition: pltcl.c:140
bool fn_retisset
Definition: pltcl.c:150
Oid user_id
Definition: pltcl.c:195
int errmsg(const char *fmt,...)
Definition: elog.c:821
bool * arg_is_rowtype
Definition: pltcl.c:157
#define elog(elevel,...)
Definition: elog.h:214
int i
Oid getTypeIOParam(HeapTuple typeTuple)
Definition: lsyscache.c:2191
#define NameStr(name)
Definition: c.h:623
#define PG_TRY()
Definition: elog.h:295
#define snprintf
Definition: port.h:215
#define PG_END_TRY()
Definition: elog.h:320

◆ PG_FUNCTION_INFO_V1() [1/2]

PG_FUNCTION_INFO_V1 ( pltcl_call_handler  )

◆ PG_FUNCTION_INFO_V1() [2/2]

PG_FUNCTION_INFO_V1 ( pltclu_call_handler  )

◆ pltcl_AlertNotifier()

static void pltcl_AlertNotifier ( ClientData  clientData)
static

Definition at line 365 of file pltcl.c.

Referenced by _PG_init().

366 {
367 }

◆ pltcl_argisnull()

static int pltcl_argisnull ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2052 of file pltcl.c.

References pltcl_call_state::fcinfo, FunctionCallInfoBaseData::nargs, and PG_ARGISNULL.

Referenced by pltcl_init_interp().

2054 {
2055  int argno;
2057 
2058  /************************************************************
2059  * Check call syntax
2060  ************************************************************/
2061  if (objc != 2)
2062  {
2063  Tcl_WrongNumArgs(interp, 1, objv, "argno");
2064  return TCL_ERROR;
2065  }
2066 
2067  /************************************************************
2068  * Check that we're called as a normal function
2069  ************************************************************/
2070  if (fcinfo == NULL)
2071  {
2072  Tcl_SetObjResult(interp,
2073  Tcl_NewStringObj("argisnull cannot be used in triggers", -1));
2074  return TCL_ERROR;
2075  }
2076 
2077  /************************************************************
2078  * Get the argument number
2079  ************************************************************/
2080  if (Tcl_GetIntFromObj(interp, objv[1], &argno) != TCL_OK)
2081  return TCL_ERROR;
2082 
2083  /************************************************************
2084  * Check that the argno is valid
2085  ************************************************************/
2086  argno--;
2087  if (argno < 0 || argno >= fcinfo->nargs)
2088  {
2089  Tcl_SetObjResult(interp,
2090  Tcl_NewStringObj("argno out of range", -1));
2091  return TCL_ERROR;
2092  }
2093 
2094  /************************************************************
2095  * Get the requested NULL state
2096  ************************************************************/
2097  Tcl_SetObjResult(interp, Tcl_NewBooleanObj(PG_ARGISNULL(argno)));
2098  return TCL_OK;
2099 }
FunctionCallInfo fcinfo
Definition: pltcl.c:211
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245
#define PG_ARGISNULL(n)
Definition: fmgr.h:209

◆ pltcl_build_tuple_argument()

static Tcl_Obj * pltcl_build_tuple_argument ( HeapTuple  tuple,
TupleDesc  tupdesc,
bool  include_generated 
)
static

Definition at line 3092 of file pltcl.c.

References attname, getTypeOutputInfo(), heap_getattr, i, NameStr, TupleDescData::natts, OidOutputFunctionCall(), pfree(), TupleDescAttr, UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_func_handler(), and pltcl_trigger_handler().

3093 {
3094  Tcl_Obj *retobj = Tcl_NewObj();
3095  int i;
3096  char *outputstr;
3097  Datum attr;
3098  bool isnull;
3099  char *attname;
3100  Oid typoutput;
3101  bool typisvarlena;
3102 
3103  for (i = 0; i < tupdesc->natts; i++)
3104  {
3105  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3106 
3107  /* ignore dropped attributes */
3108  if (att->attisdropped)
3109  continue;
3110 
3111  if (att->attgenerated)
3112  {
3113  /* don't include unless requested */
3114  if (!include_generated)
3115  continue;
3116  }
3117 
3118  /************************************************************
3119  * Get the attribute name
3120  ************************************************************/
3121  attname = NameStr(att->attname);
3122 
3123  /************************************************************
3124  * Get the attributes value
3125  ************************************************************/
3126  attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3127 
3128  /************************************************************
3129  * If there is a value, append the attribute name and the
3130  * value to the list
3131  *
3132  * Hmmm - Null attributes will cause functions to
3133  * crash if they don't expect them - need something
3134  * smarter here.
3135  ************************************************************/
3136  if (!isnull)
3137  {
3138  getTypeOutputInfo(att->atttypid,
3139  &typoutput, &typisvarlena);
3140  outputstr = OidOutputFunctionCall(typoutput, attr);
3141  UTF_BEGIN;
3142  Tcl_ListObjAppendElement(NULL, retobj,
3143  Tcl_NewStringObj(UTF_E2U(attname), -1));
3144  UTF_END;
3145  UTF_BEGIN;
3146  Tcl_ListObjAppendElement(NULL, retobj,
3147  Tcl_NewStringObj(UTF_E2U(outputstr), -1));
3148  UTF_END;
3149  pfree(outputstr);
3150  }
3151  }
3152 
3153  return retobj;
3154 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2784
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1057
#define UTF_E2U(x)
Definition: pltcl.c:99
NameData attname
Definition: pg_attribute.h:40
#define UTF_END
Definition: pltcl.c:91
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
#define UTF_BEGIN
Definition: pltcl.c:86
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1657
int i
#define NameStr(name)
Definition: c.h:623

◆ pltcl_build_tuple_result()

static HeapTuple pltcl_build_tuple_result ( Tcl_Interp *  interp,
Tcl_Obj **  kvObjv,
int  kvObjc,
pltcl_call_state call_state 
)
static

Definition at line 3168 of file pltcl.c.

References pltcl_call_state::attinmeta, BuildTupleFromCStrings(), domain_check(), pltcl_proc_desc::domain_info, elog, ereport, errcode(), errmsg(), ERROR, pltcl_proc_desc::fn_cxt, pltcl_proc_desc::fn_retisdomain, HeapTupleGetDatum, i, TupleDescData::natts, palloc0(), pltcl_call_state::prodesc, RelationGetDescr, pltcl_proc_desc::result_typid, pltcl_call_state::ret_tupdesc, SPI_ERROR_NOATTRIBUTE, SPI_fnumber(), TriggerData::tg_relation, pltcl_call_state::trigdata, TupleDescAttr, TupleDescGetAttInMetadata(), utf_u2e(), and values.

Referenced by pltcl_func_handler(), pltcl_returnnext(), and pltcl_trigger_handler().

3170 {
3171  HeapTuple tuple;
3172  TupleDesc tupdesc;
3173  AttInMetadata *attinmeta;
3174  char **values;
3175  int i;
3176 
3177  if (call_state->ret_tupdesc)
3178  {
3179  tupdesc = call_state->ret_tupdesc;
3180  attinmeta = call_state->attinmeta;
3181  }
3182  else if (call_state->trigdata)
3183  {
3184  tupdesc = RelationGetDescr(call_state->trigdata->tg_relation);
3185  attinmeta = TupleDescGetAttInMetadata(tupdesc);
3186  }
3187  else
3188  {
3189  elog(ERROR, "PL/Tcl function does not return a tuple");
3190  tupdesc = NULL; /* keep compiler quiet */
3191  attinmeta = NULL;
3192  }
3193 
3194  values = (char **) palloc0(tupdesc->natts * sizeof(char *));
3195 
3196  if (kvObjc % 2 != 0)
3197  ereport(ERROR,
3198  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3199  errmsg("column name/value list must have even number of elements")));
3200 
3201  for (i = 0; i < kvObjc; i += 2)
3202  {
3203  char *fieldName = utf_u2e(Tcl_GetString(kvObjv[i]));
3204  int attn = SPI_fnumber(tupdesc, fieldName);
3205 
3206  /*
3207  * We silently ignore ".tupno", if it's present but doesn't match any
3208  * actual output column. This allows direct use of a row returned by
3209  * pltcl_set_tuple_values().
3210  */
3211  if (attn == SPI_ERROR_NOATTRIBUTE)
3212  {
3213  if (strcmp(fieldName, ".tupno") == 0)
3214  continue;
3215  ereport(ERROR,
3216  (errcode(ERRCODE_UNDEFINED_COLUMN),
3217  errmsg("column name/value list contains nonexistent column name \"%s\"",
3218  fieldName)));
3219  }
3220 
3221  if (attn <= 0)
3222  ereport(ERROR,
3223  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3224  errmsg("cannot set system attribute \"%s\"",
3225  fieldName)));
3226 
3227  if (TupleDescAttr(tupdesc, attn - 1)->attgenerated)
3228  ereport(ERROR,
3229  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3230  errmsg("cannot set generated column \"%s\"",
3231  fieldName)));
3232 
3233  values[attn - 1] = utf_u2e(Tcl_GetString(kvObjv[i + 1]));
3234  }
3235 
3236  tuple = BuildTupleFromCStrings(attinmeta, values);
3237 
3238  /* if result type is domain-over-composite, check domain constraints */
3239  if (call_state->prodesc->fn_retisdomain)
3240  domain_check(HeapTupleGetDatum(tuple), false,
3241  call_state->prodesc->result_typid,
3242  &call_state->prodesc->domain_info,
3243  call_state->prodesc->fn_cxt);
3244 
3245  return tuple;
3246 }
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:1024
#define RelationGetDescr(relation)
Definition: rel.h:482
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void * domain_info
Definition: pltcl.c:153
int errcode(int sqlerrcode)
Definition: elog.c:610
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2116
bool fn_retisdomain
Definition: pltcl.c:152
AttInMetadata * attinmeta
Definition: pltcl.c:225
#define ERROR
Definition: elog.h:43
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:47
static char * utf_u2e(const char *src)
Definition: pltcl.c:75
TupleDesc ret_tupdesc
Definition: pltcl.c:224
void * palloc0(Size size)
Definition: mcxt.c:981
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
void domain_check(Datum value, bool isnull, Oid domainType, void **extra, MemoryContext mcxt)
Definition: domains.c:327
#define ereport(elevel,...)
Definition: elog.h:144
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
Oid result_typid
Definition: pltcl.c:147
static Datum values[MAXATTR]
Definition: bootstrap.c:165
MemoryContext fn_cxt
Definition: pltcl.c:140
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
int i
TriggerData * trigdata
Definition: pltcl.c:214
Relation tg_relation
Definition: trigger.h:34

◆ pltcl_call_handler()

Datum pltcl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 696 of file pltcl.c.

References PG_FUNCTION_INFO_V1(), pltcl_handler(), and pltclu_call_handler().

Referenced by start_proc_error_callback().

697 {
698  return pltcl_handler(fcinfo, true);
699 }
static Datum pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted)
Definition: pltcl.c:719

◆ pltcl_commit()

static int pltcl_commit ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2925 of file pltcl.c.

References CopyErrorData(), CurrentMemoryContext, FlushErrorState(), FreeErrorData(), MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_construct_errorCode(), SPI_commit(), SPI_start_transaction(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_init_interp().

2927 {
2928  MemoryContext oldcontext = CurrentMemoryContext;
2929 
2930  PG_TRY();
2931  {
2932  SPI_commit();
2934  }
2935  PG_CATCH();
2936  {
2937  ErrorData *edata;
2938 
2939  /* Save error info */
2940  MemoryContextSwitchTo(oldcontext);
2941  edata = CopyErrorData();
2942  FlushErrorState();
2943 
2944  /* Pass the error data to Tcl */
2945  pltcl_construct_errorCode(interp, edata);
2946  UTF_BEGIN;
2947  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2948  UTF_END;
2949  FreeErrorData(edata);
2950 
2951  return TCL_ERROR;
2952  }
2953  PG_END_TRY();
2954 
2955  return TCL_OK;
2956 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1471
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void FlushErrorState(void)
Definition: elog.c:1565
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1527
#define UTF_E2U(x)
Definition: pltcl.c:99
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1835
#define UTF_END
Definition: pltcl.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void SPI_commit(void)
Definition: spi.c:279
#define UTF_BEGIN
Definition: pltcl.c:86
#define PG_CATCH()
Definition: elog.h:305
void SPI_start_transaction(void)
Definition: spi.c:213
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
char * message
Definition: elog.h:365

◆ pltcl_construct_errorCode()

static void pltcl_construct_errorCode ( Tcl_Interp *  interp,
ErrorData edata 
)
static

Definition at line 1835 of file pltcl.c.

References ErrorData::column_name, ErrorData::constraint_name, ErrorData::context, ErrorData::datatype_name, ErrorData::detail, ErrorData::filename, ErrorData::funcname, ErrorData::hint, ErrorData::internalpos, ErrorData::internalquery, ErrorData::lineno, ErrorData::message, pltcl_get_condition_name(), ErrorData::schema_name, ErrorData::sqlerrcode, ErrorData::table_name, unpack_sql_state(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_commit(), pltcl_elog(), pltcl_rollback(), and pltcl_subtrans_abort().

1836 {
1837  Tcl_Obj *obj = Tcl_NewObj();
1838 
1839  Tcl_ListObjAppendElement(interp, obj,
1840  Tcl_NewStringObj("POSTGRES", -1));
1841  Tcl_ListObjAppendElement(interp, obj,
1842  Tcl_NewStringObj(PG_VERSION, -1));
1843  Tcl_ListObjAppendElement(interp, obj,
1844  Tcl_NewStringObj("SQLSTATE", -1));
1845  Tcl_ListObjAppendElement(interp, obj,
1846  Tcl_NewStringObj(unpack_sql_state(edata->sqlerrcode), -1));
1847  Tcl_ListObjAppendElement(interp, obj,
1848  Tcl_NewStringObj("condition", -1));
1849  Tcl_ListObjAppendElement(interp, obj,
1850  Tcl_NewStringObj(pltcl_get_condition_name(edata->sqlerrcode), -1));
1851  Tcl_ListObjAppendElement(interp, obj,
1852  Tcl_NewStringObj("message", -1));
1853  UTF_BEGIN;
1854  Tcl_ListObjAppendElement(interp, obj,
1855  Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1856  UTF_END;
1857  if (edata->detail)
1858  {
1859  Tcl_ListObjAppendElement(interp, obj,
1860  Tcl_NewStringObj("detail", -1));
1861  UTF_BEGIN;
1862  Tcl_ListObjAppendElement(interp, obj,
1863  Tcl_NewStringObj(UTF_E2U(edata->detail), -1));
1864  UTF_END;
1865  }
1866  if (edata->hint)
1867  {
1868  Tcl_ListObjAppendElement(interp, obj,
1869  Tcl_NewStringObj("hint", -1));
1870  UTF_BEGIN;
1871  Tcl_ListObjAppendElement(interp, obj,
1872  Tcl_NewStringObj(UTF_E2U(edata->hint), -1));
1873  UTF_END;
1874  }
1875  if (edata->context)
1876  {
1877  Tcl_ListObjAppendElement(interp, obj,
1878  Tcl_NewStringObj("context", -1));
1879  UTF_BEGIN;
1880  Tcl_ListObjAppendElement(interp, obj,
1881  Tcl_NewStringObj(UTF_E2U(edata->context), -1));
1882  UTF_END;
1883  }
1884  if (edata->schema_name)
1885  {
1886  Tcl_ListObjAppendElement(interp, obj,
1887  Tcl_NewStringObj("schema", -1));
1888  UTF_BEGIN;
1889  Tcl_ListObjAppendElement(interp, obj,
1890  Tcl_NewStringObj(UTF_E2U(edata->schema_name), -1));
1891  UTF_END;
1892  }
1893  if (edata->table_name)
1894  {
1895  Tcl_ListObjAppendElement(interp, obj,
1896  Tcl_NewStringObj("table", -1));
1897  UTF_BEGIN;
1898  Tcl_ListObjAppendElement(interp, obj,
1899  Tcl_NewStringObj(UTF_E2U(edata->table_name), -1));
1900  UTF_END;
1901  }
1902  if (edata->column_name)
1903  {
1904  Tcl_ListObjAppendElement(interp, obj,
1905  Tcl_NewStringObj("column", -1));
1906  UTF_BEGIN;
1907  Tcl_ListObjAppendElement(interp, obj,
1908  Tcl_NewStringObj(UTF_E2U(edata->column_name), -1));
1909  UTF_END;
1910  }
1911  if (edata->datatype_name)
1912  {
1913  Tcl_ListObjAppendElement(interp, obj,
1914  Tcl_NewStringObj("datatype", -1));
1915  UTF_BEGIN;
1916  Tcl_ListObjAppendElement(interp, obj,
1917  Tcl_NewStringObj(UTF_E2U(edata->datatype_name), -1));
1918  UTF_END;
1919  }
1920  if (edata->constraint_name)
1921  {
1922  Tcl_ListObjAppendElement(interp, obj,
1923  Tcl_NewStringObj("constraint", -1));
1924  UTF_BEGIN;
1925  Tcl_ListObjAppendElement(interp, obj,
1926  Tcl_NewStringObj(UTF_E2U(edata->constraint_name), -1));
1927  UTF_END;
1928  }
1929  /* cursorpos is never interesting here; report internal query/pos */
1930  if (edata->internalquery)
1931  {
1932  Tcl_ListObjAppendElement(interp, obj,
1933  Tcl_NewStringObj("statement", -1));
1934  UTF_BEGIN;
1935  Tcl_ListObjAppendElement(interp, obj,
1936  Tcl_NewStringObj(UTF_E2U(edata->internalquery), -1));
1937  UTF_END;
1938  }
1939  if (edata->internalpos > 0)
1940  {
1941  Tcl_ListObjAppendElement(interp, obj,
1942  Tcl_NewStringObj("cursor_position", -1));
1943  Tcl_ListObjAppendElement(interp, obj,
1944  Tcl_NewIntObj(edata->internalpos));
1945  }
1946  if (edata->filename)
1947  {
1948  Tcl_ListObjAppendElement(interp, obj,
1949  Tcl_NewStringObj("filename", -1));
1950  UTF_BEGIN;
1951  Tcl_ListObjAppendElement(interp, obj,
1952  Tcl_NewStringObj(UTF_E2U(edata->filename), -1));
1953  UTF_END;
1954  }
1955  if (edata->lineno > 0)
1956  {
1957  Tcl_ListObjAppendElement(interp, obj,
1958  Tcl_NewStringObj("lineno", -1));
1959  Tcl_ListObjAppendElement(interp, obj,
1960  Tcl_NewIntObj(edata->lineno));
1961  }
1962  if (edata->funcname)
1963  {
1964  Tcl_ListObjAppendElement(interp, obj,
1965  Tcl_NewStringObj("funcname", -1));
1966  UTF_BEGIN;
1967  Tcl_ListObjAppendElement(interp, obj,
1968  Tcl_NewStringObj(UTF_E2U(edata->funcname), -1));
1969  UTF_END;
1970  }
1971 
1972  Tcl_SetObjErrorCode(interp, obj);
1973 }
char * schema_name
Definition: elog.h:372
int sqlerrcode
Definition: elog.h:364
const char * funcname
Definition: elog.h:361
char * unpack_sql_state(int sql_state)
Definition: elog.c:2890
int lineno
Definition: elog.h:360
static const char * pltcl_get_condition_name(int sqlstate)
Definition: pltcl.c:1980
char * internalquery
Definition: elog.h:379
#define UTF_E2U(x)
Definition: pltcl.c:99
const char * filename
Definition: elog.h:359
char * table_name
Definition: elog.h:373
#define UTF_END
Definition: pltcl.c:91
int internalpos
Definition: elog.h:378
char * datatype_name
Definition: elog.h:375
char * detail
Definition: elog.h:366
char * column_name
Definition: elog.h:374
#define UTF_BEGIN
Definition: pltcl.c:86
char * hint
Definition: elog.h:368
char * context
Definition: elog.h:369
char * constraint_name
Definition: elog.h:376
char * message
Definition: elog.h:365

◆ pltcl_CreateFileHandler()

static void pltcl_CreateFileHandler ( int  fd,
int  mask,
Tcl_FileProc *  proc,
ClientData  clientData 
)
static

Definition at line 370 of file pltcl.c.

Referenced by _PG_init().

372 {
373 }

◆ pltcl_DeleteFileHandler()

static void pltcl_DeleteFileHandler ( int  fd)
static

Definition at line 376 of file pltcl.c.

Referenced by _PG_init().

377 {
378 }

◆ pltcl_elog()

static int pltcl_elog ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 1748 of file pltcl.c.

References CopyErrorData(), CurrentMemoryContext, DEBUG2, ereport, errcode(), errmsg(), ERROR, FATAL, FlushErrorState(), FreeErrorData(), INFO, LOG, MemoryContextSwitchTo(), ErrorData::message, NOTICE, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_construct_errorCode(), UTF_BEGIN, UTF_E2U, UTF_END, UTF_U2E, and WARNING.

Referenced by pltcl_init_interp().

1750 {
1751  volatile int level;
1752  MemoryContext oldcontext;
1753  int priIndex;
1754 
1755  static const char *logpriorities[] = {
1756  "DEBUG", "LOG", "INFO", "NOTICE",
1757  "WARNING", "ERROR", "FATAL", (const char *) NULL
1758  };
1759 
1760  static const int loglevels[] = {
1761  DEBUG2, LOG, INFO, NOTICE,
1762  WARNING, ERROR, FATAL
1763  };
1764 
1765  if (objc != 3)
1766  {
1767  Tcl_WrongNumArgs(interp, 1, objv, "level msg");
1768  return TCL_ERROR;
1769  }
1770 
1771  if (Tcl_GetIndexFromObj(interp, objv[1], logpriorities, "priority",
1772  TCL_EXACT, &priIndex) != TCL_OK)
1773  return TCL_ERROR;
1774 
1775  level = loglevels[priIndex];
1776 
1777  if (level == ERROR)
1778  {
1779  /*
1780  * We just pass the error back to Tcl. If it's not caught, it'll
1781  * eventually get converted to a PG error when we reach the call
1782  * handler.
1783  */
1784  Tcl_SetObjResult(interp, objv[2]);
1785  return TCL_ERROR;
1786  }
1787 
1788  /*
1789  * For non-error messages, just pass 'em to ereport(). We do not expect
1790  * that this will fail, but just on the off chance it does, report the
1791  * error back to Tcl. Note we are assuming that ereport() can't have any
1792  * internal failures that are so bad as to require a transaction abort.
1793  *
1794  * This path is also used for FATAL errors, which aren't going to come
1795  * back to us at all.
1796  */
1797  oldcontext = CurrentMemoryContext;
1798  PG_TRY();
1799  {
1800  UTF_BEGIN;
1801  ereport(level,
1802  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1803  errmsg("%s", UTF_U2E(Tcl_GetString(objv[2])))));
1804  UTF_END;
1805  }
1806  PG_CATCH();
1807  {
1808  ErrorData *edata;
1809 
1810  /* Must reset elog.c's state */
1811  MemoryContextSwitchTo(oldcontext);
1812  edata = CopyErrorData();
1813  FlushErrorState();
1814 
1815  /* Pass the error data to Tcl */
1816  pltcl_construct_errorCode(interp, edata);
1817  UTF_BEGIN;
1818  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1819  UTF_END;
1820  FreeErrorData(edata);
1821 
1822  return TCL_ERROR;
1823  }
1824  PG_END_TRY();
1825 
1826  return TCL_OK;
1827 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1471
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
#define INFO
Definition: elog.h:33
#define LOG
Definition: elog.h:26
void FlushErrorState(void)
Definition: elog.c:1565
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1527
#define UTF_E2U(x)
Definition: pltcl.c:99
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define DEBUG2
Definition: elog.h:24
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1835
#define UTF_END
Definition: pltcl.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define WARNING
Definition: elog.h:40
#define UTF_U2E(x)
Definition: pltcl.c:96
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define UTF_BEGIN
Definition: pltcl.c:86
#define PG_CATCH()
Definition: elog.h:305
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
char * message
Definition: elog.h:365

◆ pltcl_event_trigger_handler()

static void pltcl_event_trigger_handler ( PG_FUNCTION_ARGS  ,
pltcl_call_state call_state,
bool  pltrusted 
)
static

Definition at line 1306 of file pltcl.c.

References compile_pltcl_function(), elog, ERROR, EventTriggerData::event, pltcl_proc_desc::fn_refcount, GetCommandTagName(), pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, InvalidOid, pltcl_call_state::prodesc, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, EventTriggerData::tag, throw_tcl_error(), pltcl_proc_desc::user_proname, and utf_e2u().

Referenced by pltcl_handler().

1308 {
1309  pltcl_proc_desc *prodesc;
1310  Tcl_Interp *volatile interp;
1311  EventTriggerData *tdata = (EventTriggerData *) fcinfo->context;
1312  Tcl_Obj *tcl_cmd;
1313  int tcl_rc;
1314 
1315  /* Connect to SPI manager */
1316  if (SPI_connect() != SPI_OK_CONNECT)
1317  elog(ERROR, "could not connect to SPI manager");
1318 
1319  /* Find or compile the function */
1320  prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1321  InvalidOid, true, pltrusted);
1322 
1323  call_state->prodesc = prodesc;
1324  prodesc->fn_refcount++;
1325 
1326  interp = prodesc->interp_desc->interp;
1327 
1328  /* Create the tcl command and call the internal proc */
1329  tcl_cmd = Tcl_NewObj();
1330  Tcl_IncrRefCount(tcl_cmd);
1331  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1332  Tcl_NewStringObj(prodesc->internal_proname, -1));
1333  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1334  Tcl_NewStringObj(utf_e2u(tdata->event), -1));
1335  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1336  Tcl_NewStringObj(utf_e2u(GetCommandTagName(tdata->tag)),
1337  -1));
1338 
1339  tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
1340 
1341  /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1342  Tcl_DecrRefCount(tcl_cmd);
1343 
1344  /* Check for errors reported by Tcl. */
1345  if (tcl_rc != TCL_OK)
1346  throw_tcl_error(interp, prodesc->user_proname);
1347 
1348  if (SPI_finish() != SPI_OK_FINISH)
1349  elog(ERROR, "SPI_finish() failed");
1350 }
#define SPI_OK_CONNECT
Definition: spi.h:53
CommandTag tag
Definition: event_trigger.h:29
int SPI_connect(void)
Definition: spi.c:90
int SPI_finish(void)
Definition: spi.c:177
char * user_proname
Definition: pltcl.c:138
static void throw_tcl_error(Tcl_Interp *interp, const char *proname)
Definition: pltcl.c:1357
#define ERROR
Definition: elog.h:43
const char * event
Definition: event_trigger.h:27
pltcl_interp_desc * interp_desc
Definition: pltcl.c:146
unsigned long fn_refcount
Definition: pltcl.c:141
Tcl_Interp * interp
Definition: pltcl.c:116
static pltcl_proc_desc * compile_pltcl_function(Oid fn_oid, Oid tgreloid, bool is_event_trigger, bool pltrusted)
Definition: pltcl.c:1386
static char * utf_e2u(const char *src)
Definition: pltcl.c:81
#define InvalidOid
Definition: postgres_ext.h:36
char * internal_proname
Definition: pltcl.c:139
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
#define SPI_OK_FINISH
Definition: spi.h:54
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:45
#define elog(elevel,...)
Definition: elog.h:214

◆ pltcl_fetch_interp()

static pltcl_interp_desc * pltcl_fetch_interp ( Oid  prolang,
bool  pltrusted 
)
static

Definition at line 559 of file pltcl.c.

References GetUserId(), HASH_ENTER, hash_search(), pltcl_interp_desc::interp, InvalidOid, pltcl_init_interp(), and pltcl_interp_desc::user_id.

Referenced by compile_pltcl_function().

560 {
561  Oid user_id;
562  pltcl_interp_desc *interp_desc;
563  bool found;
564 
565  /* Find or create the interpreter hashtable entry for this userid */
566  if (pltrusted)
567  user_id = GetUserId();
568  else
569  user_id = InvalidOid;
570 
571  interp_desc = hash_search(pltcl_interp_htab, &user_id,
572  HASH_ENTER,
573  &found);
574  if (!found)
575  interp_desc->interp = NULL;
576 
577  /* If we haven't yet successfully made an interpreter, try to do that */
578  if (!interp_desc->interp)
579  pltcl_init_interp(interp_desc, prolang, pltrusted);
580 
581  return interp_desc;
582 }
static void pltcl_init_interp(pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
Definition: pltcl.c:486
Oid GetUserId(void)
Definition: miscinit.c:476
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
unsigned int Oid
Definition: postgres_ext.h:31
Tcl_Interp * interp
Definition: pltcl.c:116
#define InvalidOid
Definition: postgres_ext.h:36
static HTAB * pltcl_interp_htab
Definition: pltcl.c:241

◆ pltcl_FinalizeNotifier()

static void pltcl_FinalizeNotifier ( ClientData  clientData)
static

Definition at line 355 of file pltcl.c.

Referenced by _PG_init().

356 {
357 }

◆ pltcl_func_handler()

static Datum pltcl_func_handler ( PG_FUNCTION_ARGS  ,
pltcl_call_state call_state,
bool  pltrusted 
)
static

Definition at line 793 of file pltcl.c.

References ReturnSetInfo::allowedModes, pltcl_proc_desc::arg_is_rowtype, pltcl_proc_desc::arg_out_func, Assert, pltcl_call_state::attinmeta, castNode, compile_pltcl_function(), CreateTupleDescCopy(), CurrentResourceOwner, DatumGetHeapTupleHeader, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, pltcl_proc_desc::fn_refcount, pltcl_proc_desc::fn_retisdomain, pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, get_call_result_type(), HeapTupleGetDatum, HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, i, InputFunctionCall(), pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, InvalidOid, IsA, lookup_rowtype_tupdesc(), MemoryContextSwitchTo(), pltcl_proc_desc::nargs, OutputFunctionCall(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pltcl_build_tuple_argument(), pltcl_build_tuple_result(), pltcl_call_state::prodesc, ReleaseTupleDesc, pltcl_proc_desc::result_in_func, pltcl_proc_desc::result_typioparam, pltcl_call_state::ret_tupdesc, ReturnSetInfo::returnMode, pltcl_call_state::rsi, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SPI_connect_ext(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OPT_NONATOMIC, HeapTupleData::t_data, HeapTupleData::t_len, throw_tcl_error(), pltcl_call_state::tuple_store, pltcl_call_state::tuple_store_cxt, pltcl_call_state::tuple_store_owner, TupleDescGetAttInMetadata(), TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, TYPEFUNC_RECORD, pltcl_proc_desc::user_proname, UTF_BEGIN, UTF_E2U, UTF_END, and utf_u2e().

Referenced by pltcl_handler().

795 {
796  bool nonatomic;
797  pltcl_proc_desc *prodesc;
798  Tcl_Interp *volatile interp;
799  Tcl_Obj *tcl_cmd;
800  int i;
801  int tcl_rc;
802  Datum retval;
803 
804  nonatomic = fcinfo->context &&
805  IsA(fcinfo->context, CallContext) &&
806  !castNode(CallContext, fcinfo->context)->atomic;
807 
808  /* Connect to SPI manager */
809  if (SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0) != SPI_OK_CONNECT)
810  elog(ERROR, "could not connect to SPI manager");
811 
812  /* Find or compile the function */
813  prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid, InvalidOid,
814  false, pltrusted);
815 
816  call_state->prodesc = prodesc;
817  prodesc->fn_refcount++;
818 
819  interp = prodesc->interp_desc->interp;
820 
821  /*
822  * If we're a SRF, check caller can handle materialize mode, and save
823  * relevant info into call_state. We must ensure that the returned
824  * tuplestore is owned by the caller's context, even if we first create it
825  * inside a subtransaction.
826  */
827  if (prodesc->fn_retisset)
828  {
829  ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
830 
831  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
832  (rsi->allowedModes & SFRM_Materialize) == 0)
833  ereport(ERROR,
834  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
835  errmsg("set-valued function called in context that cannot accept a set")));
836 
837  call_state->rsi = rsi;
838  call_state->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
840  }
841 
842  /************************************************************
843  * Create the tcl command to call the internal
844  * proc in the Tcl interpreter
845  ************************************************************/
846  tcl_cmd = Tcl_NewObj();
847  Tcl_ListObjAppendElement(NULL, tcl_cmd,
848  Tcl_NewStringObj(prodesc->internal_proname, -1));
849 
850  /* We hold a refcount on tcl_cmd just to be sure it stays around */
851  Tcl_IncrRefCount(tcl_cmd);
852 
853  /************************************************************
854  * Add all call arguments to the command
855  ************************************************************/
856  PG_TRY();
857  {
858  for (i = 0; i < prodesc->nargs; i++)
859  {
860  if (prodesc->arg_is_rowtype[i])
861  {
862  /**************************************************
863  * For tuple values, add a list for 'array set ...'
864  **************************************************/
865  if (fcinfo->args[i].isnull)
866  Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
867  else
868  {
869  HeapTupleHeader td;
870  Oid tupType;
871  int32 tupTypmod;
872  TupleDesc tupdesc;
873  HeapTupleData tmptup;
874  Tcl_Obj *list_tmp;
875 
876  td = DatumGetHeapTupleHeader(fcinfo->args[i].value);
877  /* Extract rowtype info and find a tupdesc */
878  tupType = HeapTupleHeaderGetTypeId(td);
879  tupTypmod = HeapTupleHeaderGetTypMod(td);
880  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
881  /* Build a temporary HeapTuple control structure */
883  tmptup.t_data = td;
884 
885  list_tmp = pltcl_build_tuple_argument(&tmptup, tupdesc, true);
886  Tcl_ListObjAppendElement(NULL, tcl_cmd, list_tmp);
887 
888  ReleaseTupleDesc(tupdesc);
889  }
890  }
891  else
892  {
893  /**************************************************
894  * Single values are added as string element
895  * of their external representation
896  **************************************************/
897  if (fcinfo->args[i].isnull)
898  Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
899  else
900  {
901  char *tmp;
902 
903  tmp = OutputFunctionCall(&prodesc->arg_out_func[i],
904  fcinfo->args[i].value);
905  UTF_BEGIN;
906  Tcl_ListObjAppendElement(NULL, tcl_cmd,
907  Tcl_NewStringObj(UTF_E2U(tmp), -1));
908  UTF_END;
909  pfree(tmp);
910  }
911  }
912  }
913  }
914  PG_CATCH();
915  {
916  /* Release refcount to free tcl_cmd */
917  Tcl_DecrRefCount(tcl_cmd);
918  PG_RE_THROW();
919  }
920  PG_END_TRY();
921 
922  /************************************************************
923  * Call the Tcl function
924  *
925  * We assume no PG error can be thrown directly from this call.
926  ************************************************************/
927  tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
928 
929  /* Release refcount to free tcl_cmd (and all subsidiary objects) */
930  Tcl_DecrRefCount(tcl_cmd);
931 
932  /************************************************************
933  * Check for errors reported by Tcl.
934  ************************************************************/
935  if (tcl_rc != TCL_OK)
936  throw_tcl_error(interp, prodesc->user_proname);
937 
938  /************************************************************
939  * Disconnect from SPI manager and then create the return
940  * value datum (if the input function does a palloc for it
941  * this must not be allocated in the SPI memory context
942  * because SPI_finish would free it). But don't try to call
943  * the result_in_func if we've been told to return a NULL;
944  * the Tcl result may not be a valid value of the result type
945  * in that case.
946  ************************************************************/
947  if (SPI_finish() != SPI_OK_FINISH)
948  elog(ERROR, "SPI_finish() failed");
949 
950  if (prodesc->fn_retisset)
951  {
952  ReturnSetInfo *rsi = call_state->rsi;
953 
954  /* We already checked this is OK */
956 
957  /* If we produced any tuples, send back the result */
958  if (call_state->tuple_store)
959  {
960  rsi->setResult = call_state->tuple_store;
961  if (call_state->ret_tupdesc)
962  {
963  MemoryContext oldcxt;
964 
965  oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
966  rsi->setDesc = CreateTupleDescCopy(call_state->ret_tupdesc);
967  MemoryContextSwitchTo(oldcxt);
968  }
969  }
970  retval = (Datum) 0;
971  fcinfo->isnull = true;
972  }
973  else if (fcinfo->isnull)
974  {
975  retval = InputFunctionCall(&prodesc->result_in_func,
976  NULL,
977  prodesc->result_typioparam,
978  -1);
979  }
980  else if (prodesc->fn_retistuple)
981  {
982  TupleDesc td;
983  HeapTuple tup;
984  Tcl_Obj *resultObj;
985  Tcl_Obj **resultObjv;
986  int resultObjc;
987 
988  /*
989  * Set up data about result type. XXX it's tempting to consider
990  * caching this in the prodesc, in the common case where the rowtype
991  * is determined by the function not the calling query. But we'd have
992  * to be able to deal with ADD/DROP/ALTER COLUMN events when the
993  * result type is a named composite type, so it's not exactly trivial.
994  * Maybe worth improving someday.
995  */
996  switch (get_call_result_type(fcinfo, NULL, &td))
997  {
998  case TYPEFUNC_COMPOSITE:
999  /* success */
1000  break;
1002  Assert(prodesc->fn_retisdomain);
1003  break;
1004  case TYPEFUNC_RECORD:
1005  /* failed to determine actual type of RECORD */
1006  ereport(ERROR,
1007  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1008  errmsg("function returning record called in context "
1009  "that cannot accept type record")));
1010  break;
1011  default:
1012  /* result type isn't composite? */
1013  elog(ERROR, "return type must be a row type");
1014  break;
1015  }
1016 
1017  Assert(!call_state->ret_tupdesc);
1018  Assert(!call_state->attinmeta);
1019  call_state->ret_tupdesc = td;
1020  call_state->attinmeta = TupleDescGetAttInMetadata(td);
1021 
1022  /* Convert function result to tuple */
1023  resultObj = Tcl_GetObjResult(interp);
1024  if (Tcl_ListObjGetElements(interp, resultObj, &resultObjc, &resultObjv) == TCL_ERROR)
1025  throw_tcl_error(interp, prodesc->user_proname);
1026 
1027  tup = pltcl_build_tuple_result(interp, resultObjv, resultObjc,
1028  call_state);
1029  retval = HeapTupleGetDatum(tup);
1030  }
1031  else
1032  retval = InputFunctionCall(&prodesc->result_in_func,
1033  utf_u2e(Tcl_GetStringResult(interp)),
1034  prodesc->result_typioparam,
1035  -1);
1036 
1037  return retval;
1038 }
#define SPI_OK_CONNECT
Definition: spi.h:53
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
bool fn_retistuple
Definition: pltcl.c:151
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1710
int SPI_connect_ext(int options)
Definition: spi.c:96
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
FmgrInfo result_in_func
Definition: pltcl.c:148
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
int SPI_finish(void)
Definition: spi.c:177
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
char * user_proname
Definition: pltcl.c:138
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:294
static void throw_tcl_error(Tcl_Interp *interp, const char *proname)
Definition: pltcl.c:1357
ResourceOwner tuple_store_owner
Definition: pltcl.c:230
signed int int32
Definition: c.h:363
bool fn_retisdomain
Definition: pltcl.c:152
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1577
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:468
void pfree(void *pointer)
Definition: mcxt.c:1057
AttInMetadata * attinmeta
Definition: pltcl.c:225
#define UTF_E2U(x)
Definition: pltcl.c:99
#define ERROR
Definition: elog.h:43
FmgrInfo * arg_out_func
Definition: pltcl.c:156
#define SPI_OPT_NONATOMIC
Definition: spi.h:71
ReturnSetInfo * rsi
Definition: pltcl.c:227
pltcl_interp_desc * interp_desc
Definition: pltcl.c:146
uint32 t_len
Definition: htup.h:64
#define UTF_END
Definition: pltcl.c:91
static char * utf_u2e(const char *src)
Definition: pltcl.c:75
unsigned long fn_refcount
Definition: pltcl.c:141
Tcl_Interp * interp
Definition: pltcl.c:116
MemoryContext tuple_store_cxt
Definition: pltcl.c:229
Tuplestorestate * tuple_store
Definition: pltcl.c:228
TupleDesc ret_tupdesc
Definition: pltcl.c:224
static pltcl_proc_desc * compile_pltcl_function(Oid fn_oid, Oid tgreloid, bool is_event_trigger, bool pltrusted)
Definition: pltcl.c:1386
uintptr_t Datum
Definition: postgres.h:367
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:458
Oid result_typioparam
Definition: pltcl.c:149
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1533
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
int allowedModes
Definition: execnodes.h:304
static HeapTuple pltcl_build_tuple_result(Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc, pltcl_call_state *call_state)
Definition: pltcl.c:3168
#define UTF_BEGIN
Definition: pltcl.c:86
char * internal_proname
Definition: pltcl.c:139
SetFunctionReturnMode returnMode
Definition: execnodes.h:306
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:746
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
#define SPI_OK_FINISH
Definition: spi.h:54
#define PG_RE_THROW()
Definition: elog.h:336
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:232
Tuplestorestate * setResult
Definition: execnodes.h:309
ExprContext * econtext
Definition: execnodes.h:302
bool fn_retisset
Definition: pltcl.c:150
TupleDesc setDesc
Definition: execnodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:821
bool * arg_is_rowtype
Definition: pltcl.c:157
#define elog(elevel,...)
Definition: elog.h:214
int i
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
static Tcl_Obj * pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
Definition: pltcl.c:3092
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:452

◆ pltcl_get_condition_name()

static const char * pltcl_get_condition_name ( int  sqlstate)
static

Definition at line 1980 of file pltcl.c.

References i, and TclExceptionNameMap::label.

Referenced by pltcl_construct_errorCode().

1981 {
1982  int i;
1983 
1984  for (i = 0; exception_name_map[i].label != NULL; i++)
1985  {
1986  if (exception_name_map[i].sqlerrstate == sqlstate)
1987  return exception_name_map[i].label;
1988  }
1989  return "unrecognized_sqlstate";
1990 }
static const TclExceptionNameMap exception_name_map[]
Definition: pltcl.c:256
const char * label
Definition: pltcl.c:252
int i

◆ pltcl_handler()

static Datum pltcl_handler ( PG_FUNCTION_ARGS  ,
bool  pltrusted 
)
static

Definition at line 719 of file pltcl.c.

References Assert, CALLED_AS_EVENT_TRIGGER, CALLED_AS_TRIGGER, pltcl_call_state::fcinfo, pltcl_proc_desc::fn_cxt, pltcl_proc_desc::fn_refcount, MemoryContextDelete(), PG_END_TRY, PG_FINALLY, PG_TRY, pltcl_current_call_state, pltcl_event_trigger_handler(), pltcl_func_handler(), pltcl_trigger_handler(), PointerGetDatum, and pltcl_call_state::prodesc.

Referenced by pltcl_call_handler(), and pltclu_call_handler().

720 {
721  Datum retval = (Datum) 0;
722  pltcl_call_state current_call_state;
723  pltcl_call_state *save_call_state;
724 
725  /*
726  * Initialize current_call_state to nulls/zeroes; in particular, set its
727  * prodesc pointer to null. Anything that sets it non-null should
728  * increase the prodesc's fn_refcount at the same time. We'll decrease
729  * the refcount, and then delete the prodesc if it's no longer referenced,
730  * on the way out of this function. This ensures that prodescs live as
731  * long as needed even if somebody replaces the originating pg_proc row
732  * while they're executing.
733  */
734  memset(&current_call_state, 0, sizeof(current_call_state));
735 
736  /*
737  * Ensure that static pointer is saved/restored properly
738  */
739  save_call_state = pltcl_current_call_state;
740  pltcl_current_call_state = &current_call_state;
741 
742  PG_TRY();
743  {
744  /*
745  * Determine if called as function or trigger and call appropriate
746  * subhandler
747  */
748  if (CALLED_AS_TRIGGER(fcinfo))
749  {
750  /* invoke the trigger handler */
751  retval = PointerGetDatum(pltcl_trigger_handler(fcinfo,
752  &current_call_state,
753  pltrusted));
754  }
755  else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
756  {
757  /* invoke the event trigger handler */
758  pltcl_event_trigger_handler(fcinfo, &current_call_state, pltrusted);
759  retval = (Datum) 0;
760  }
761  else
762  {
763  /* invoke the regular function handler */
764  current_call_state.fcinfo = fcinfo;
765  retval = pltcl_func_handler(fcinfo, &current_call_state, pltrusted);
766  }
767  }
768  PG_FINALLY();
769  {
770  /* Restore static pointer, then clean up the prodesc refcount if any */
771  /*
772  * (We're being paranoid in case an error is thrown in context
773  * deletion)
774  */
775  pltcl_current_call_state = save_call_state;
776  if (current_call_state.prodesc != NULL)
777  {
778  Assert(current_call_state.prodesc->fn_refcount > 0);
779  if (--current_call_state.prodesc->fn_refcount == 0)
780  MemoryContextDelete(current_call_state.prodesc->fn_cxt);
781  }
782  }
783  PG_END_TRY();
784 
785  return retval;
786 }
#define CALLED_AS_EVENT_TRIGGER(fcinfo)
Definition: event_trigger.h:40
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define PointerGetDatum(X)
Definition: postgres.h:556
FunctionCallInfo fcinfo
Definition: pltcl.c:211
static Datum pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
Definition: pltcl.c:793
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245
static void pltcl_event_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
Definition: pltcl.c:1306
unsigned long fn_refcount
Definition: pltcl.c:141
static HeapTuple pltcl_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
Definition: pltcl.c:1045
#define PG_FINALLY()
Definition: elog.h:312
uintptr_t Datum
Definition: postgres.h:367
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define Assert(condition)
Definition: c.h:746
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
MemoryContext fn_cxt
Definition: pltcl.c:140
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320

◆ pltcl_init_interp()

static void pltcl_init_interp ( pltcl_interp_desc interp_desc,
Oid  prolang,
bool  pltrusted 
)
static

Definition at line 486 of file pltcl.c.

References call_pltcl_start_proc(), elog, ERROR, pltcl_interp_desc::interp, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pltcl_argisnull(), pltcl_commit(), pltcl_elog(), pltcl_hold_interp, pltcl_quote(), pltcl_returnnext(), pltcl_returnnull(), pltcl_rollback(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), pltcl_SPI_prepare(), pltcl_subtransaction(), pltcl_interp_desc::query_hash, snprintf, and pltcl_interp_desc::user_id.

Referenced by pltcl_fetch_interp().

487 {
488  Tcl_Interp *interp;
489  char interpname[32];
490 
491  /************************************************************
492  * Create the Tcl interpreter subsidiary to pltcl_hold_interp.
493  * Note: Tcl automatically does Tcl_Init in the untrusted case,
494  * and it's not wanted in the trusted case.
495  ************************************************************/
496  snprintf(interpname, sizeof(interpname), "subsidiary_%u", interp_desc->user_id);
497  if ((interp = Tcl_CreateSlave(pltcl_hold_interp, interpname,
498  pltrusted ? 1 : 0)) == NULL)
499  elog(ERROR, "could not create subsidiary Tcl interpreter");
500 
501  /************************************************************
502  * Initialize the query hash table associated with interpreter
503  ************************************************************/
504  Tcl_InitHashTable(&interp_desc->query_hash, TCL_STRING_KEYS);
505 
506  /************************************************************
507  * Install the commands for SPI support in the interpreter
508  ************************************************************/
509  Tcl_CreateObjCommand(interp, "elog",
510  pltcl_elog, NULL, NULL);
511  Tcl_CreateObjCommand(interp, "quote",
512  pltcl_quote, NULL, NULL);
513  Tcl_CreateObjCommand(interp, "argisnull",
514  pltcl_argisnull, NULL, NULL);
515  Tcl_CreateObjCommand(interp, "return_null",
516  pltcl_returnnull, NULL, NULL);
517  Tcl_CreateObjCommand(interp, "return_next",
518  pltcl_returnnext, NULL, NULL);
519  Tcl_CreateObjCommand(interp, "spi_exec",
520  pltcl_SPI_execute, NULL, NULL);
521  Tcl_CreateObjCommand(interp, "spi_prepare",
522  pltcl_SPI_prepare, NULL, NULL);
523  Tcl_CreateObjCommand(interp, "spi_execp",
524  pltcl_SPI_execute_plan, NULL, NULL);
525  Tcl_CreateObjCommand(interp, "subtransaction",
526  pltcl_subtransaction, NULL, NULL);
527  Tcl_CreateObjCommand(interp, "commit",
528  pltcl_commit, NULL, NULL);
529  Tcl_CreateObjCommand(interp, "rollback",
530  pltcl_rollback, NULL, NULL);
531 
532  /************************************************************
533  * Call the appropriate start_proc, if there is one.
534  *
535  * We must set interp_desc->interp before the call, else the start_proc
536  * won't find the interpreter it's supposed to use. But, if the
537  * start_proc fails, we want to abandon use of the interpreter.
538  ************************************************************/
539  PG_TRY();
540  {
541  interp_desc->interp = interp;
542  call_pltcl_start_proc(prolang, pltrusted);
543  }
544  PG_CATCH();
545  {
546  interp_desc->interp = NULL;
547  Tcl_DeleteInterp(interp);
548  PG_RE_THROW();
549  }
550  PG_END_TRY();
551 }
static int pltcl_rollback(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2965
static int pltcl_argisnull(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2052
static int pltcl_commit(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2925
static int pltcl_elog(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:1748
static int pltcl_subtransaction(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2877
static int pltcl_SPI_prepare(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2534
static int pltcl_quote(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:1998
static int pltcl_SPI_execute_plan(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2661
#define ERROR
Definition: elog.h:43
static void call_pltcl_start_proc(Oid prolang, bool pltrusted)
Definition: pltcl.c:589
static Tcl_Interp * pltcl_hold_interp
Definition: pltcl.c:240
Tcl_Interp * interp
Definition: pltcl.c:116
#define PG_CATCH()
Definition: elog.h:305
static int pltcl_returnnext(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2144
#define PG_RE_THROW()
Definition: elog.h:336
#define elog(elevel,...)
Definition: elog.h:214
static int pltcl_returnnull(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2106
#define PG_TRY()
Definition: elog.h:295
#define snprintf
Definition: port.h:215
#define PG_END_TRY()
Definition: elog.h:320
Tcl_HashTable query_hash
Definition: pltcl.c:117
static int pltcl_SPI_execute(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2314

◆ pltcl_init_tuple_store()

static void pltcl_init_tuple_store ( pltcl_call_state call_state)
static

Definition at line 3252 of file pltcl.c.

References ReturnSetInfo::allowedModes, Assert, pltcl_call_state::attinmeta, CurrentResourceOwner, ReturnSetInfo::expectedDesc, MemoryContextSwitchTo(), pltcl_call_state::ret_tupdesc, pltcl_call_state::rsi, SFRM_Materialize_Random, pltcl_call_state::tuple_store, pltcl_call_state::tuple_store_cxt, pltcl_call_state::tuple_store_owner, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), and work_mem.

Referenced by pltcl_returnnext().

3253 {
3254  ReturnSetInfo *rsi = call_state->rsi;
3255  MemoryContext oldcxt;
3256  ResourceOwner oldowner;
3257 
3258  /* Should be in a SRF */
3259  Assert(rsi);
3260  /* Should be first time through */
3261  Assert(!call_state->tuple_store);
3262  Assert(!call_state->attinmeta);
3263 
3264  /* We expect caller to provide an appropriate result tupdesc */
3265  Assert(rsi->expectedDesc);
3266  call_state->ret_tupdesc = rsi->expectedDesc;
3267 
3268  /*
3269  * Switch to the right memory context and resource owner for storing the
3270  * tuplestore. If we're within a subtransaction opened for an exception
3271  * block, for example, we must still create the tuplestore in the resource
3272  * owner that was active when this function was entered, and not in the
3273  * subtransaction's resource owner.
3274  */
3275  oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
3276  oldowner = CurrentResourceOwner;
3278 
3279  call_state->tuple_store =
3281  false, work_mem);
3282 
3283  /* Build attinmeta in this context, too */
3284  call_state->attinmeta = TupleDescGetAttInMetadata(call_state->ret_tupdesc);
3285 
3286  CurrentResourceOwner = oldowner;
3287  MemoryContextSwitchTo(oldcxt);
3288 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ResourceOwner tuple_store_owner
Definition: pltcl.c:230
TupleDesc expectedDesc
Definition: execnodes.h:303
AttInMetadata * attinmeta
Definition: pltcl.c:225
ReturnSetInfo * rsi
Definition: pltcl.c:227
MemoryContext tuple_store_cxt
Definition: pltcl.c:229
Tuplestorestate * tuple_store
Definition: pltcl.c:228
TupleDesc ret_tupdesc
Definition: pltcl.c:224
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
int work_mem
Definition: globals.c:121
int allowedModes
Definition: execnodes.h:304
#define Assert(condition)
Definition: c.h:746

◆ pltcl_InitNotifier()

static ClientData pltcl_InitNotifier ( void  )
static

Definition at line 347 of file pltcl.c.

Referenced by _PG_init().

348 {
349  static int fakeThreadKey; /* To give valid address for ClientData */
350 
351  return (ClientData) &(fakeThreadKey);
352 }

◆ pltcl_process_SPI_result()

static int pltcl_process_SPI_result ( Tcl_Interp *  interp,
const char *  arrayname,
Tcl_Obj *  loop_body,
int  spi_rc,
SPITupleTable tuptable,
uint64  ntuples 
)
static

Definition at line 2423 of file pltcl.c.

References i, pltcl_set_tuple_values(), SPI_freetuptable(), SPI_OK_DELETE, SPI_OK_DELETE_RETURNING, SPI_OK_INSERT, SPI_OK_INSERT_RETURNING, SPI_OK_REWRITTEN, SPI_OK_SELECT, SPI_OK_SELINTO, SPI_OK_UPDATE, SPI_OK_UPDATE_RETURNING, SPI_OK_UTILITY, SPI_result_code_string(), SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by pltcl_SPI_execute(), and pltcl_SPI_execute_plan().

2429 {
2430  int my_rc = TCL_OK;
2431  int loop_rc;
2432  HeapTuple *tuples;
2433  TupleDesc tupdesc;
2434 
2435  switch (spi_rc)
2436  {
2437  case SPI_OK_SELINTO:
2438  case SPI_OK_INSERT:
2439  case SPI_OK_DELETE:
2440  case SPI_OK_UPDATE:
2441  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2442  break;
2443 
2444  case SPI_OK_UTILITY:
2445  case SPI_OK_REWRITTEN:
2446  if (tuptable == NULL)
2447  {
2448  Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
2449  break;
2450  }
2451  /* fall through for utility returning tuples */
2452  /* FALLTHROUGH */
2453 
2454  case SPI_OK_SELECT:
2458 
2459  /*
2460  * Process the tuples we got
2461  */
2462  tuples = tuptable->vals;
2463  tupdesc = tuptable->tupdesc;
2464 
2465  if (loop_body == NULL)
2466  {
2467  /*
2468  * If there is no loop body given, just set the variables from
2469  * the first tuple (if any)
2470  */
2471  if (ntuples > 0)
2472  pltcl_set_tuple_values(interp, arrayname, 0,
2473  tuples[0], tupdesc);
2474  }
2475  else
2476  {
2477  /*
2478  * There is a loop body - process all tuples and evaluate the
2479  * body on each
2480  */
2481  uint64 i;
2482 
2483  for (i = 0; i < ntuples; i++)
2484  {
2485  pltcl_set_tuple_values(interp, arrayname, i,
2486  tuples[i], tupdesc);
2487 
2488  loop_rc = Tcl_EvalObjEx(interp, loop_body, 0);
2489 
2490  if (loop_rc == TCL_OK)
2491  continue;
2492  if (loop_rc == TCL_CONTINUE)
2493  continue;
2494  if (loop_rc == TCL_RETURN)
2495  {
2496  my_rc = TCL_RETURN;
2497  break;
2498  }
2499  if (loop_rc == TCL_BREAK)
2500  break;
2501  my_rc = TCL_ERROR;
2502  break;
2503  }
2504  }
2505 
2506  if (my_rc == TCL_OK)
2507  {
2508  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2509  }
2510  break;
2511 
2512  default:
2513  Tcl_AppendResult(interp, "pltcl: SPI_execute failed: ",
2514  SPI_result_code_string(spi_rc), NULL);
2515  my_rc = TCL_ERROR;
2516  break;
2517  }
2518 
2519  SPI_freetuptable(tuptable);
2520 
2521  return my_rc;
2522 }
#define SPI_OK_DELETE_RETURNING
Definition: spi.h:64
#define SPI_OK_DELETE
Definition: spi.h:60
HeapTuple * vals
Definition: spi.h:26
#define SPI_OK_INSERT_RETURNING
Definition: spi.h:63
const char * SPI_result_code_string(int code)
Definition: spi.c:1815
#define SPI_OK_UTILITY
Definition: spi.h:56
#define SPI_OK_UPDATE_RETURNING
Definition: spi.h:65
#define SPI_OK_REWRITTEN
Definition: spi.h:66
#define SPI_OK_SELINTO
Definition: spi.h:58
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1235
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
#define SPI_OK_UPDATE
Definition: spi.h:61
int i
#define SPI_OK_INSERT
Definition: spi.h:59
static void pltcl_set_tuple_values(Tcl_Interp *interp, const char *arrayname, uint64 tupno, HeapTuple tuple, TupleDesc tupdesc)
Definition: pltcl.c:3006

◆ pltcl_quote()

static int pltcl_quote ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 1998 of file pltcl.c.

References palloc(), and pfree().

Referenced by pltcl_init_interp().

2000 {
2001  char *tmp;
2002  const char *cp1;
2003  char *cp2;
2004  int length;
2005 
2006  /************************************************************
2007  * Check call syntax
2008  ************************************************************/
2009  if (objc != 2)
2010  {
2011  Tcl_WrongNumArgs(interp, 1, objv, "string");
2012  return TCL_ERROR;
2013  }
2014 
2015  /************************************************************
2016  * Allocate space for the maximum the string can
2017  * grow to and initialize pointers
2018  ************************************************************/
2019  cp1 = Tcl_GetStringFromObj(objv[1], &length);
2020  tmp = palloc(length * 2 + 1);
2021  cp2 = tmp;
2022 
2023  /************************************************************
2024  * Walk through string and double every quote and backslash
2025  ************************************************************/
2026  while (*cp1)
2027  {
2028  if (*cp1 == '\'')
2029  *cp2++ = '\'';
2030  else
2031  {
2032  if (*cp1 == '\\')
2033  *cp2++ = '\\';
2034  }
2035  *cp2++ = *cp1++;
2036  }
2037 
2038  /************************************************************
2039  * Terminate the string and set it as result
2040  ************************************************************/
2041  *cp2 = '\0';
2042  Tcl_SetObjResult(interp, Tcl_NewStringObj(tmp, -1));
2043  pfree(tmp);
2044  return TCL_OK;
2045 }
void pfree(void *pointer)
Definition: mcxt.c:1057
void * palloc(Size size)
Definition: mcxt.c:950

◆ pltcl_returnnext()

static int pltcl_returnnext ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2144 of file pltcl.c.

References BeginInternalSubTransaction(), CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, pltcl_call_state::fcinfo, pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, InputFunctionCall(), TupleDescData::natts, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_build_tuple_result(), pltcl_current_call_state, pltcl_init_tuple_store(), pltcl_subtrans_abort(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, pltcl_proc_desc::result_in_func, pltcl_proc_desc::result_typioparam, pltcl_call_state::ret_tupdesc, pltcl_call_state::tuple_store, tuplestore_puttuple(), tuplestore_putvalues(), and utf_u2e().

Referenced by pltcl_init_interp().

2146 {
2148  FunctionCallInfo fcinfo = call_state->fcinfo;
2149  pltcl_proc_desc *prodesc = call_state->prodesc;
2150  MemoryContext oldcontext = CurrentMemoryContext;
2152  volatile int result = TCL_OK;
2153 
2154  /*
2155  * Check that we're called as a set-returning function
2156  */
2157  if (fcinfo == NULL)
2158  {
2159  Tcl_SetObjResult(interp,
2160  Tcl_NewStringObj("return_next cannot be used in triggers", -1));
2161  return TCL_ERROR;
2162  }
2163 
2164  if (!prodesc->fn_retisset)
2165  {
2166  Tcl_SetObjResult(interp,
2167  Tcl_NewStringObj("return_next cannot be used in non-set-returning functions", -1));
2168  return TCL_ERROR;
2169  }
2170 
2171  /*
2172  * Check call syntax
2173  */
2174  if (objc != 2)
2175  {
2176  Tcl_WrongNumArgs(interp, 1, objv, "result");
2177  return TCL_ERROR;
2178  }
2179 
2180  /*
2181  * The rest might throw elog(ERROR), so must run in a subtransaction.
2182  *
2183  * A small advantage of using a subtransaction is that it provides a
2184  * short-lived memory context for free, so we needn't worry about leaking
2185  * memory here. To use that context, call BeginInternalSubTransaction
2186  * directly instead of going through pltcl_subtrans_begin.
2187  */
2189  PG_TRY();
2190  {
2191  /* Set up tuple store if first output row */
2192  if (call_state->tuple_store == NULL)
2193  pltcl_init_tuple_store(call_state);
2194 
2195  if (prodesc->fn_retistuple)
2196  {
2197  Tcl_Obj **rowObjv;
2198  int rowObjc;
2199 
2200  /* result should be a list, so break it down */
2201  if (Tcl_ListObjGetElements(interp, objv[1], &rowObjc, &rowObjv) == TCL_ERROR)
2202  result = TCL_ERROR;
2203  else
2204  {
2205  HeapTuple tuple;
2206 
2207  tuple = pltcl_build_tuple_result(interp, rowObjv, rowObjc,
2208  call_state);
2209  tuplestore_puttuple(call_state->tuple_store, tuple);
2210  }
2211  }
2212  else
2213  {
2214  Datum retval;
2215  bool isNull = false;
2216 
2217  /* for paranoia's sake, check that tupdesc has exactly one column */
2218  if (call_state->ret_tupdesc->natts != 1)
2219  elog(ERROR, "wrong result type supplied in return_next");
2220 
2221  retval = InputFunctionCall(&prodesc->result_in_func,
2222  utf_u2e((char *) Tcl_GetString(objv[1])),
2223  prodesc->result_typioparam,
2224  -1);
2225  tuplestore_putvalues(call_state->tuple_store, call_state->ret_tupdesc,
2226  &retval, &isNull);
2227  }
2228 
2229  pltcl_subtrans_commit(oldcontext, oldowner);
2230  }
2231  PG_CATCH();
2232  {
2233  pltcl_subtrans_abort(interp, oldcontext, oldowner);
2234  return TCL_ERROR;
2235  }
2236  PG_END_TRY();
2237 
2238  return result;
2239 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
bool fn_retistuple
Definition: pltcl.c:151
static void pltcl_subtrans_abort(Tcl_Interp *interp, MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2285
static void pltcl_init_tuple_store(pltcl_call_state *call_state)
Definition: pltcl.c:3252
FmgrInfo result_in_func
Definition: pltcl.c:148
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static void pltcl_subtrans_commit(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2276
FunctionCallInfo fcinfo
Definition: pltcl.c:211
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245
#define ERROR
Definition: elog.h:43
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
static char * utf_u2e(const char *src)
Definition: pltcl.c:75
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Tuplestorestate * tuple_store
Definition: pltcl.c:228
TupleDesc ret_tupdesc
Definition: pltcl.c:224
uintptr_t Datum
Definition: postgres.h:367
Oid result_typioparam
Definition: pltcl.c:149
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1533
static HeapTuple pltcl_build_tuple_result(Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc, pltcl_call_state *call_state)
Definition: pltcl.c:3168
#define PG_CATCH()
Definition: elog.h:305
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4408
bool fn_retisset
Definition: pltcl.c:150
#define elog(elevel,...)
Definition: elog.h:214
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320

◆ pltcl_returnnull()

static int pltcl_returnnull ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2106 of file pltcl.c.

References pltcl_call_state::fcinfo, and FunctionCallInfoBaseData::isnull.

Referenced by pltcl_init_interp().

2108 {
2110 
2111  /************************************************************
2112  * Check call syntax
2113  ************************************************************/
2114  if (objc != 1)
2115  {
2116  Tcl_WrongNumArgs(interp, 1, objv, "");
2117  return TCL_ERROR;
2118  }
2119 
2120  /************************************************************
2121  * Check that we're called as a normal function
2122  ************************************************************/
2123  if (fcinfo == NULL)
2124  {
2125  Tcl_SetObjResult(interp,
2126  Tcl_NewStringObj("return_null cannot be used in triggers", -1));
2127  return TCL_ERROR;
2128  }
2129 
2130  /************************************************************
2131  * Set the NULL return flag and cause Tcl to return from the
2132  * procedure.
2133  ************************************************************/
2134  fcinfo->isnull = true;
2135 
2136  return TCL_RETURN;
2137 }
FunctionCallInfo fcinfo
Definition: pltcl.c:211
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245

◆ pltcl_rollback()

static int pltcl_rollback ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2965 of file pltcl.c.

References CopyErrorData(), CurrentMemoryContext, FlushErrorState(), FreeErrorData(), MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_construct_errorCode(), SPI_rollback(), SPI_start_transaction(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_init_interp().

2967 {
2968  MemoryContext oldcontext = CurrentMemoryContext;
2969 
2970  PG_TRY();
2971  {
2972  SPI_rollback();
2974  }
2975  PG_CATCH();
2976  {
2977  ErrorData *edata;
2978 
2979  /* Save error info */
2980  MemoryContextSwitchTo(oldcontext);
2981  edata = CopyErrorData();
2982  FlushErrorState();
2983 
2984  /* Pass the error data to Tcl */
2985  pltcl_construct_errorCode(interp, edata);
2986  UTF_BEGIN;
2987  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2988  UTF_END;
2989  FreeErrorData(edata);
2990 
2991  return TCL_ERROR;
2992  }
2993  PG_END_TRY();
2994 
2995  return TCL_OK;
2996 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1471
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPI_rollback(void)
Definition: spi.c:334
void FlushErrorState(void)
Definition: elog.c:1565
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1527
#define UTF_E2U(x)
Definition: pltcl.c:99
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1835
#define UTF_END
Definition: pltcl.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define UTF_BEGIN
Definition: pltcl.c:86
#define PG_CATCH()
Definition: elog.h:305
void SPI_start_transaction(void)
Definition: spi.c:213
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
char * message
Definition: elog.h:365

◆ pltcl_ServiceModeHook()

static void pltcl_ServiceModeHook ( int  mode)
static

Definition at line 381 of file pltcl.c.

Referenced by _PG_init().

382 {
383 }

◆ pltcl_set_tuple_values()

static void pltcl_set_tuple_values ( Tcl_Interp *  interp,
const char *  arrayname,
uint64  tupno,
HeapTuple  tuple,
TupleDesc  tupdesc 
)
static

Definition at line 3006 of file pltcl.c.

References attname, getTypeOutputInfo(), heap_getattr, i, NameStr, TupleDescData::natts, OidOutputFunctionCall(), pfree(), pstrdup(), TupleDescAttr, unconstify, UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_process_SPI_result().

3008 {
3009  int i;
3010  char *outputstr;
3011  Datum attr;
3012  bool isnull;
3013  const char *attname;
3014  Oid typoutput;
3015  bool typisvarlena;
3016  const char **arrptr;
3017  const char **nameptr;
3018  const char *nullname = NULL;
3019 
3020  /************************************************************
3021  * Prepare pointers for Tcl_SetVar2Ex() below
3022  ************************************************************/
3023  if (arrayname == NULL)
3024  {
3025  arrptr = &attname;
3026  nameptr = &nullname;
3027  }
3028  else
3029  {
3030  arrptr = &arrayname;
3031  nameptr = &attname;
3032 
3033  /*
3034  * When outputting to an array, fill the ".tupno" element with the
3035  * current tuple number. This will be overridden below if ".tupno" is
3036  * in use as an actual field name in the rowtype.
3037  */
3038  Tcl_SetVar2Ex(interp, arrayname, ".tupno", Tcl_NewWideIntObj(tupno), 0);
3039  }
3040 
3041  for (i = 0; i < tupdesc->natts; i++)
3042  {
3043  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3044 
3045  /* ignore dropped attributes */
3046  if (att->attisdropped)
3047  continue;
3048 
3049  /************************************************************
3050  * Get the attribute name
3051  ************************************************************/
3052  UTF_BEGIN;
3053  attname = pstrdup(UTF_E2U(NameStr(att->attname)));
3054  UTF_END;
3055 
3056  /************************************************************
3057  * Get the attributes value
3058  ************************************************************/
3059  attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3060 
3061  /************************************************************
3062  * If there is a value, set the variable
3063  * If not, unset it
3064  *
3065  * Hmmm - Null attributes will cause functions to
3066  * crash if they don't expect them - need something
3067  * smarter here.
3068  ************************************************************/
3069  if (!isnull)
3070  {
3071  getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3072  outputstr = OidOutputFunctionCall(typoutput, attr);
3073  UTF_BEGIN;
3074  Tcl_SetVar2Ex(interp, *arrptr, *nameptr,
3075  Tcl_NewStringObj(UTF_E2U(outputstr), -1), 0);
3076  UTF_END;
3077  pfree(outputstr);
3078  }
3079  else
3080  Tcl_UnsetVar2(interp, *arrptr, *nameptr, 0);
3081 
3082  pfree(unconstify(char *, attname));
3083  }
3084 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2784
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1187
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1057
#define UTF_E2U(x)
Definition: pltcl.c:99
NameData attname
Definition: pg_attribute.h:40
#define UTF_END
Definition: pltcl.c:91
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
#define unconstify(underlying_type, expr)
Definition: c.h:1185
uintptr_t Datum
Definition: postgres.h:367
#define UTF_BEGIN
Definition: pltcl.c:86
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1657
int i
#define NameStr(name)
Definition: c.h:623

◆ pltcl_SetTimer()

static void pltcl_SetTimer ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 360 of file pltcl.c.

Referenced by _PG_init().

361 {
362 }

◆ pltcl_SPI_execute()

static int pltcl_SPI_execute ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2314 of file pltcl.c.

References CurrentMemoryContext, CurrentResourceOwner, pltcl_proc_desc::fn_readonly, i, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_process_SPI_result(), pltcl_subtrans_abort(), pltcl_subtrans_begin(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, SPI_execute(), SPI_processed, SPI_tuptable, UTF_BEGIN, UTF_END, and UTF_U2E.

Referenced by pltcl_init_interp().

2316 {
2317  int my_rc;
2318  int spi_rc;
2319  int query_idx;
2320  int i;
2321  int optIndex;
2322  int count = 0;
2323  const char *volatile arrayname = NULL;
2324  Tcl_Obj *volatile loop_body = NULL;
2325  MemoryContext oldcontext = CurrentMemoryContext;
2327 
2328  enum options
2329  {
2330  OPT_ARRAY, OPT_COUNT
2331  };
2332 
2333  static const char *options[] = {
2334  "-array", "-count", (const char *) NULL
2335  };
2336 
2337  /************************************************************
2338  * Check the call syntax and get the options
2339  ************************************************************/
2340  if (objc < 2)
2341  {
2342  Tcl_WrongNumArgs(interp, 1, objv,
2343  "?-count n? ?-array name? query ?loop body?");
2344  return TCL_ERROR;
2345  }
2346 
2347  i = 1;
2348  while (i < objc)
2349  {
2350  if (Tcl_GetIndexFromObj(NULL, objv[i], options, NULL,
2351  TCL_EXACT, &optIndex) != TCL_OK)
2352  break;
2353 
2354  if (++i >= objc)
2355  {
2356  Tcl_SetObjResult(interp,
2357  Tcl_NewStringObj("missing argument to -count or -array", -1));
2358  return TCL_ERROR;
2359  }
2360 
2361  switch ((enum options) optIndex)
2362  {
2363  case OPT_ARRAY:
2364  arrayname = Tcl_GetString(objv[i++]);
2365  break;
2366 
2367  case OPT_COUNT:
2368  if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
2369  return TCL_ERROR;
2370  break;
2371  }
2372  }
2373 
2374  query_idx = i;
2375  if (query_idx >= objc || query_idx + 2 < objc)
2376  {
2377  Tcl_WrongNumArgs(interp, query_idx - 1, objv, "query ?loop body?");
2378  return TCL_ERROR;
2379  }
2380 
2381  if (query_idx + 1 < objc)
2382  loop_body = objv[query_idx + 1];
2383 
2384  /************************************************************
2385  * Execute the query inside a sub-transaction, so we can cope with
2386  * errors sanely
2387  ************************************************************/
2388 
2389  pltcl_subtrans_begin(oldcontext, oldowner);
2390 
2391  PG_TRY();
2392  {
2393  UTF_BEGIN;
2394  spi_rc = SPI_execute(UTF_U2E(Tcl_GetString(objv[query_idx])),
2396  UTF_END;
2397 
2398  my_rc = pltcl_process_SPI_result(interp,
2399  arrayname,
2400  loop_body,
2401  spi_rc,
2402  SPI_tuptable,
2403  SPI_processed);
2404 
2405  pltcl_subtrans_commit(oldcontext, oldowner);
2406  }
2407  PG_CATCH();
2408  {
2409  pltcl_subtrans_abort(interp, oldcontext, oldowner);
2410  return TCL_ERROR;
2411  }
2412  PG_END_TRY();
2413 
2414  return my_rc;
2415 }
static void pltcl_subtrans_begin(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2267
static void pltcl_subtrans_abort(Tcl_Interp *interp, MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2285
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
SPITupleTable * SPI_tuptable
Definition: spi.c:46
static void pltcl_subtrans_commit(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2276
uint64 SPI_processed
Definition: spi.c:45
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245
static int pltcl_process_SPI_result(Tcl_Interp *interp, const char *arrayname, Tcl_Obj *loop_body, int spi_rc, SPITupleTable *tuptable, uint64 ntuples)
Definition: pltcl.c:2423
#define UTF_END
Definition: pltcl.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
bool fn_readonly
Definition: pltcl.c:144
#define UTF_U2E(x)
Definition: pltcl.c:96
#define UTF_BEGIN
Definition: pltcl.c:86
#define PG_CATCH()
Definition: elog.h:305
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
int i
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:497

◆ pltcl_SPI_execute_plan()

static int pltcl_SPI_execute_plan ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2661 of file pltcl.c.

References pltcl_query_desc::arginfuncs, pltcl_query_desc::argtypioparams, CurrentMemoryContext, CurrentResourceOwner, pltcl_proc_desc::fn_readonly, i, InputFunctionCall(), pltcl_proc_desc::interp_desc, pltcl_query_desc::nargs, palloc(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_query_desc::plan, pltcl_process_SPI_result(), pltcl_subtrans_abort(), pltcl_subtrans_begin(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, pltcl_interp_desc::query_hash, SPI_execute_plan(), SPI_processed, SPI_tuptable, UTF_BEGIN, UTF_END, and UTF_U2E.

Referenced by pltcl_init_interp().

2663 {
2664  int my_rc;
2665  int spi_rc;
2666  int i;
2667  int j;
2668  int optIndex;
2669  Tcl_HashEntry *hashent;
2670  pltcl_query_desc *qdesc;
2671  const char *nulls = NULL;
2672  const char *arrayname = NULL;
2673  Tcl_Obj *loop_body = NULL;
2674  int count = 0;
2675  int callObjc;
2676  Tcl_Obj **callObjv = NULL;
2677  Datum *argvalues;
2678  MemoryContext oldcontext = CurrentMemoryContext;
2680  Tcl_HashTable *query_hash;
2681 
2682  enum options
2683  {
2684  OPT_ARRAY, OPT_COUNT, OPT_NULLS
2685  };
2686 
2687  static const char *options[] = {
2688  "-array", "-count", "-nulls", (const char *) NULL
2689  };
2690 
2691  /************************************************************
2692  * Get the options and check syntax
2693  ************************************************************/
2694  i = 1;
2695  while (i < objc)
2696  {
2697  if (Tcl_GetIndexFromObj(NULL, objv[i], options, NULL,
2698  TCL_EXACT, &optIndex) != TCL_OK)
2699  break;
2700 
2701  if (++i >= objc)
2702  {
2703  Tcl_SetObjResult(interp,
2704  Tcl_NewStringObj("missing argument to -array, -count or -nulls", -1));
2705  return TCL_ERROR;
2706  }
2707 
2708  switch ((enum options) optIndex)
2709  {
2710  case OPT_ARRAY:
2711  arrayname = Tcl_GetString(objv[i++]);
2712  break;
2713 
2714  case OPT_COUNT:
2715  if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
2716  return TCL_ERROR;
2717  break;
2718 
2719  case OPT_NULLS:
2720  nulls = Tcl_GetString(objv[i++]);
2721  break;
2722  }
2723  }
2724 
2725  /************************************************************
2726  * Get the prepared plan descriptor by its key
2727  ************************************************************/
2728  if (i >= objc)
2729  {
2730  Tcl_SetObjResult(interp,
2731  Tcl_NewStringObj("missing argument to -count or -array", -1));
2732  return TCL_ERROR;
2733  }
2734 
2736 
2737  hashent = Tcl_FindHashEntry(query_hash, Tcl_GetString(objv[i]));
2738  if (hashent == NULL)
2739  {
2740  Tcl_AppendResult(interp, "invalid queryid '", Tcl_GetString(objv[i]), "'", NULL);
2741  return TCL_ERROR;
2742  }
2743  qdesc = (pltcl_query_desc *) Tcl_GetHashValue(hashent);
2744  i++;
2745 
2746  /************************************************************
2747  * If a nulls string is given, check for correct length
2748  ************************************************************/
2749  if (nulls != NULL)
2750  {
2751  if (strlen(nulls) != qdesc->nargs)
2752  {
2753  Tcl_SetObjResult(interp,
2754  Tcl_NewStringObj("length of nulls string doesn't match number of arguments",
2755  -1));
2756  return TCL_ERROR;
2757  }
2758  }
2759 
2760  /************************************************************
2761  * If there was an argtype list on preparation, we need
2762  * an argument value list now
2763  ************************************************************/
2764  if (qdesc->nargs > 0)
2765  {
2766  if (i >= objc)
2767  {
2768  Tcl_SetObjResult(interp,
2769  Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
2770  -1));
2771  return TCL_ERROR;
2772  }
2773 
2774  /************************************************************
2775  * Split the argument values
2776  ************************************************************/
2777  if (Tcl_ListObjGetElements(interp, objv[i++], &callObjc, &callObjv) != TCL_OK)
2778  return TCL_ERROR;
2779 
2780  /************************************************************
2781  * Check that the number of arguments matches
2782  ************************************************************/
2783  if (callObjc != qdesc->nargs)
2784  {
2785  Tcl_SetObjResult(interp,
2786  Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
2787  -1));
2788  return TCL_ERROR;
2789  }
2790  }
2791  else
2792  callObjc = 0;
2793 
2794  /************************************************************
2795  * Get loop body if present
2796  ************************************************************/
2797  if (i < objc)
2798  loop_body = objv[i++];
2799 
2800  if (i != objc)
2801  {
2802  Tcl_WrongNumArgs(interp, 1, objv,
2803  "?-count n? ?-array name? ?-nulls string? "
2804  "query ?args? ?loop body?");
2805  return TCL_ERROR;
2806  }
2807 
2808  /************************************************************
2809  * Execute the plan inside a sub-transaction, so we can cope with
2810  * errors sanely
2811  ************************************************************/
2812 
2813  pltcl_subtrans_begin(oldcontext, oldowner);
2814 
2815  PG_TRY();
2816  {
2817  /************************************************************
2818  * Setup the value array for SPI_execute_plan() using
2819  * the type specific input functions
2820  ************************************************************/
2821  argvalues = (Datum *) palloc(callObjc * sizeof(Datum));
2822 
2823  for (j = 0; j < callObjc; j++)
2824  {
2825  if (nulls && nulls[j] == 'n')
2826  {
2827  argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
2828  NULL,
2829  qdesc->argtypioparams[j],
2830  -1);
2831  }
2832  else
2833  {
2834  UTF_BEGIN;
2835  argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
2836  UTF_U2E(Tcl_GetString(callObjv[j])),
2837  qdesc->argtypioparams[j],
2838  -1);
2839  UTF_END;
2840  }
2841  }
2842 
2843  /************************************************************
2844  * Execute the plan
2845  ************************************************************/
2846  spi_rc = SPI_execute_plan(qdesc->plan, argvalues, nulls,
2848  count);
2849 
2850  my_rc = pltcl_process_SPI_result(interp,
2851  arrayname,
2852  loop_body,
2853  spi_rc,
2854  SPI_tuptable,
2855  SPI_processed);
2856 
2857  pltcl_subtrans_commit(oldcontext, oldowner);
2858  }
2859  PG_CATCH();
2860  {
2861  pltcl_subtrans_abort(interp, oldcontext, oldowner);
2862  return TCL_ERROR;
2863  }
2864  PG_END_TRY();
2865 
2866  return my_rc;
2867 }
static void pltcl_subtrans_begin(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2267
static void pltcl_subtrans_abort(Tcl_Interp *interp, MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2285
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
SPITupleTable * SPI_tuptable
Definition: spi.c:46
static void pltcl_subtrans_commit(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2276
FmgrInfo * arginfuncs
Definition: pltcl.c:170
uint64 SPI_processed
Definition: spi.c:45
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245
pltcl_interp_desc * interp_desc
Definition: pltcl.c:146
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:532
static int pltcl_process_SPI_result(Tcl_Interp *interp, const char *arrayname, Tcl_Obj *loop_body, int spi_rc, SPITupleTable *tuptable, uint64 ntuples)
Definition: pltcl.c:2423
SPIPlanPtr plan
Definition: pltcl.c:167
#define UTF_END
Definition: pltcl.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
bool fn_readonly
Definition: pltcl.c:144
uintptr_t Datum
Definition: postgres.h:367
#define UTF_U2E(x)
Definition: pltcl.c:96
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1533
#define UTF_BEGIN
Definition: pltcl.c:86
#define PG_CATCH()
Definition: elog.h:305
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
Oid * argtypioparams
Definition: pltcl.c:171
void * palloc(Size size)
Definition: mcxt.c:950
int i
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320
Tcl_HashTable query_hash
Definition: pltcl.c:117

◆ pltcl_SPI_prepare()

static int pltcl_SPI_prepare ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2534 of file pltcl.c.

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, pltcl_query_desc::arginfuncs, pltcl_query_desc::argtypes, pltcl_query_desc::argtypioparams, CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, fmgr_info_cxt(), getTypeInputInfo(), i, pltcl_proc_desc::interp_desc, MemoryContextDelete(), MemoryContextSwitchTo(), pltcl_query_desc::nargs, palloc(), palloc0(), parseTypeString(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_query_desc::plan, pltcl_subtrans_abort(), pltcl_subtrans_begin(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, pltcl_query_desc::qname, pltcl_interp_desc::query_hash, snprintf, SPI_keepplan(), SPI_prepare(), TopMemoryContext, UTF_BEGIN, UTF_END, and UTF_U2E.

Referenced by pltcl_init_interp().

2536 {
2537  volatile MemoryContext plan_cxt = NULL;
2538  int nargs;
2539  Tcl_Obj **argsObj;
2540  pltcl_query_desc *qdesc;
2541  int i;
2542  Tcl_HashEntry *hashent;
2543  int hashnew;
2544  Tcl_HashTable *query_hash;
2545  MemoryContext oldcontext = CurrentMemoryContext;
2547 
2548  /************************************************************
2549  * Check the call syntax
2550  ************************************************************/
2551  if (objc != 3)
2552  {
2553  Tcl_WrongNumArgs(interp, 1, objv, "query argtypes");
2554  return TCL_ERROR;
2555  }
2556 
2557  /************************************************************
2558  * Split the argument type list
2559  ************************************************************/
2560  if (Tcl_ListObjGetElements(interp, objv[2], &nargs, &argsObj) != TCL_OK)
2561  return TCL_ERROR;
2562 
2563  /************************************************************
2564  * Allocate the new querydesc structure
2565  *
2566  * struct qdesc and subsidiary data all live in plan_cxt. Note that if the
2567  * function is recompiled for whatever reason, permanent memory leaks
2568  * occur. FIXME someday.
2569  ************************************************************/
2571  "PL/Tcl spi_prepare query",
2573  MemoryContextSwitchTo(plan_cxt);
2574  qdesc = (pltcl_query_desc *) palloc0(sizeof(pltcl_query_desc));
2575  snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
2576  qdesc->nargs = nargs;
2577  qdesc->argtypes = (Oid *) palloc(nargs * sizeof(Oid));
2578  qdesc->arginfuncs = (FmgrInfo *) palloc(nargs * sizeof(FmgrInfo));
2579  qdesc->argtypioparams = (Oid *) palloc(nargs * sizeof(Oid));
2580  MemoryContextSwitchTo(oldcontext);
2581 
2582  /************************************************************
2583  * Execute the prepare inside a sub-transaction, so we can cope with
2584  * errors sanely
2585  ************************************************************/
2586 
2587  pltcl_subtrans_begin(oldcontext, oldowner);
2588 
2589  PG_TRY();
2590  {
2591  /************************************************************
2592  * Resolve argument type names and then look them up by oid
2593  * in the system cache, and remember the required information
2594  * for input conversion.
2595  ************************************************************/
2596  for (i = 0; i < nargs; i++)
2597  {
2598  Oid typId,
2599  typInput,
2600  typIOParam;
2601  int32 typmod;
2602 
2603  parseTypeString(Tcl_GetString(argsObj[i]), &typId, &typmod, false);
2604 
2605  getTypeInputInfo(typId, &typInput, &typIOParam);
2606 
2607  qdesc->argtypes[i] = typId;
2608  fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
2609  qdesc->argtypioparams[i] = typIOParam;
2610  }
2611 
2612  /************************************************************
2613  * Prepare the plan and check for errors
2614  ************************************************************/
2615  UTF_BEGIN;
2616  qdesc->plan = SPI_prepare(UTF_U2E(Tcl_GetString(objv[1])),
2617  nargs, qdesc->argtypes);
2618  UTF_END;
2619 
2620  if (qdesc->plan == NULL)
2621  elog(ERROR, "SPI_prepare() failed");
2622 
2623  /************************************************************
2624  * Save the plan into permanent memory (right now it's in the
2625  * SPI procCxt, which will go away at function end).
2626  ************************************************************/
2627  if (SPI_keepplan(qdesc->plan))
2628  elog(ERROR, "SPI_keepplan() failed");
2629 
2630  pltcl_subtrans_commit(oldcontext, oldowner);
2631  }
2632  PG_CATCH();
2633  {
2634  pltcl_subtrans_abort(interp, oldcontext, oldowner);
2635 
2636  MemoryContextDelete(plan_cxt);
2637 
2638  return TCL_ERROR;
2639  }
2640  PG_END_TRY();
2641 
2642  /************************************************************
2643  * Insert a hashtable entry for the plan and return
2644  * the key to the caller
2645  ************************************************************/
2647 
2648  hashent = Tcl_CreateHashEntry(query_hash, qdesc->qname, &hashnew);
2649  Tcl_SetHashValue(hashent, (ClientData) qdesc);
2650 
2651  /* qname is ASCII, so no need for encoding conversion */
2652  Tcl_SetObjResult(interp, Tcl_NewStringObj(qdesc->qname, -1));
2653  return TCL_OK;
2654 }
static void pltcl_subtrans_begin(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2267
Definition: fmgr.h:56
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
static void pltcl_subtrans_abort(Tcl_Interp *interp, MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2285
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:747
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Oid * argtypes
Definition: pltcl.c:169
static void pltcl_subtrans_commit(MemoryContext oldcontext, ResourceOwner oldowner)
Definition: pltcl.c:2276
FmgrInfo * arginfuncs
Definition: pltcl.c:170
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:245
char qname[20]
Definition: pltcl.c:166
#define ERROR
Definition: elog.h:43
pltcl_interp_desc * interp_desc
Definition: pltcl.c:146
SPIPlanPtr plan
Definition: pltcl.c:167
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:825
#define UTF_END
Definition: pltcl.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2751
MemoryContext TopMemoryContext
Definition: mcxt.c:44
void * palloc0(Size size)
Definition: mcxt.c:981
#define UTF_U2E(x)
Definition: pltcl.c:96
void parseTypeString(const char *str, Oid *typeid_p, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:832
#define UTF_BEGIN
Definition: pltcl.c:86
#define PG_CATCH()
Definition: elog.h:305
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
Oid * argtypioparams
Definition: pltcl.c:171
void * palloc(Size size)
Definition: mcxt.c:950
#define elog(elevel,...)
Definition: elog.h:214
int i
#define PG_TRY()
Definition: elog.h:295
#define snprintf
Definition: port.h:215
#define PG_END_TRY()
Definition: elog.h:320
Tcl_HashTable query_hash
Definition: pltcl.c:117

◆ pltcl_subtrans_abort()

static void pltcl_subtrans_abort ( Tcl_Interp *  interp,
MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2285 of file pltcl.c.

References CopyErrorData(), CurrentResourceOwner, FlushErrorState(), FreeErrorData(), MemoryContextSwitchTo(), ErrorData::message, pltcl_construct_errorCode(), RollbackAndReleaseCurrentSubTransaction(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_returnnext(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

2287 {
2288  ErrorData *edata;
2289 
2290  /* Save error info */
2291  MemoryContextSwitchTo(oldcontext);
2292  edata = CopyErrorData();
2293  FlushErrorState();
2294 
2295  /* Abort the inner transaction */
2297  MemoryContextSwitchTo(oldcontext);
2298  CurrentResourceOwner = oldowner;
2299 
2300  /* Pass the error data to Tcl */
2301  pltcl_construct_errorCode(interp, edata);
2302  UTF_BEGIN;
2303  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2304  UTF_END;
2305  FreeErrorData(edata);
2306 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1471
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void FlushErrorState(void)
Definition: elog.c:1565
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1527
#define UTF_E2U(x)
Definition: pltcl.c:99
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1835
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4513
#define UTF_END
Definition: pltcl.c:91
#define UTF_BEGIN
Definition: pltcl.c:86
char * message
Definition: elog.h:365

◆ pltcl_subtrans_begin()

static void pltcl_subtrans_begin ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2267 of file pltcl.c.

References BeginInternalSubTransaction(), and MemoryContextSwitchTo().

Referenced by pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

2268 {
2270 
2271  /* Want to run inside function's memory context */
2272  MemoryContextSwitchTo(oldcontext);
2273 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4408

◆ pltcl_subtrans_commit()

static void pltcl_subtrans_commit ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2276 of file pltcl.c.

References CurrentResourceOwner, MemoryContextSwitchTo(), and ReleaseCurrentSubTransaction().

Referenced by pltcl_returnnext(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

2277 {
2278  /* Commit the inner transaction, return to outer xact context */
2280  MemoryContextSwitchTo(oldcontext);
2281  CurrentResourceOwner = oldowner;
2282 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4479
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109

◆ pltcl_subtransaction()

static int pltcl_subtransaction ( ClientData  cdata,
Tcl_Interp *  interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2877 of file pltcl.c.

References BeginInternalSubTransaction(), CurrentMemoryContext, CurrentResourceOwner, MemoryContextSwitchTo(), ReleaseCurrentSubTransaction(), and RollbackAndReleaseCurrentSubTransaction().

Referenced by pltcl_init_interp().

2879 {
2880  MemoryContext oldcontext = CurrentMemoryContext;
2882  int retcode;
2883 
2884  if (objc != 2)
2885  {
2886  Tcl_WrongNumArgs(interp, 1, objv, "command");
2887  return TCL_ERROR;
2888  }
2889 
2890  /*
2891  * Note: we don't use pltcl_subtrans_begin and friends here because we
2892  * don't want the error handling in pltcl_subtrans_abort. But otherwise
2893  * the processing should be about the same as in those functions.
2894  */
2896  MemoryContextSwitchTo(oldcontext);
2897 
2898  retcode = Tcl_EvalObjEx(interp, objv[1], 0);
2899 
2900  if (retcode == TCL_ERROR)
2901  {
2902  /* Rollback the subtransaction */
2904  }
2905  else
2906  {
2907  /* Commit the subtransaction */
2909  }
2910 
2911  /* In either case, restore previous memory context and resource owner */
2912  MemoryContextSwitchTo(oldcontext);
2913  CurrentResourceOwner = oldowner;
2914 
2915  return retcode;
2916 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4479
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4513
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4408

◆ pltcl_trigger_handler()

static HeapTuple pltcl_trigger_handler ( PG_FUNCTION_ARGS  ,
pltcl_call_state call_state,
bool  pltrusted 
)
static

Definition at line 1045 of file pltcl.c.

References Assert, compile_pltcl_function(), DatumGetCString, DirectFunctionCall1, elog, ereport, errcode(), errmsg(), ERROR, pltcl_proc_desc::fn_refcount, i, pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, NameStr, TupleDescData::natts, ObjectIdGetDatum, oidout(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PG_USED_FOR_ASSERTS_ONLY, pltcl_build_tuple_argument(), pltcl_build_tuple_result(), pltcl_call_state::prodesc, RelationData::rd_id, RelationGetDescr, RelationGetRelid, SPI_connect(), SPI_finish(), SPI_getnspname(), SPI_getrelname(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_register_trigger_data(), TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, Trigger::tgargs, Trigger::tgname, Trigger::tgnargs, throw_tcl_error(), pltcl_call_state::trigdata, TRIGGER_FIRED_AFTER, TRIGGER_FIRED_BEFORE, TRIGGER_FIRED_BY_DELETE, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_TRUNCATE, TRIGGER_FIRED_BY_UPDATE, TRIGGER_FIRED_FOR_ROW, TRIGGER_FIRED_FOR_STATEMENT, TRIGGER_FIRED_INSTEAD, TupleDescAttr, pltcl_proc_desc::user_proname, utf_e2u(), and utf_u2e().

Referenced by pltcl_handler().

1047 {
1048  pltcl_proc_desc *prodesc;
1049  Tcl_Interp *volatile interp;
1050  TriggerData *trigdata = (TriggerData *) fcinfo->context;
1051  char *stroid;
1052  TupleDesc tupdesc;
1053  volatile HeapTuple rettup;
1054  Tcl_Obj *tcl_cmd;
1055  Tcl_Obj *tcl_trigtup;
1056  int tcl_rc;
1057  int i;
1058  const char *result;
1059  int result_Objc;
1060  Tcl_Obj **result_Objv;
1061  int rc PG_USED_FOR_ASSERTS_ONLY;
1062 
1063  call_state->trigdata = trigdata;
1064 
1065  /* Connect to SPI manager */
1066  if (SPI_connect() != SPI_OK_CONNECT)
1067  elog(ERROR, "could not connect to SPI manager");
1068 
1069  /* Make transition tables visible to this SPI connection */
1070  rc = SPI_register_trigger_data(trigdata);
1071  Assert(rc >= 0);
1072 
1073  /* Find or compile the function */
1074  prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1075  RelationGetRelid(trigdata->tg_relation),
1076  false, /* not an event trigger */
1077  pltrusted);
1078 
1079  call_state->prodesc = prodesc;
1080  prodesc->fn_refcount++;
1081 
1082  interp = prodesc->interp_desc->interp;
1083 
1084  tupdesc = RelationGetDescr(trigdata->tg_relation);
1085 
1086  /************************************************************
1087  * Create the tcl command to call the internal
1088  * proc in the interpreter
1089  ************************************************************/
1090  tcl_cmd = Tcl_NewObj();
1091  Tcl_IncrRefCount(tcl_cmd);
1092 
1093  PG_TRY();
1094  {
1095  /* The procedure name (note this is all ASCII, so no utf_e2u) */
1096  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1097  Tcl_NewStringObj(prodesc->internal_proname, -1));
1098 
1099  /* The trigger name for argument TG_name */
1100  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1101  Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgname), -1));
1102 
1103  /* The oid of the trigger relation for argument TG_relid */
1104  /* Consider not converting to a string for more performance? */
1106  ObjectIdGetDatum(trigdata->tg_relation->rd_id)));
1107  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1108  Tcl_NewStringObj(stroid, -1));
1109  pfree(stroid);
1110 
1111  /* The name of the table the trigger is acting on: TG_table_name */
1112  stroid = SPI_getrelname(trigdata->tg_relation);
1113  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1114  Tcl_NewStringObj(utf_e2u(stroid), -1));
1115  pfree(stroid);
1116 
1117  /* The schema of the table the trigger is acting on: TG_table_schema */
1118  stroid = SPI_getnspname(trigdata->tg_relation);
1119  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1120  Tcl_NewStringObj(utf_e2u(stroid), -1));
1121  pfree(stroid);
1122 
1123  /* A list of attribute names for argument TG_relatts */
1124  tcl_trigtup = Tcl_NewObj();
1125  Tcl_ListObjAppendElement(NULL, tcl_trigtup, Tcl_NewObj());
1126  for (i = 0; i < tupdesc->natts; i++)
1127  {
1128  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1129 
1130  if (att->attisdropped)
1131  Tcl_ListObjAppendElement(NULL, tcl_trigtup, Tcl_NewObj());
1132  else
1133  Tcl_ListObjAppendElement(NULL, tcl_trigtup,
1134  Tcl_NewStringObj(utf_e2u(NameStr(att->attname)), -1));
1135  }
1136  Tcl_ListObjAppendElement(NULL, tcl_cmd, tcl_trigtup);
1137 
1138  /* The when part of the event for TG_when */
1139  if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
1140  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1141  Tcl_NewStringObj("BEFORE", -1));
1142  else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
1143  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1144  Tcl_NewStringObj("AFTER", -1));
1145  else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
1146  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1147  Tcl_NewStringObj("INSTEAD OF", -1));
1148  else
1149  elog(ERROR, "unrecognized WHEN tg_event: %u", trigdata->tg_event);
1150 
1151  /* The level part of the event for TG_level */
1152  if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1153  {
1154  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1155  Tcl_NewStringObj("ROW", -1));
1156 
1157  /*
1158  * Now the command part of the event for TG_op and data for NEW
1159  * and OLD
1160  *
1161  * Note: In BEFORE trigger, stored generated columns are not
1162  * computed yet, so don't make them accessible in NEW row.
1163  */
1164  if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1165  {
1166  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1167  Tcl_NewStringObj("INSERT", -1));
1168 
1169  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1171  tupdesc,
1172  !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
1173  Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1174 
1175  rettup = trigdata->tg_trigtuple;
1176  }
1177  else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1178  {
1179  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1180  Tcl_NewStringObj("DELETE", -1));
1181 
1182  Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1183  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1185  tupdesc,
1186  true));
1187 
1188  rettup = trigdata->tg_trigtuple;
1189  }
1190  else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1191  {
1192  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1193  Tcl_NewStringObj("UPDATE", -1));
1194 
1195  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1197  tupdesc,
1198  !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
1199  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1201  tupdesc,
1202  true));
1203 
1204  rettup = trigdata->tg_newtuple;
1205  }
1206  else
1207  elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
1208  }
1209  else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
1210  {
1211  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1212  Tcl_NewStringObj("STATEMENT", -1));
1213 
1214  if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1215  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1216  Tcl_NewStringObj("INSERT", -1));
1217  else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1218  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1219  Tcl_NewStringObj("DELETE", -1));
1220  else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1221  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1222  Tcl_NewStringObj("UPDATE", -1));
1223  else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
1224  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1225  Tcl_NewStringObj("TRUNCATE", -1));
1226  else
1227  elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
1228 
1229  Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1230  Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1231 
1232  rettup = (HeapTuple) NULL;
1233  }
1234  else
1235  elog(ERROR, "unrecognized LEVEL tg_event: %u", trigdata->tg_event);
1236 
1237  /* Finally append the arguments from CREATE TRIGGER */
1238  for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
1239  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1240  Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgargs[i]), -1));
1241 
1242  }
1243  PG_CATCH();
1244  {
1245  Tcl_DecrRefCount(tcl_cmd);
1246  PG_RE_THROW();
1247  }
1248  PG_END_TRY();
1249 
1250  /************************************************************
1251  * Call the Tcl function
1252  *
1253  * We assume no PG error can be thrown directly from this call.
1254  ************************************************************/
1255  tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
1256 
1257  /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1258  Tcl_DecrRefCount(tcl_cmd);
1259 
1260  /************************************************************
1261  * Check for errors reported by Tcl.
1262  ************************************************************/
1263  if (tcl_rc != TCL_OK)
1264  throw_tcl_error(interp, prodesc->user_proname);
1265 
1266  /************************************************************
1267  * Exit SPI environment.
1268  ************************************************************/
1269  if (SPI_finish() != SPI_OK_FINISH)
1270  elog(ERROR, "SPI_finish() failed");
1271 
1272  /************************************************************
1273  * The return value from the procedure might be one of
1274  * the magic strings OK or SKIP, or a list from array get.
1275  * We can check for OK or SKIP without worrying about encoding.
1276  ************************************************************/
1277  result = Tcl_GetStringResult(interp);
1278 
1279  if (strcmp(result, "OK") == 0)
1280  return rettup;
1281  if (strcmp(result, "SKIP") == 0)
1282  return (HeapTuple) NULL;
1283 
1284  /************************************************************
1285  * Otherwise, the return value should be a column name/value list
1286  * specifying the modified tuple to return.
1287  ************************************************************/
1288  if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
1289  &result_Objc, &result_Objv) != TCL_OK)
1290  ereport(ERROR,
1291  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1292  errmsg("could not split return value from trigger: %s",
1293  utf_u2e(Tcl_GetStringResult(interp)))));
1294 
1295  /* Convert function result to tuple */
1296  rettup = pltcl_build_tuple_result(interp, result_Objv, result_Objc,
1297  call_state);
1298 
1299  return rettup;
1300 }
#define SPI_OK_CONNECT
Definition: spi.h:53
HeapTupleData * HeapTuple
Definition: htup.h:71
#define RelationGetDescr(relation)
Definition: rel.h:482
int SPI_connect(void)
Definition: spi.c:90
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int SPI_finish(void)
Definition: spi.c:177
char * user_proname
Definition: pltcl.c:138
int errcode(int sqlerrcode)
Definition: elog.c:610
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:624
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:130
Datum oidout(PG_FUNCTION_ARGS)
Definition: oid.c:127
static void throw_tcl_error(Tcl_Interp *interp, const char *proname)
Definition: pltcl.c:1357
#define TRIGGER_FIRED_FOR_STATEMENT(event)
Definition: trigger.h:124
HeapTuple tg_trigtuple
Definition: trigger.h:35
void pfree(void *pointer)
Definition: mcxt.c:1057
#define TRIGGER_FIRED_BY_TRUNCATE(event)
Definition: trigger.h:118
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define DatumGetCString(X)
Definition: postgres.h:566
char * tgname
Definition: reltrigger.h:27
pltcl_interp_desc * interp_desc
Definition: pltcl.c:146
static char * utf_u2e(const char *src)
Definition: pltcl.c:75
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
unsigned long fn_refcount
Definition: pltcl.c:141
Tcl_Interp * interp
Definition: pltcl.c:116
int SPI_register_trigger_data(TriggerData *tdata)
Definition: spi.c:3063
Oid rd_id
Definition: rel.h:111
char ** tgargs
Definition: reltrigger.h:41
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:112
static pltcl_proc_desc * compile_pltcl_function(Oid fn_oid, Oid tgreloid, bool is_event_trigger, bool pltrusted)
Definition: pltcl.c:1386
static char * utf_e2u(const char *src)
Definition: pltcl.c:81
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
char * SPI_getrelname(Relation rel)
Definition: spi.c:1175
#define ereport(elevel,...)
Definition: elog.h:144
static HeapTuple pltcl_build_tuple_result(Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc, pltcl_call_state *call_state)
Definition: pltcl.c:3168
char * internal_proname
Definition: pltcl.c:139
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:746
pltcl_proc_desc * prodesc
Definition: pltcl.c:217
TriggerEvent tg_event
Definition: trigger.h:33
char * SPI_getnspname(Relation rel)
Definition: spi.c:1181
#define SPI_OK_FINISH
Definition: spi.h:54
#define PG_RE_THROW()
Definition: elog.h:336
#define TRIGGER_FIRED_BEFORE(event)
Definition: trigger.h:127
#define TRIGGER_FIRED_INSTEAD(event)
Definition: trigger.h:133
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:109
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
int i
int16 tgnargs
Definition: reltrigger.h:38
#define NameStr(name)
Definition: c.h:623
TriggerData * trigdata
Definition: pltcl.c:214
#define PG_TRY()
Definition: elog.h:295
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:121
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:115
#define RelationGetRelid(relation)
Definition: rel.h:456
#define PG_END_TRY()
Definition: elog.h:320
static Tcl_Obj * pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
Definition: pltcl.c:3092
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:122
Relation tg_relation
Definition: trigger.h:34

◆ pltcl_WaitForEvent()

static int pltcl_WaitForEvent ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 386 of file pltcl.c.

Referenced by _PG_init().

387 {
388  return 0;
389 }

◆ pltclu_call_handler()

Datum pltclu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 708 of file pltcl.c.

References pltcl_handler().

Referenced by pltcl_call_handler().

709 {
710  return pltcl_handler(fcinfo, false);
711 }
static Datum pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted)
Definition: pltcl.c:719

◆ start_proc_error_callback()

static void start_proc_error_callback ( void *  arg)
static

Definition at line 676 of file pltcl.c.

References errcontext, PG_FUNCTION_INFO_V1(), and pltcl_call_handler().

Referenced by call_pltcl_start_proc().

677 {
678  const char *gucname = (const char *) arg;
679 
680  /* translator: %s is "pltcl.start_proc" or "pltclu.start_proc" */
681  errcontext("processing %s parameter", gucname);
682 }
#define errcontext
Definition: elog.h:185
void * arg

◆ throw_tcl_error()

static void throw_tcl_error ( Tcl_Interp *  interp,
const char *  proname 
)
static

Definition at line 1357 of file pltcl.c.

References ereport, errcode(), errcontext, errmsg(), ERROR, pstrdup(), and utf_u2e().

Referenced by pltcl_event_trigger_handler(), pltcl_func_handler(), and pltcl_trigger_handler().

1358 {
1359  /*
1360  * Caution is needed here because Tcl_GetVar could overwrite the
1361  * interpreter result (even though it's not really supposed to), and we
1362  * can't control the order of evaluation of ereport arguments. Hence, make
1363  * real sure we have our own copy of the result string before invoking
1364  * Tcl_GetVar.
1365  */
1366  char *emsg;
1367  char *econtext;
1368 
1369  emsg = pstrdup(utf_u2e(Tcl_GetStringResult(interp)));
1370  econtext = utf_u2e(Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY));
1371  ereport(ERROR,
1372  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1373  errmsg("%s", emsg),
1374  errcontext("%s\nin PL/Tcl function \"%s\"",
1375  econtext, proname)));
1376 }
NameData proname
Definition: pg_proc.h:35
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
static char * utf_u2e(const char *src)
Definition: pltcl.c:75
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define errcontext
Definition: elog.h:185

◆ utf_e2u()

static char* utf_e2u ( const char *  src)
inlinestatic

Definition at line 81 of file pltcl.c.

References pg_server_to_any(), and PG_UTF8.

Referenced by pltcl_event_trigger_handler(), and pltcl_trigger_handler().

82 {
83  return pg_server_to_any(src, strlen(src), PG_UTF8);
84 }
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:692

◆ utf_u2e()

static char* utf_u2e ( const char *  src)
inlinestatic

Definition at line 75 of file pltcl.c.

References pg_any_to_server(), and PG_UTF8.

Referenced by compile_pltcl_function(), pltcl_build_tuple_result(), pltcl_func_handler(), pltcl_returnnext(), pltcl_trigger_handler(), and throw_tcl_error().

76 {
77  return pg_any_to_server(src, strlen(src), PG_UTF8);
78 }
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:619

Variable Documentation

◆ exception_name_map

const TclExceptionNameMap exception_name_map[]
static
Initial value:
= {
{NULL, 0}
}

Definition at line 256 of file pltcl.c.

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 43 of file pltcl.c.

◆ pltcl_current_call_state

pltcl_call_state* pltcl_current_call_state = NULL
static

Definition at line 245 of file pltcl.c.

Referenced by pltcl_handler(), and pltcl_returnnext().

◆ pltcl_hold_interp

Tcl_Interp* pltcl_hold_interp = NULL
static

Definition at line 240 of file pltcl.c.

Referenced by _PG_init(), and pltcl_init_interp().

◆ pltcl_interp_htab

HTAB* pltcl_interp_htab = NULL
static

Definition at line 241 of file pltcl.c.

◆ pltcl_pm_init_done

bool pltcl_pm_init_done = false
static

Definition at line 239 of file pltcl.c.

Referenced by _PG_init().

◆ pltcl_proc_htab

HTAB* pltcl_proc_htab = NULL
static

Definition at line 242 of file pltcl.c.

◆ pltcl_start_proc

char* pltcl_start_proc = NULL
static

Definition at line 237 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().

◆ pltclu_start_proc

char* pltclu_start_proc = NULL
static

Definition at line 238 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().