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/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_SPI_lastoid (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)
 
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 55 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 44 of file pltcl.c.

◆ TEXTDOMAIN

#define TEXTDOMAIN   PG_TEXTDOMAIN("pltcl")

Definition at line 60 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 95 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 402 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.

403 {
404  Tcl_NotifierProcs notifier;
405  HASHCTL hash_ctl;
406 
407  /* Be sure we do initialization only once (should be redundant now) */
408  if (pltcl_pm_init_done)
409  return;
410 
412 
413 #ifdef WIN32
414  /* Required on win32 to prevent error loading init.tcl */
415  Tcl_FindExecutable("");
416 #endif
417 
418  /*
419  * Override the functions in the Notifier subsystem. See comments above.
420  */
421  notifier.setTimerProc = pltcl_SetTimer;
422  notifier.waitForEventProc = pltcl_WaitForEvent;
423  notifier.createFileHandlerProc = pltcl_CreateFileHandler;
424  notifier.deleteFileHandlerProc = pltcl_DeleteFileHandler;
425  notifier.initNotifierProc = pltcl_InitNotifier;
426  notifier.finalizeNotifierProc = pltcl_FinalizeNotifier;
427  notifier.alertNotifierProc = pltcl_AlertNotifier;
428  notifier.serviceModeHookProc = pltcl_ServiceModeHook;
429  Tcl_SetNotifier(&notifier);
430 
431  /************************************************************
432  * Create the dummy hold interpreter to prevent close of
433  * stdout and stderr on DeleteInterp
434  ************************************************************/
435  if ((pltcl_hold_interp = Tcl_CreateInterp()) == NULL)
436  elog(ERROR, "could not create master Tcl interpreter");
437  if (Tcl_Init(pltcl_hold_interp) == TCL_ERROR)
438  elog(ERROR, "could not initialize master Tcl interpreter");
439 
440  /************************************************************
441  * Create the hash table for working interpreters
442  ************************************************************/
443  memset(&hash_ctl, 0, sizeof(hash_ctl));
444  hash_ctl.keysize = sizeof(Oid);
445  hash_ctl.entrysize = sizeof(pltcl_interp_desc);
446  pltcl_interp_htab = hash_create("PL/Tcl interpreters",
447  8,
448  &hash_ctl,
450 
451  /************************************************************
452  * Create the hash table for function lookup
453  ************************************************************/
454  memset(&hash_ctl, 0, sizeof(hash_ctl));
455  hash_ctl.keysize = sizeof(pltcl_proc_key);
456  hash_ctl.entrysize = sizeof(pltcl_proc_ptr);
457  pltcl_proc_htab = hash_create("PL/Tcl functions",
458  100,
459  &hash_ctl,
461 
462  /************************************************************
463  * Define PL/Tcl's custom GUCs
464  ************************************************************/
465  DefineCustomStringVariable("pltcl.start_proc",
466  gettext_noop("PL/Tcl function to call once when pltcl is first used."),
467  NULL,
469  NULL,
470  PGC_SUSET, 0,
471  NULL, NULL, NULL);
472  DefineCustomStringVariable("pltclu.start_proc",
473  gettext_noop("PL/TclU function to call once when pltclu is first used."),
474  NULL,
476  NULL,
477  PGC_SUSET, 0,
478  NULL, NULL, NULL);
479 
480  pltcl_pm_init_done = true;
481 }
#define TEXTDOMAIN
Definition: pltcl.c:60
struct pltcl_proc_ptr pltcl_proc_ptr
#define HASH_ELEM
Definition: hsearch.h:87
struct pltcl_proc_key pltcl_proc_key
static void pltcl_DeleteFileHandler(int fd)
Definition: pltcl.c:377
Size entrysize
Definition: hsearch.h:73
#define gettext_noop(x)
Definition: c.h:1036
static void pltcl_ServiceModeHook(int mode)
Definition: pltcl.c:382
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:371
static void pltcl_AlertNotifier(ClientData clientData)
Definition: pltcl.c:366
static bool pltcl_pm_init_done
Definition: pltcl.c:238
static char * pltcl_start_proc
Definition: pltcl.c:236
static int pltcl_WaitForEvent(CONST86 Tcl_Time *timePtr)
Definition: pltcl.c:387
#define ERROR
Definition: elog.h:43
static ClientData pltcl_InitNotifier(void)
Definition: pltcl.c:348
Definition: guc.h:75
static void pltcl_SetTimer(CONST86 Tcl_Time *timePtr)
Definition: pltcl.c:361
static Tcl_Interp * pltcl_hold_interp
Definition: pltcl.c:239
#define HASH_BLOBS
Definition: hsearch.h:88
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:8067
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size keysize
Definition: hsearch.h:72
static HTAB * pltcl_proc_htab
Definition: pltcl.c:241
static void pltcl_FinalizeNotifier(ClientData clientData)
Definition: pltcl.c:356
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1603
static HTAB * pltcl_interp_htab
Definition: pltcl.c:240
static char * pltclu_start_proc
Definition: pltcl.c:237
#define elog
Definition: elog.h:219

◆ call_pltcl_start_proc()

static void call_pltcl_start_proc ( Oid  prolang,
bool  pltrusted 
)
static

Definition at line 592 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, 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(), and stringToQualifiedNameList().

Referenced by pltcl_init_interp().

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

◆ 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 1389 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().

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

◆ 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 366 of file pltcl.c.

Referenced by _PG_init().

367 {
368 }

◆ pltcl_argisnull()

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

Definition at line 2055 of file pltcl.c.

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

Referenced by pltcl_init_interp().

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

◆ pltcl_build_tuple_argument()

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

Definition at line 3119 of file pltcl.c.

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

Referenced by pltcl_func_handler(), and pltcl_trigger_handler().

3120 {
3121  Tcl_Obj *retobj = Tcl_NewObj();
3122  int i;
3123  char *outputstr;
3124  Datum attr;
3125  bool isnull;
3126  char *attname;
3127  Oid typoutput;
3128  bool typisvarlena;
3129 
3130  for (i = 0; i < tupdesc->natts; i++)
3131  {
3132  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3133 
3134  /* ignore dropped attributes */
3135  if (att->attisdropped)
3136  continue;
3137 
3138  /************************************************************
3139  * Get the attribute name
3140  ************************************************************/
3141  attname = NameStr(att->attname);
3142 
3143  /************************************************************
3144  * Get the attributes value
3145  ************************************************************/
3146  attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3147 
3148  /************************************************************
3149  * If there is a value, append the attribute name and the
3150  * value to the list
3151  *
3152  * Hmmm - Null attributes will cause functions to
3153  * crash if they don't expect them - need something
3154  * smarter here.
3155  ************************************************************/
3156  if (!isnull)
3157  {
3158  getTypeOutputInfo(att->atttypid,
3159  &typoutput, &typisvarlena);
3160  outputstr = OidOutputFunctionCall(typoutput, attr);
3161  UTF_BEGIN;
3162  Tcl_ListObjAppendElement(NULL, retobj,
3163  Tcl_NewStringObj(UTF_E2U(attname), -1));
3164  UTF_END;
3165  UTF_BEGIN;
3166  Tcl_ListObjAppendElement(NULL, retobj,
3167  Tcl_NewStringObj(UTF_E2U(outputstr), -1));
3168  UTF_END;
3169  pfree(outputstr);
3170  }
3171  }
3172 
3173  return retobj;
3174 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2650
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:82
void pfree(void *pointer)
Definition: mcxt.c:1031
#define UTF_E2U(x)
Definition: pltcl.c:98
NameData attname
Definition: pg_attribute.h:40
#define UTF_END
Definition: pltcl.c:90
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:786
uintptr_t Datum
Definition: postgres.h:365
#define UTF_BEGIN
Definition: pltcl.c:85
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1832
int i
#define NameStr(name)
Definition: c.h:576

◆ 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 3188 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, tupleDesc::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, TupleDescGetAttInMetadata(), utf_u2e(), and values.

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

3190 {
3191  HeapTuple tuple;
3192  TupleDesc tupdesc;
3193  AttInMetadata *attinmeta;
3194  char **values;
3195  int i;
3196 
3197  if (call_state->ret_tupdesc)
3198  {
3199  tupdesc = call_state->ret_tupdesc;
3200  attinmeta = call_state->attinmeta;
3201  }
3202  else if (call_state->trigdata)
3203  {
3204  tupdesc = RelationGetDescr(call_state->trigdata->tg_relation);
3205  attinmeta = TupleDescGetAttInMetadata(tupdesc);
3206  }
3207  else
3208  {
3209  elog(ERROR, "PL/Tcl function does not return a tuple");
3210  tupdesc = NULL; /* keep compiler quiet */
3211  attinmeta = NULL;
3212  }
3213 
3214  values = (char **) palloc0(tupdesc->natts * sizeof(char *));
3215 
3216  if (kvObjc % 2 != 0)
3217  ereport(ERROR,
3218  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3219  errmsg("column name/value list must have even number of elements")));
3220 
3221  for (i = 0; i < kvObjc; i += 2)
3222  {
3223  char *fieldName = utf_u2e(Tcl_GetString(kvObjv[i]));
3224  int attn = SPI_fnumber(tupdesc, fieldName);
3225 
3226  /*
3227  * We silently ignore ".tupno", if it's present but doesn't match any
3228  * actual output column. This allows direct use of a row returned by
3229  * pltcl_set_tuple_values().
3230  */
3231  if (attn == SPI_ERROR_NOATTRIBUTE)
3232  {
3233  if (strcmp(fieldName, ".tupno") == 0)
3234  continue;
3235  ereport(ERROR,
3236  (errcode(ERRCODE_UNDEFINED_COLUMN),
3237  errmsg("column name/value list contains nonexistent column name \"%s\"",
3238  fieldName)));
3239  }
3240 
3241  if (attn <= 0)
3242  ereport(ERROR,
3243  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3244  errmsg("cannot set system attribute \"%s\"",
3245  fieldName)));
3246 
3247  values[attn - 1] = utf_u2e(Tcl_GetString(kvObjv[i + 1]));
3248  }
3249 
3250  tuple = BuildTupleFromCStrings(attinmeta, values);
3251 
3252  /* if result type is domain-over-composite, check domain constraints */
3253  if (call_state->prodesc->fn_retisdomain)
3254  domain_check(HeapTupleGetDatum(tuple), false,
3255  call_state->prodesc->result_typid,
3256  &call_state->prodesc->domain_info,
3257  call_state->prodesc->fn_cxt);
3258 
3259  return tuple;
3260 }
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:855
#define RelationGetDescr(relation)
Definition: rel.h:433
void * domain_info
Definition: pltcl.c:152
int errcode(int sqlerrcode)
Definition: elog.c:575
int natts
Definition: tupdesc.h:82
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:1195
bool fn_retisdomain
Definition: pltcl.c:151
AttInMetadata * attinmeta
Definition: pltcl.c:224
#define ERROR
Definition: elog.h:43
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
static char * utf_u2e(const char *src)
Definition: pltcl.c:74
#define ereport(elevel, rest)
Definition: elog.h:122
TupleDesc ret_tupdesc
Definition: pltcl.c:223
void * palloc0(Size size)
Definition: mcxt.c:955
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1146
void domain_check(Datum value, bool isnull, Oid domainType, void **extra, MemoryContext mcxt)
Definition: domains.c:327
pltcl_proc_desc * prodesc
Definition: pltcl.c:216
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:231
Oid result_typid
Definition: pltcl.c:146
static Datum values[MAXATTR]
Definition: bootstrap.c:164
MemoryContext fn_cxt
Definition: pltcl.c:139
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define elog
Definition: elog.h:219
TriggerData * trigdata
Definition: pltcl.c:213
Relation tg_relation
Definition: trigger.h:34

◆ pltcl_call_handler()

Datum pltcl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 700 of file pltcl.c.

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

Referenced by start_proc_error_callback().

701 {
702  return pltcl_handler(fcinfo, true);
703 }
static Datum pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted)
Definition: pltcl.c:723

◆ pltcl_commit()

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

Definition at line 2952 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().

2954 {
2955  MemoryContext oldcontext = CurrentMemoryContext;
2956 
2957  PG_TRY();
2958  {
2959  SPI_commit();
2961  }
2962  PG_CATCH();
2963  {
2964  ErrorData *edata;
2965 
2966  /* Save error info */
2967  MemoryContextSwitchTo(oldcontext);
2968  edata = CopyErrorData();
2969  FlushErrorState();
2970 
2971  /* Pass the error data to Tcl */
2972  pltcl_construct_errorCode(interp, edata);
2973  UTF_BEGIN;
2974  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2975  UTF_END;
2976  FreeErrorData(edata);
2977 
2978  return TCL_ERROR;
2979  }
2980  PG_END_TRY();
2981 
2982  return TCL_OK;
2983 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void FlushErrorState(void)
Definition: elog.c:1587
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1551
#define UTF_E2U(x)
Definition: pltcl.c:98
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1838
#define UTF_END
Definition: pltcl.c:90
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void SPI_commit(void)
Definition: spi.c:206
#define UTF_BEGIN
Definition: pltcl.c:85
#define PG_CATCH()
Definition: elog.h:293
void SPI_start_transaction(void)
Definition: spi.c:197
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343

◆ pltcl_construct_errorCode()

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

Definition at line 1838 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().

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

◆ pltcl_CreateFileHandler()

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

Definition at line 371 of file pltcl.c.

Referenced by _PG_init().

373 {
374 }

◆ pltcl_DeleteFileHandler()

static void pltcl_DeleteFileHandler ( int  fd)
static

Definition at line 377 of file pltcl.c.

Referenced by _PG_init().

378 {
379 }

◆ pltcl_elog()

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

Definition at line 1751 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().

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

◆ pltcl_event_trigger_handler()

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

Definition at line 1310 of file pltcl.c.

References compile_pltcl_function(), elog, ERROR, EventTriggerData::event, pltcl_proc_desc::fn_refcount, 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().

1312 {
1313  pltcl_proc_desc *prodesc;
1314  Tcl_Interp *volatile interp;
1315  EventTriggerData *tdata = (EventTriggerData *) fcinfo->context;
1316  Tcl_Obj *tcl_cmd;
1317  int tcl_rc;
1318 
1319  /* Connect to SPI manager */
1320  if (SPI_connect() != SPI_OK_CONNECT)
1321  elog(ERROR, "could not connect to SPI manager");
1322 
1323  /* Find or compile the function */
1324  prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1325  InvalidOid, true, pltrusted);
1326 
1327  call_state->prodesc = prodesc;
1328  prodesc->fn_refcount++;
1329 
1330  interp = prodesc->interp_desc->interp;
1331 
1332  /* Create the tcl command and call the internal proc */
1333  tcl_cmd = Tcl_NewObj();
1334  Tcl_IncrRefCount(tcl_cmd);
1335  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1336  Tcl_NewStringObj(prodesc->internal_proname, -1));
1337  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1338  Tcl_NewStringObj(utf_e2u(tdata->event), -1));
1339  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1340  Tcl_NewStringObj(utf_e2u(tdata->tag), -1));
1341 
1342  tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
1343 
1344  /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1345  Tcl_DecrRefCount(tcl_cmd);
1346 
1347  /* Check for errors reported by Tcl. */
1348  if (tcl_rc != TCL_OK)
1349  throw_tcl_error(interp, prodesc->user_proname);
1350 
1351  if (SPI_finish() != SPI_OK_FINISH)
1352  elog(ERROR, "SPI_finish() failed");
1353 }
#define SPI_OK_CONNECT
Definition: spi.h:50
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:161
char * user_proname
Definition: pltcl.c:137
const char * tag
Definition: event_trigger.h:28
static void throw_tcl_error(Tcl_Interp *interp, const char *proname)
Definition: pltcl.c:1360
#define ERROR
Definition: elog.h:43
const char * event
Definition: event_trigger.h:26
pltcl_interp_desc * interp_desc
Definition: pltcl.c:145
unsigned long fn_refcount
Definition: pltcl.c:140
Tcl_Interp * interp
Definition: pltcl.c:115
static pltcl_proc_desc * compile_pltcl_function(Oid fn_oid, Oid tgreloid, bool is_event_trigger, bool pltrusted)
Definition: pltcl.c:1389
static char * utf_e2u(const char *src)
Definition: pltcl.c:80
#define InvalidOid
Definition: postgres_ext.h:36
char * internal_proname
Definition: pltcl.c:138
pltcl_proc_desc * prodesc
Definition: pltcl.c:216
#define SPI_OK_FINISH
Definition: spi.h:51
#define elog
Definition: elog.h:219

◆ pltcl_fetch_interp()

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

Definition at line 562 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().

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

◆ pltcl_FinalizeNotifier()

static void pltcl_FinalizeNotifier ( ClientData  clientData)
static

Definition at line 356 of file pltcl.c.

Referenced by _PG_init().

357 {
358 }

◆ pltcl_func_handler()

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

Definition at line 804 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().

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

◆ pltcl_get_condition_name()

static const char * pltcl_get_condition_name ( int  sqlstate)
static

Definition at line 1983 of file pltcl.c.

References i, and TclExceptionNameMap::label.

Referenced by pltcl_construct_errorCode().

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

◆ pltcl_handler()

static Datum pltcl_handler ( PG_FUNCTION_ARGS  ,
bool  pltrusted 
)
static

Definition at line 723 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_CATCH, PG_END_TRY, PG_RE_THROW, 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().

724 {
725  Datum retval;
726  pltcl_call_state current_call_state;
727  pltcl_call_state *save_call_state;
728 
729  /*
730  * Initialize current_call_state to nulls/zeroes; in particular, set its
731  * prodesc pointer to null. Anything that sets it non-null should
732  * increase the prodesc's fn_refcount at the same time. We'll decrease
733  * the refcount, and then delete the prodesc if it's no longer referenced,
734  * on the way out of this function. This ensures that prodescs live as
735  * long as needed even if somebody replaces the originating pg_proc row
736  * while they're executing.
737  */
738  memset(&current_call_state, 0, sizeof(current_call_state));
739 
740  /*
741  * Ensure that static pointer is saved/restored properly
742  */
743  save_call_state = pltcl_current_call_state;
744  pltcl_current_call_state = &current_call_state;
745 
746  PG_TRY();
747  {
748  /*
749  * Determine if called as function or trigger and call appropriate
750  * subhandler
751  */
752  if (CALLED_AS_TRIGGER(fcinfo))
753  {
754  /* invoke the trigger handler */
755  retval = PointerGetDatum(pltcl_trigger_handler(fcinfo,
756  &current_call_state,
757  pltrusted));
758  }
759  else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
760  {
761  /* invoke the event trigger handler */
762  pltcl_event_trigger_handler(fcinfo, &current_call_state, pltrusted);
763  retval = (Datum) 0;
764  }
765  else
766  {
767  /* invoke the regular function handler */
768  current_call_state.fcinfo = fcinfo;
769  retval = pltcl_func_handler(fcinfo, &current_call_state, pltrusted);
770  }
771  }
772  PG_CATCH();
773  {
774  /* Restore static pointer, then clean up the prodesc refcount if any */
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  PG_RE_THROW();
783  }
784  PG_END_TRY();
785 
786  /* Restore static pointer, then clean up the prodesc refcount if any */
787  /* (We're being paranoid in case an error is thrown in context deletion) */
788  pltcl_current_call_state = save_call_state;
789  if (current_call_state.prodesc != NULL)
790  {
791  Assert(current_call_state.prodesc->fn_refcount > 0);
792  if (--current_call_state.prodesc->fn_refcount == 0)
793  MemoryContextDelete(current_call_state.prodesc->fn_cxt);
794  }
795 
796  return retval;
797 }
#define CALLED_AS_EVENT_TRIGGER(fcinfo)
Definition: event_trigger.h:40
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define PointerGetDatum(X)
Definition: postgres.h:539
FunctionCallInfo fcinfo
Definition: pltcl.c:210
static Datum pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
Definition: pltcl.c:804
static pltcl_call_state * pltcl_current_call_state
Definition: pltcl.c:244
static void pltcl_event_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
Definition: pltcl.c:1310
unsigned long fn_refcount
Definition: pltcl.c:140
static HeapTuple pltcl_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
Definition: pltcl.c:1056
uintptr_t Datum
Definition: postgres.h:365
#define PG_CATCH()
Definition: elog.h:293
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define Assert(condition)
Definition: c.h:699
pltcl_proc_desc * prodesc
Definition: pltcl.c:216
#define PG_RE_THROW()
Definition: elog.h:314
MemoryContext fn_cxt
Definition: pltcl.c:139
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300

◆ pltcl_init_interp()

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

Definition at line 487 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_lastoid(), pltcl_SPI_prepare(), pltcl_subtransaction(), pltcl_interp_desc::query_hash, snprintf(), and pltcl_interp_desc::user_id.

Referenced by pltcl_fetch_interp().

488 {
489  Tcl_Interp *interp;
490  char interpname[32];
491 
492  /************************************************************
493  * Create the Tcl interpreter as a slave of pltcl_hold_interp.
494  * Note: Tcl automatically does Tcl_Init in the untrusted case,
495  * and it's not wanted in the trusted case.
496  ************************************************************/
497  snprintf(interpname, sizeof(interpname), "slave_%u", interp_desc->user_id);
498  if ((interp = Tcl_CreateSlave(pltcl_hold_interp, interpname,
499  pltrusted ? 1 : 0)) == NULL)
500  elog(ERROR, "could not create slave Tcl interpreter");
501 
502  /************************************************************
503  * Initialize the query hash table associated with interpreter
504  ************************************************************/
505  Tcl_InitHashTable(&interp_desc->query_hash, TCL_STRING_KEYS);
506 
507  /************************************************************
508  * Install the commands for SPI support in the interpreter
509  ************************************************************/
510  Tcl_CreateObjCommand(interp, "elog",
511  pltcl_elog, NULL, NULL);
512  Tcl_CreateObjCommand(interp, "quote",
513  pltcl_quote, NULL, NULL);
514  Tcl_CreateObjCommand(interp, "argisnull",
515  pltcl_argisnull, NULL, NULL);
516  Tcl_CreateObjCommand(interp, "return_null",
517  pltcl_returnnull, NULL, NULL);
518  Tcl_CreateObjCommand(interp, "return_next",
519  pltcl_returnnext, NULL, NULL);
520  Tcl_CreateObjCommand(interp, "spi_exec",
521  pltcl_SPI_execute, NULL, NULL);
522  Tcl_CreateObjCommand(interp, "spi_prepare",
523  pltcl_SPI_prepare, NULL, NULL);
524  Tcl_CreateObjCommand(interp, "spi_execp",
525  pltcl_SPI_execute_plan, NULL, NULL);
526  Tcl_CreateObjCommand(interp, "spi_lastoid",
527  pltcl_SPI_lastoid, NULL, NULL);
528  Tcl_CreateObjCommand(interp, "subtransaction",
529  pltcl_subtransaction, NULL, NULL);
530  Tcl_CreateObjCommand(interp, "commit",
531  pltcl_commit, NULL, NULL);
532  Tcl_CreateObjCommand(interp, "rollback",
533  pltcl_rollback, NULL, NULL);
534 
535  /************************************************************
536  * Call the appropriate start_proc, if there is one.
537  *
538  * We must set interp_desc->interp before the call, else the start_proc
539  * won't find the interpreter it's supposed to use. But, if the
540  * start_proc fails, we want to abandon use of the interpreter.
541  ************************************************************/
542  PG_TRY();
543  {
544  interp_desc->interp = interp;
545  call_pltcl_start_proc(prolang, pltrusted);
546  }
547  PG_CATCH();
548  {
549  interp_desc->interp = NULL;
550  Tcl_DeleteInterp(interp);
551  PG_RE_THROW();
552  }
553  PG_END_TRY();
554 }
static int pltcl_rollback(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2992
static int pltcl_argisnull(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2055
static int pltcl_commit(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2952
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static int pltcl_elog(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:1751
static int pltcl_subtransaction(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2904
static int pltcl_SPI_prepare(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2536
static int pltcl_quote(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2001
static int pltcl_SPI_execute_plan(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2663
#define ERROR
Definition: elog.h:43
static void call_pltcl_start_proc(Oid prolang, bool pltrusted)
Definition: pltcl.c:592
static Tcl_Interp * pltcl_hold_interp
Definition: pltcl.c:239
Tcl_Interp * interp
Definition: pltcl.c:115
static int pltcl_SPI_lastoid(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2880
#define PG_CATCH()
Definition: elog.h:293
static int pltcl_returnnext(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2147
#define PG_RE_THROW()
Definition: elog.h:314
#define elog
Definition: elog.h:219
static int pltcl_returnnull(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2109
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
Tcl_HashTable query_hash
Definition: pltcl.c:116
static int pltcl_SPI_execute(ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
Definition: pltcl.c:2317

◆ pltcl_init_tuple_store()

static void pltcl_init_tuple_store ( pltcl_call_state call_state)
static

Definition at line 3266 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().

3267 {
3268  ReturnSetInfo *rsi = call_state->rsi;
3269  MemoryContext oldcxt;
3270  ResourceOwner oldowner;
3271 
3272  /* Should be in a SRF */
3273  Assert(rsi);
3274  /* Should be first time through */
3275  Assert(!call_state->tuple_store);
3276  Assert(!call_state->attinmeta);
3277 
3278  /* We expect caller to provide an appropriate result tupdesc */
3279  Assert(rsi->expectedDesc);
3280  call_state->ret_tupdesc = rsi->expectedDesc;
3281 
3282  /*
3283  * Switch to the right memory context and resource owner for storing the
3284  * tuplestore. If we're within a subtransaction opened for an exception
3285  * block, for example, we must still create the tuplestore in the resource
3286  * owner that was active when this function was entered, and not in the
3287  * subtransaction's resource owner.
3288  */
3289  oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
3290  oldowner = CurrentResourceOwner;
3292 
3293  call_state->tuple_store =
3295  false, work_mem);
3296 
3297  /* Build attinmeta in this context, too */
3298  call_state->attinmeta = TupleDescGetAttInMetadata(call_state->ret_tupdesc);
3299 
3300  CurrentResourceOwner = oldowner;
3301  MemoryContextSwitchTo(oldcxt);
3302 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ResourceOwner tuple_store_owner
Definition: pltcl.c:229
TupleDesc expectedDesc
Definition: execnodes.h:296
AttInMetadata * attinmeta
Definition: pltcl.c:224
ReturnSetInfo * rsi
Definition: pltcl.c:226
MemoryContext tuple_store_cxt
Definition: pltcl.c:228
Tuplestorestate * tuple_store
Definition: pltcl.c:227
TupleDesc ret_tupdesc
Definition: pltcl.c:223
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:1146
int work_mem
Definition: globals.c:122
int allowedModes
Definition: execnodes.h:297
#define Assert(condition)
Definition: c.h:699

◆ pltcl_InitNotifier()

static ClientData pltcl_InitNotifier ( void  )
static

Definition at line 348 of file pltcl.c.

Referenced by _PG_init().

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

◆ 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 2426 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().

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

◆ pltcl_quote()

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

Definition at line 2001 of file pltcl.c.

References length(), palloc(), and pfree().

Referenced by pltcl_init_interp().

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

◆ pltcl_returnnext()

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

Definition at line 2147 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(), tupleDesc::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().

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

◆ pltcl_returnnull()

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

Definition at line 2109 of file pltcl.c.

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

Referenced by pltcl_init_interp().

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

◆ pltcl_rollback()

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

Definition at line 2992 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().

2994 {
2995  MemoryContext oldcontext = CurrentMemoryContext;
2996 
2997  PG_TRY();
2998  {
2999  SPI_rollback();
3001  }
3002  PG_CATCH();
3003  {
3004  ErrorData *edata;
3005 
3006  /* Save error info */
3007  MemoryContextSwitchTo(oldcontext);
3008  edata = CopyErrorData();
3009  FlushErrorState();
3010 
3011  /* Pass the error data to Tcl */
3012  pltcl_construct_errorCode(interp, edata);
3013  UTF_BEGIN;
3014  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
3015  UTF_END;
3016  FreeErrorData(edata);
3017 
3018  return TCL_ERROR;
3019  }
3020  PG_END_TRY();
3021 
3022  return TCL_OK;
3023 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void SPI_rollback(void)
Definition: spi.c:240
void FlushErrorState(void)
Definition: elog.c:1587
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1551
#define UTF_E2U(x)
Definition: pltcl.c:98
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1838
#define UTF_END
Definition: pltcl.c:90
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define UTF_BEGIN
Definition: pltcl.c:85
#define PG_CATCH()
Definition: elog.h:293
void SPI_start_transaction(void)
Definition: spi.c:197
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343

◆ pltcl_ServiceModeHook()

static void pltcl_ServiceModeHook ( int  mode)
static

Definition at line 382 of file pltcl.c.

Referenced by _PG_init().

383 {
384 }

◆ 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 3033 of file pltcl.c.

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

Referenced by pltcl_process_SPI_result().

3035 {
3036  int i;
3037  char *outputstr;
3038  Datum attr;
3039  bool isnull;
3040  const char *attname;
3041  Oid typoutput;
3042  bool typisvarlena;
3043  const char **arrptr;
3044  const char **nameptr;
3045  const char *nullname = NULL;
3046 
3047  /************************************************************
3048  * Prepare pointers for Tcl_SetVar2() below
3049  ************************************************************/
3050  if (arrayname == NULL)
3051  {
3052  arrptr = &attname;
3053  nameptr = &nullname;
3054  }
3055  else
3056  {
3057  arrptr = &arrayname;
3058  nameptr = &attname;
3059 
3060  /*
3061  * When outputting to an array, fill the ".tupno" element with the
3062  * current tuple number. This will be overridden below if ".tupno" is
3063  * in use as an actual field name in the rowtype.
3064  */
3065  Tcl_SetVar2Ex(interp, arrayname, ".tupno", Tcl_NewWideIntObj(tupno), 0);
3066  }
3067 
3068  for (i = 0; i < tupdesc->natts; i++)
3069  {
3070  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3071 
3072  /* ignore dropped attributes */
3073  if (att->attisdropped)
3074  continue;
3075 
3076  /************************************************************
3077  * Get the attribute name
3078  ************************************************************/
3079  UTF_BEGIN;
3080  attname = pstrdup(UTF_E2U(NameStr(att->attname)));
3081  UTF_END;
3082 
3083  /************************************************************
3084  * Get the attributes value
3085  ************************************************************/
3086  attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3087 
3088  /************************************************************
3089  * If there is a value, set the variable
3090  * If not, unset it
3091  *
3092  * Hmmm - Null attributes will cause functions to
3093  * crash if they don't expect them - need something
3094  * smarter here.
3095  ************************************************************/
3096  if (!isnull)
3097  {
3098  getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3099  outputstr = OidOutputFunctionCall(typoutput, attr);
3100  UTF_BEGIN;
3101  Tcl_SetVar2Ex(interp, *arrptr, *nameptr,
3102  Tcl_NewStringObj(UTF_E2U(outputstr), -1), 0);
3103  UTF_END;
3104  pfree(outputstr);
3105  }
3106  else
3107  Tcl_UnsetVar2(interp, *arrptr, *nameptr, 0);
3108 
3109  pfree((char *) attname);
3110  }
3111 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2650
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
char * pstrdup(const char *in)
Definition: mcxt.c:1161
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:82
void pfree(void *pointer)
Definition: mcxt.c:1031
#define UTF_E2U(x)
Definition: pltcl.c:98
NameData attname
Definition: pg_attribute.h:40
#define UTF_END
Definition: pltcl.c:90
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:786
uintptr_t Datum
Definition: postgres.h:365
#define UTF_BEGIN
Definition: pltcl.c:85
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1832
int i
#define NameStr(name)
Definition: c.h:576

◆ pltcl_SetTimer()

static void pltcl_SetTimer ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 361 of file pltcl.c.

Referenced by _PG_init().

362 {
363 }

◆ pltcl_SPI_execute()

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

Definition at line 2317 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().

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

◆ 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 2663 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().

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

◆ pltcl_SPI_lastoid()

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

Definition at line 2880 of file pltcl.c.

References SPI_lastoid.

Referenced by pltcl_init_interp().

2882 {
2883  /*
2884  * Check call syntax
2885  */
2886  if (objc != 1)
2887  {
2888  Tcl_WrongNumArgs(interp, 1, objv, "");
2889  return TCL_ERROR;
2890  }
2891 
2892  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(SPI_lastoid));
2893  return TCL_OK;
2894 }
Oid SPI_lastoid
Definition: spi.c:40

◆ pltcl_SPI_prepare()

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

Definition at line 2536 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().

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

◆ pltcl_subtrans_abort()

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

Definition at line 2288 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().

2290 {
2291  ErrorData *edata;
2292 
2293  /* Save error info */
2294  MemoryContextSwitchTo(oldcontext);
2295  edata = CopyErrorData();
2296  FlushErrorState();
2297 
2298  /* Abort the inner transaction */
2300  MemoryContextSwitchTo(oldcontext);
2301  CurrentResourceOwner = oldowner;
2302 
2303  /* Pass the error data to Tcl */
2304  pltcl_construct_errorCode(interp, edata);
2305  UTF_BEGIN;
2306  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2307  UTF_END;
2308  FreeErrorData(edata);
2309 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void FlushErrorState(void)
Definition: elog.c:1587
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1551
#define UTF_E2U(x)
Definition: pltcl.c:98
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1838
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4251
#define UTF_END
Definition: pltcl.c:90
#define UTF_BEGIN
Definition: pltcl.c:85
char * message
Definition: elog.h:343

◆ pltcl_subtrans_begin()

static void pltcl_subtrans_begin ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2270 of file pltcl.c.

References BeginInternalSubTransaction(), and MemoryContextSwitchTo().

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

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

◆ pltcl_subtrans_commit()

static void pltcl_subtrans_commit ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2279 of file pltcl.c.

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

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

2280 {
2281  /* Commit the inner transaction, return to outer xact context */
2283  MemoryContextSwitchTo(oldcontext);
2284  CurrentResourceOwner = oldowner;
2285 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4217
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 2904 of file pltcl.c.

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

Referenced by pltcl_init_interp().

2906 {
2907  MemoryContext oldcontext = CurrentMemoryContext;
2909  int retcode;
2910 
2911  if (objc != 2)
2912  {
2913  Tcl_WrongNumArgs(interp, 1, objv, "command");
2914  return TCL_ERROR;
2915  }
2916 
2917  /*
2918  * Note: we don't use pltcl_subtrans_begin and friends here because we
2919  * don't want the error handling in pltcl_subtrans_abort. But otherwise
2920  * the processing should be about the same as in those functions.
2921  */
2923  MemoryContextSwitchTo(oldcontext);
2924 
2925  retcode = Tcl_EvalObjEx(interp, objv[1], 0);
2926 
2927  if (retcode == TCL_ERROR)
2928  {
2929  /* Rollback the subtransaction */
2931  }
2932  else
2933  {
2934  /* Commit the subtransaction */
2936  }
2937 
2938  /* In either case, restore previous memory context and resource owner */
2939  MemoryContextSwitchTo(oldcontext);
2940  CurrentResourceOwner = oldowner;
2941 
2942  return retcode;
2943 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4217
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4251
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4146

◆ pltcl_trigger_handler()

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

Definition at line 1056 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, tupleDesc::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().

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

◆ pltcl_WaitForEvent()

static int pltcl_WaitForEvent ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 387 of file pltcl.c.

Referenced by _PG_init().

388 {
389  return 0;
390 }

◆ pltclu_call_handler()

Datum pltclu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 712 of file pltcl.c.

References pltcl_handler().

Referenced by pltcl_call_handler().

713 {
714  return pltcl_handler(fcinfo, false);
715 }
static Datum pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted)
Definition: pltcl.c:723

◆ start_proc_error_callback()

static void start_proc_error_callback ( void *  arg)
static

Definition at line 680 of file pltcl.c.

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

Referenced by call_pltcl_start_proc().

681 {
682  const char *gucname = (const char *) arg;
683 
684  /* translator: %s is "pltcl.start_proc" or "pltclu.start_proc" */
685  errcontext("processing %s parameter", gucname);
686 }
#define errcontext
Definition: elog.h:164
void * arg

◆ throw_tcl_error()

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

Definition at line 1360 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().

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

◆ utf_e2u()

static char* utf_e2u ( const char *  src)
inlinestatic

Definition at line 80 of file pltcl.c.

References pg_server_to_any(), and PG_UTF8.

Referenced by pltcl_event_trigger_handler(), and pltcl_trigger_handler().

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

◆ utf_u2e()

static char* utf_u2e ( const char *  src)
inlinestatic

Definition at line 74 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().

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

Variable Documentation

◆ exception_name_map

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

Definition at line 255 of file pltcl.c.

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 42 of file pltcl.c.

◆ pltcl_current_call_state

pltcl_call_state* pltcl_current_call_state = NULL
static

Definition at line 244 of file pltcl.c.

Referenced by pltcl_handler(), and pltcl_returnnext().

◆ pltcl_hold_interp

Tcl_Interp* pltcl_hold_interp = NULL
static

Definition at line 239 of file pltcl.c.

Referenced by _PG_init(), and pltcl_init_interp().

◆ pltcl_interp_htab

HTAB* pltcl_interp_htab = NULL
static

Definition at line 240 of file pltcl.c.

◆ pltcl_pm_init_done

bool pltcl_pm_init_done = false
static

Definition at line 238 of file pltcl.c.

Referenced by _PG_init().

◆ pltcl_proc_htab

HTAB* pltcl_proc_htab = NULL
static

Definition at line 241 of file pltcl.c.

◆ pltcl_start_proc

char* pltcl_start_proc = NULL
static

Definition at line 236 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 237 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().