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 403 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.

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

◆ call_pltcl_start_proc()

static void call_pltcl_start_proc ( Oid  prolang,
bool  pltrusted 
)
static

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

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

References ALLOCSET_SMALL_SIZES, AllocSetContextCreateExtended(), Anum_pg_proc_prosrc, pltcl_proc_desc::arg_is_rowtype, pltcl_proc_desc::arg_out_func, Assert, buf, pltcl_proc_desc::domain_info, elog, ereport, errcode(), errmsg(), ERROR, EVTTRIGGEROID, fmgr_info_cxt(), pltcl_proc_desc::fn_cxt, pltcl_proc_desc::fn_is_procedure, 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, MEMCONTEXT_COPY_NAME, MemoryContextDelete(), 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, PROVOLATILE_VOLATILE, pstrdup(), RECORDOID, 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, TRIGGEROID, type_is_rowtype(), TYPEOID, TYPTYPE_DOMAIN, TYPTYPE_PSEUDO, pltcl_proc_key::user_id, pltcl_proc_desc::user_proname, UTF_BEGIN, UTF_E2U, UTF_END, utf_u2e(), and VOIDOID.

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

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

Referenced by _PG_init().

368 {
369 }

◆ pltcl_argisnull()

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

Definition at line 2061 of file pltcl.c.

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

Referenced by pltcl_init_interp().

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

◆ pltcl_build_tuple_argument()

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

Definition at line 3125 of file pltcl.c.

References 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().

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

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

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

◆ pltcl_call_handler()

Datum pltcl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 701 of file pltcl.c.

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

Referenced by start_proc_error_callback().

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

◆ pltcl_commit()

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

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

2960 {
2961  MemoryContext oldcontext = CurrentMemoryContext;
2962 
2963  PG_TRY();
2964  {
2965  SPI_commit();
2967  }
2968  PG_CATCH();
2969  {
2970  ErrorData *edata;
2971 
2972  /* Save error info */
2973  MemoryContextSwitchTo(oldcontext);
2974  edata = CopyErrorData();
2975  FlushErrorState();
2976 
2977  /* Pass the error data to Tcl */
2978  pltcl_construct_errorCode(interp, edata);
2979  UTF_BEGIN;
2980  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2981  UTF_END;
2982  FreeErrorData(edata);
2983 
2984  return TCL_ERROR;
2985  }
2986  PG_END_TRY();
2987 
2988  return TCL_OK;
2989 }
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:1844
#define UTF_END
Definition: pltcl.c:90
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
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 1844 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().

1845 {
1846  Tcl_Obj *obj = Tcl_NewObj();
1847 
1848  Tcl_ListObjAppendElement(interp, obj,
1849  Tcl_NewStringObj("POSTGRES", -1));
1850  Tcl_ListObjAppendElement(interp, obj,
1851  Tcl_NewStringObj(PG_VERSION, -1));
1852  Tcl_ListObjAppendElement(interp, obj,
1853  Tcl_NewStringObj("SQLSTATE", -1));
1854  Tcl_ListObjAppendElement(interp, obj,
1855  Tcl_NewStringObj(unpack_sql_state(edata->sqlerrcode), -1));
1856  Tcl_ListObjAppendElement(interp, obj,
1857  Tcl_NewStringObj("condition", -1));
1858  Tcl_ListObjAppendElement(interp, obj,
1859  Tcl_NewStringObj(pltcl_get_condition_name(edata->sqlerrcode), -1));
1860  Tcl_ListObjAppendElement(interp, obj,
1861  Tcl_NewStringObj("message", -1));
1862  UTF_BEGIN;
1863  Tcl_ListObjAppendElement(interp, obj,
1864  Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1865  UTF_END;
1866  if (edata->detail)
1867  {
1868  Tcl_ListObjAppendElement(interp, obj,
1869  Tcl_NewStringObj("detail", -1));
1870  UTF_BEGIN;
1871  Tcl_ListObjAppendElement(interp, obj,
1872  Tcl_NewStringObj(UTF_E2U(edata->detail), -1));
1873  UTF_END;
1874  }
1875  if (edata->hint)
1876  {
1877  Tcl_ListObjAppendElement(interp, obj,
1878  Tcl_NewStringObj("hint", -1));
1879  UTF_BEGIN;
1880  Tcl_ListObjAppendElement(interp, obj,
1881  Tcl_NewStringObj(UTF_E2U(edata->hint), -1));
1882  UTF_END;
1883  }
1884  if (edata->context)
1885  {
1886  Tcl_ListObjAppendElement(interp, obj,
1887  Tcl_NewStringObj("context", -1));
1888  UTF_BEGIN;
1889  Tcl_ListObjAppendElement(interp, obj,
1890  Tcl_NewStringObj(UTF_E2U(edata->context), -1));
1891  UTF_END;
1892  }
1893  if (edata->schema_name)
1894  {
1895  Tcl_ListObjAppendElement(interp, obj,
1896  Tcl_NewStringObj("schema", -1));
1897  UTF_BEGIN;
1898  Tcl_ListObjAppendElement(interp, obj,
1899  Tcl_NewStringObj(UTF_E2U(edata->schema_name), -1));
1900  UTF_END;
1901  }
1902  if (edata->table_name)
1903  {
1904  Tcl_ListObjAppendElement(interp, obj,
1905  Tcl_NewStringObj("table", -1));
1906  UTF_BEGIN;
1907  Tcl_ListObjAppendElement(interp, obj,
1908  Tcl_NewStringObj(UTF_E2U(edata->table_name), -1));
1909  UTF_END;
1910  }
1911  if (edata->column_name)
1912  {
1913  Tcl_ListObjAppendElement(interp, obj,
1914  Tcl_NewStringObj("column", -1));
1915  UTF_BEGIN;
1916  Tcl_ListObjAppendElement(interp, obj,
1917  Tcl_NewStringObj(UTF_E2U(edata->column_name), -1));
1918  UTF_END;
1919  }
1920  if (edata->datatype_name)
1921  {
1922  Tcl_ListObjAppendElement(interp, obj,
1923  Tcl_NewStringObj("datatype", -1));
1924  UTF_BEGIN;
1925  Tcl_ListObjAppendElement(interp, obj,
1926  Tcl_NewStringObj(UTF_E2U(edata->datatype_name), -1));
1927  UTF_END;
1928  }
1929  if (edata->constraint_name)
1930  {
1931  Tcl_ListObjAppendElement(interp, obj,
1932  Tcl_NewStringObj("constraint", -1));
1933  UTF_BEGIN;
1934  Tcl_ListObjAppendElement(interp, obj,
1935  Tcl_NewStringObj(UTF_E2U(edata->constraint_name), -1));
1936  UTF_END;
1937  }
1938  /* cursorpos is never interesting here; report internal query/pos */
1939  if (edata->internalquery)
1940  {
1941  Tcl_ListObjAppendElement(interp, obj,
1942  Tcl_NewStringObj("statement", -1));
1943  UTF_BEGIN;
1944  Tcl_ListObjAppendElement(interp, obj,
1945  Tcl_NewStringObj(UTF_E2U(edata->internalquery), -1));
1946  UTF_END;
1947  }
1948  if (edata->internalpos > 0)
1949  {
1950  Tcl_ListObjAppendElement(interp, obj,
1951  Tcl_NewStringObj("cursor_position", -1));
1952  Tcl_ListObjAppendElement(interp, obj,
1953  Tcl_NewIntObj(edata->internalpos));
1954  }
1955  if (edata->filename)
1956  {
1957  Tcl_ListObjAppendElement(interp, obj,
1958  Tcl_NewStringObj("filename", -1));
1959  UTF_BEGIN;
1960  Tcl_ListObjAppendElement(interp, obj,
1961  Tcl_NewStringObj(UTF_E2U(edata->filename), -1));
1962  UTF_END;
1963  }
1964  if (edata->lineno > 0)
1965  {
1966  Tcl_ListObjAppendElement(interp, obj,
1967  Tcl_NewStringObj("lineno", -1));
1968  Tcl_ListObjAppendElement(interp, obj,
1969  Tcl_NewIntObj(edata->lineno));
1970  }
1971  if (edata->funcname)
1972  {
1973  Tcl_ListObjAppendElement(interp, obj,
1974  Tcl_NewStringObj("funcname", -1));
1975  UTF_BEGIN;
1976  Tcl_ListObjAppendElement(interp, obj,
1977  Tcl_NewStringObj(UTF_E2U(edata->funcname), -1));
1978  UTF_END;
1979  }
1980 
1981  Tcl_SetObjErrorCode(interp, obj);
1982 }
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:1989
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 372 of file pltcl.c.

Referenced by _PG_init().

374 {
375 }

◆ pltcl_DeleteFileHandler()

static void pltcl_DeleteFileHandler ( int  fd)
static

Definition at line 378 of file pltcl.c.

Referenced by _PG_init().

379 {
380 }

◆ pltcl_elog()

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

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

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

1315 {
1316  pltcl_proc_desc *prodesc;
1317  Tcl_Interp *volatile interp;
1318  EventTriggerData *tdata = (EventTriggerData *) fcinfo->context;
1319  Tcl_Obj *tcl_cmd;
1320  int tcl_rc;
1321 
1322  /* Connect to SPI manager */
1323  if (SPI_connect() != SPI_OK_CONNECT)
1324  elog(ERROR, "could not connect to SPI manager");
1325 
1326  /* Find or compile the function */
1327  prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1328  InvalidOid, true, pltrusted);
1329 
1330  call_state->prodesc = prodesc;
1331  prodesc->fn_refcount++;
1332 
1333  interp = prodesc->interp_desc->interp;
1334 
1335  /* Create the tcl command and call the internal proc */
1336  tcl_cmd = Tcl_NewObj();
1337  Tcl_IncrRefCount(tcl_cmd);
1338  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1339  Tcl_NewStringObj(prodesc->internal_proname, -1));
1340  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1341  Tcl_NewStringObj(utf_e2u(tdata->event), -1));
1342  Tcl_ListObjAppendElement(NULL, tcl_cmd,
1343  Tcl_NewStringObj(utf_e2u(tdata->tag), -1));
1344 
1345  tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
1346 
1347  /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1348  Tcl_DecrRefCount(tcl_cmd);
1349 
1350  /* Check for errors reported by Tcl. */
1351  if (tcl_rc != TCL_OK)
1352  throw_tcl_error(interp, prodesc->user_proname);
1353 
1354  if (SPI_finish() != SPI_OK_FINISH)
1355  elog(ERROR, "SPI_finish() failed");
1356 }
#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:1363
#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:1392
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:217
#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 563 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().

564 {
565  Oid user_id;
566  pltcl_interp_desc *interp_desc;
567  bool found;
568 
569  /* Find or create the interpreter hashtable entry for this userid */
570  if (pltrusted)
571  user_id = GetUserId();
572  else
573  user_id = InvalidOid;
574 
575  interp_desc = hash_search(pltcl_interp_htab, &user_id,
576  HASH_ENTER,
577  &found);
578  if (!found)
579  interp_desc->interp = NULL;
580 
581  /* If we haven't yet successfully made an interpreter, try to do that */
582  if (!interp_desc->interp)
583  pltcl_init_interp(interp_desc, prolang, pltrusted);
584 
585  return interp_desc;
586 }
static void pltcl_init_interp(pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
Definition: pltcl.c:488
Oid GetUserId(void)
Definition: miscinit.c:284
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:904
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:241

◆ pltcl_FinalizeNotifier()

static void pltcl_FinalizeNotifier ( ClientData  clientData)
static

Definition at line 357 of file pltcl.c.

Referenced by _PG_init().

358 {
359 }

◆ pltcl_func_handler()

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

Definition at line 805 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_is_procedure, 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().

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

◆ pltcl_get_condition_name()

static const char * pltcl_get_condition_name ( int  sqlstate)
static

Definition at line 1989 of file pltcl.c.

References i, and TclExceptionNameMap::label.

Referenced by pltcl_construct_errorCode().

1990 {
1991  int i;
1992 
1993  for (i = 0; exception_name_map[i].label != NULL; i++)
1994  {
1995  if (exception_name_map[i].sqlerrstate == sqlstate)
1996  return exception_name_map[i].label;
1997  }
1998  return "unrecognized_sqlstate";
1999 }
static const TclExceptionNameMap exception_name_map[]
Definition: pltcl.c:256
const char * label
Definition: pltcl.c:252
int i

◆ pltcl_handler()

static Datum pltcl_handler ( PG_FUNCTION_ARGS  ,
bool  pltrusted 
)
static

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

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

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

◆ pltcl_init_tuple_store()

static void pltcl_init_tuple_store ( pltcl_call_state call_state)
static

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

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

◆ pltcl_InitNotifier()

static ClientData pltcl_InitNotifier ( void  )
static

Definition at line 349 of file pltcl.c.

Referenced by _PG_init().

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

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

2438 {
2439  int my_rc = TCL_OK;
2440  int loop_rc;
2441  HeapTuple *tuples;
2442  TupleDesc tupdesc;
2443 
2444  switch (spi_rc)
2445  {
2446  case SPI_OK_SELINTO:
2447  case SPI_OK_INSERT:
2448  case SPI_OK_DELETE:
2449  case SPI_OK_UPDATE:
2450  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2451  break;
2452 
2453  case SPI_OK_UTILITY:
2454  case SPI_OK_REWRITTEN:
2455  if (tuptable == NULL)
2456  {
2457  Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
2458  break;
2459  }
2460  /* FALL THRU for utility returning tuples */
2461 
2462  case SPI_OK_SELECT:
2466 
2467  /*
2468  * Process the tuples we got
2469  */
2470  tuples = tuptable->vals;
2471  tupdesc = tuptable->tupdesc;
2472 
2473  if (loop_body == NULL)
2474  {
2475  /*
2476  * If there is no loop body given, just set the variables from
2477  * the first tuple (if any)
2478  */
2479  if (ntuples > 0)
2480  pltcl_set_tuple_values(interp, arrayname, 0,
2481  tuples[0], tupdesc);
2482  }
2483  else
2484  {
2485  /*
2486  * There is a loop body - process all tuples and evaluate the
2487  * body on each
2488  */
2489  uint64 i;
2490 
2491  for (i = 0; i < ntuples; i++)
2492  {
2493  pltcl_set_tuple_values(interp, arrayname, i,
2494  tuples[i], tupdesc);
2495 
2496  loop_rc = Tcl_EvalObjEx(interp, loop_body, 0);
2497 
2498  if (loop_rc == TCL_OK)
2499  continue;
2500  if (loop_rc == TCL_CONTINUE)
2501  continue;
2502  if (loop_rc == TCL_RETURN)
2503  {
2504  my_rc = TCL_RETURN;
2505  break;
2506  }
2507  if (loop_rc == TCL_BREAK)
2508  break;
2509  my_rc = TCL_ERROR;
2510  break;
2511  }
2512  }
2513 
2514  if (my_rc == TCL_OK)
2515  {
2516  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2517  }
2518  break;
2519 
2520  default:
2521  Tcl_AppendResult(interp, "pltcl: SPI_execute failed: ",
2522  SPI_result_code_string(spi_rc), NULL);
2523  my_rc = TCL_ERROR;
2524  break;
2525  }
2526 
2527  SPI_freetuptable(tuptable);
2528 
2529  return my_rc;
2530 }
#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:3039

◆ pltcl_quote()

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

Definition at line 2007 of file pltcl.c.

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

Referenced by pltcl_init_interp().

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

◆ pltcl_returnnext()

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

Definition at line 2153 of file pltcl.c.

References BeginInternalSubTransaction(), CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, pltcl_call_state::fcinfo, pltcl_proc_desc::fn_is_procedure, 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().

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

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

Referenced by pltcl_init_interp().

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

◆ pltcl_rollback()

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

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

3000 {
3001  MemoryContext oldcontext = CurrentMemoryContext;
3002 
3003  PG_TRY();
3004  {
3005  SPI_rollback();
3007  }
3008  PG_CATCH();
3009  {
3010  ErrorData *edata;
3011 
3012  /* Save error info */
3013  MemoryContextSwitchTo(oldcontext);
3014  edata = CopyErrorData();
3015  FlushErrorState();
3016 
3017  /* Pass the error data to Tcl */
3018  pltcl_construct_errorCode(interp, edata);
3019  UTF_BEGIN;
3020  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
3021  UTF_END;
3022  FreeErrorData(edata);
3023 
3024  return TCL_ERROR;
3025  }
3026  PG_END_TRY();
3027 
3028  return TCL_OK;
3029 }
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:1844
#define UTF_END
Definition: pltcl.c:90
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#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 383 of file pltcl.c.

Referenced by _PG_init().

384 {
385 }

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

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

Referenced by pltcl_process_SPI_result().

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

◆ pltcl_SetTimer()

static void pltcl_SetTimer ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 362 of file pltcl.c.

Referenced by _PG_init().

363 {
364 }

◆ pltcl_SPI_execute()

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

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

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

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

References SPI_lastoid.

Referenced by pltcl_init_interp().

2888 {
2889  /*
2890  * Check call syntax
2891  */
2892  if (objc != 1)
2893  {
2894  Tcl_WrongNumArgs(interp, 1, objv, "");
2895  return TCL_ERROR;
2896  }
2897 
2898  Tcl_SetObjResult(interp, Tcl_NewWideIntObj(SPI_lastoid));
2899  return TCL_OK;
2900 }
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 2542 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().

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

2296 {
2297  ErrorData *edata;
2298 
2299  /* Save error info */
2300  MemoryContextSwitchTo(oldcontext);
2301  edata = CopyErrorData();
2302  FlushErrorState();
2303 
2304  /* Abort the inner transaction */
2306  MemoryContextSwitchTo(oldcontext);
2307  CurrentResourceOwner = oldowner;
2308 
2309  /* Pass the error data to Tcl */
2310  pltcl_construct_errorCode(interp, edata);
2311  UTF_BEGIN;
2312  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2313  UTF_END;
2314  FreeErrorData(edata);
2315 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
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:1844
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4277
#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 2276 of file pltcl.c.

References BeginInternalSubTransaction(), and MemoryContextSwitchTo().

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

2277 {
2279 
2280  /* Want to run inside function's memory context */
2281  MemoryContextSwitchTo(oldcontext);
2282 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4172

◆ pltcl_subtrans_commit()

static void pltcl_subtrans_commit ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2285 of file pltcl.c.

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

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

2286 {
2287  /* Commit the inner transaction, return to outer xact context */
2289  MemoryContextSwitchTo(oldcontext);
2290  CurrentResourceOwner = oldowner;
2291 }
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4243
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 2910 of file pltcl.c.

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

Referenced by pltcl_init_interp().

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

◆ pltcl_trigger_handler()

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

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

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

Referenced by _PG_init().

389 {
390  return 0;
391 }

◆ pltclu_call_handler()

Datum pltclu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 713 of file pltcl.c.

References pltcl_handler().

Referenced by pltcl_call_handler().

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

◆ start_proc_error_callback()

static void start_proc_error_callback ( void *  arg)
static

Definition at line 681 of file pltcl.c.

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

Referenced by call_pltcl_start_proc().

682 {
683  const char *gucname = (const char *) arg;
684 
685  /* translator: %s is "pltcl.start_proc" or "pltclu.start_proc" */
686  errcontext("processing %s parameter", gucname);
687 }
#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 1363 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().

1364 {
1365  /*
1366  * Caution is needed here because Tcl_GetVar could overwrite the
1367  * interpreter result (even though it's not really supposed to), and we
1368  * can't control the order of evaluation of ereport arguments. Hence, make
1369  * real sure we have our own copy of the result string before invoking
1370  * Tcl_GetVar.
1371  */
1372  char *emsg;
1373  char *econtext;
1374 
1375  emsg = pstrdup(utf_u2e(Tcl_GetStringResult(interp)));
1376  econtext = utf_u2e(Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY));
1377  ereport(ERROR,
1378  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1379  errmsg("%s", emsg),
1380  errcontext("%s\nin PL/Tcl function \"%s\"",
1381  econtext, proname)));
1382 }
char * pstrdup(const char *in)
Definition: mcxt.c:1063
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 256 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 245 of file pltcl.c.

Referenced by pltcl_handler(), and pltcl_returnnext().

◆ pltcl_hold_interp

Tcl_Interp* pltcl_hold_interp = NULL
static

Definition at line 240 of file pltcl.c.

Referenced by _PG_init(), and pltcl_init_interp().

◆ pltcl_interp_htab

HTAB* pltcl_interp_htab = NULL
static

Definition at line 241 of file pltcl.c.

◆ pltcl_pm_init_done

bool pltcl_pm_init_done = false
static

Definition at line 239 of file pltcl.c.

Referenced by _PG_init().

◆ pltcl_proc_htab

HTAB* pltcl_proc_htab = NULL
static

Definition at line 242 of file pltcl.c.

◆ pltcl_start_proc

char* pltcl_start_proc = NULL
static

Definition at line 237 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().

◆ pltclu_start_proc

char* pltclu_start_proc = NULL
static

Definition at line 238 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().