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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

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

Variables

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

Macro Definition Documentation

◆ CONST86

#define CONST86

Definition at line 56 of file pltcl.c.

◆ HAVE_TCL_VERSION

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

Definition at line 45 of file pltcl.c.

◆ TEXTDOMAIN

#define TEXTDOMAIN   PG_TEXTDOMAIN("pltcl")

Definition at line 61 of file pltcl.c.

◆ UTF_BEGIN

#define UTF_BEGIN
Value:
do { \
const char *_pltcl_utf_src = NULL; \
char *_pltcl_utf_dst = NULL

Definition at line 86 of file pltcl.c.

◆ UTF_E2U

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

Definition at line 99 of file pltcl.c.

◆ UTF_END

#define UTF_END
Value:
if (_pltcl_utf_src != (const char *) _pltcl_utf_dst) \
pfree(_pltcl_utf_dst); \
} while (0)

Definition at line 91 of file pltcl.c.

◆ UTF_U2E

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

Definition at line 96 of file pltcl.c.

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

401 {
402  Tcl_NotifierProcs notifier;
403  HASHCTL hash_ctl;
404 
405  /* Be sure we do initialization only once (should be redundant now) */
406  if (pltcl_pm_init_done)
407  return;
408 
410 
411 #ifdef WIN32
412  /* Required on win32 to prevent error loading init.tcl */
413  Tcl_FindExecutable("");
414 #endif
415 
416  /*
417  * Override the functions in the Notifier subsystem. See comments above.
418  */
419  notifier.setTimerProc = pltcl_SetTimer;
420  notifier.waitForEventProc = pltcl_WaitForEvent;
421  notifier.createFileHandlerProc = pltcl_CreateFileHandler;
422  notifier.deleteFileHandlerProc = pltcl_DeleteFileHandler;
423  notifier.initNotifierProc = pltcl_InitNotifier;
424  notifier.finalizeNotifierProc = pltcl_FinalizeNotifier;
425  notifier.alertNotifierProc = pltcl_AlertNotifier;
426  notifier.serviceModeHookProc = pltcl_ServiceModeHook;
427  Tcl_SetNotifier(&notifier);
428 
429  /************************************************************
430  * Create the dummy hold interpreter to prevent close of
431  * stdout and stderr on DeleteInterp
432  ************************************************************/
433  if ((pltcl_hold_interp = Tcl_CreateInterp()) == NULL)
434  elog(ERROR, "could not create dummy Tcl interpreter");
435  if (Tcl_Init(pltcl_hold_interp) == TCL_ERROR)
436  elog(ERROR, "could not initialize dummy Tcl interpreter");
437 
438  /************************************************************
439  * Create the hash table for working interpreters
440  ************************************************************/
441  hash_ctl.keysize = sizeof(Oid);
442  hash_ctl.entrysize = sizeof(pltcl_interp_desc);
443  pltcl_interp_htab = hash_create("PL/Tcl interpreters",
444  8,
445  &hash_ctl,
447 
448  /************************************************************
449  * Create the hash table for function lookup
450  ************************************************************/
451  hash_ctl.keysize = sizeof(pltcl_proc_key);
452  hash_ctl.entrysize = sizeof(pltcl_proc_ptr);
453  pltcl_proc_htab = hash_create("PL/Tcl functions",
454  100,
455  &hash_ctl,
457 
458  /************************************************************
459  * Define PL/Tcl's custom GUCs
460  ************************************************************/
461  DefineCustomStringVariable("pltcl.start_proc",
462  gettext_noop("PL/Tcl function to call once when pltcl is first used."),
463  NULL,
465  NULL,
466  PGC_SUSET, 0,
467  NULL, NULL, NULL);
468  DefineCustomStringVariable("pltclu.start_proc",
469  gettext_noop("PL/TclU function to call once when pltclu is first used."),
470  NULL,
472  NULL,
473  PGC_SUSET, 0,
474  NULL, NULL, NULL);
475 
476  MarkGUCPrefixReserved("pltcl");
477  MarkGUCPrefixReserved("pltclu");
478 
479  pltcl_pm_init_done = true;
480 }
#define gettext_noop(x)
Definition: c.h:1135
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#define ERROR
Definition: elog.h:35
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:5026
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5087
@ PGC_SUSET
Definition: guc.h:74
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1867
static void pltcl_ServiceModeHook(int mode)
Definition: pltcl.c:380
static HTAB * pltcl_proc_htab
Definition: pltcl.c:242
static void pltcl_AlertNotifier(ClientData clientData)
Definition: pltcl.c:364
static int pltcl_WaitForEvent(CONST86 Tcl_Time *timePtr)
Definition: pltcl.c:385
static void pltcl_SetTimer(CONST86 Tcl_Time *timePtr)
Definition: pltcl.c:359
static void pltcl_DeleteFileHandler(int fd)
Definition: pltcl.c:375
static void pltcl_FinalizeNotifier(ClientData clientData)
Definition: pltcl.c:354
static void pltcl_CreateFileHandler(int fd, int mask, Tcl_FileProc *proc, ClientData clientData)
Definition: pltcl.c:369
static char * pltcl_start_proc
Definition: pltcl.c:237
static HTAB * pltcl_interp_htab
Definition: pltcl.c:241
struct pltcl_proc_key pltcl_proc_key
#define TEXTDOMAIN
Definition: pltcl.c:61
struct pltcl_interp_desc pltcl_interp_desc
static char * pltclu_start_proc
Definition: pltcl.c:238
static ClientData pltcl_InitNotifier(void)
Definition: pltcl.c:346
static Tcl_Interp * pltcl_hold_interp
Definition: pltcl.c:240
static bool pltcl_pm_init_done
Definition: pltcl.c:239
struct pltcl_proc_ptr pltcl_proc_ptr
unsigned int Oid
Definition: postgres_ext.h:31
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76

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

◆ call_pltcl_start_proc()

static void call_pltcl_start_proc ( Oid  prolang,
bool  pltrusted 
)
static

Definition at line 589 of file pltcl.c.

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

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

Referenced by pltcl_init_interp().

◆ compile_pltcl_function()

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

Definition at line 1389 of file pltcl.c.

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

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

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

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

365 {
366 }

Referenced by _PG_init().

◆ pltcl_argisnull()

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

Definition at line 2055 of file pltcl.c.

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

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

Referenced by pltcl_init_interp().

◆ pltcl_build_tuple_argument()

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

Definition at line 3093 of file pltcl.c.

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

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

Referenced by pltcl_func_handler(), and pltcl_trigger_handler().

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

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

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

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

◆ pltcl_call_handler()

Datum pltcl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 696 of file pltcl.c.

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

References pltcl_handler().

◆ pltcl_commit()

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

Definition at line 2928 of file pltcl.c.

2930 {
2931  MemoryContext oldcontext = CurrentMemoryContext;
2932 
2933  PG_TRY();
2934  {
2935  SPI_commit();
2936  }
2937  PG_CATCH();
2938  {
2939  ErrorData *edata;
2940 
2941  /* Save error info */
2942  MemoryContextSwitchTo(oldcontext);
2943  edata = CopyErrorData();
2944  FlushErrorState();
2945 
2946  /* Pass the error data to Tcl */
2947  pltcl_construct_errorCode(interp, edata);
2948  UTF_BEGIN;
2949  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2950  UTF_END;
2951  FreeErrorData(edata);
2952 
2953  return TCL_ERROR;
2954  }
2955  PG_END_TRY();
2956 
2957  return TCL_OK;
2958 }
void FreeErrorData(ErrorData *edata)
Definition: elog.c:1613
void FlushErrorState(void)
Definition: elog.c:1651
ErrorData * CopyErrorData(void)
Definition: elog.c:1557
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
Definition: pltcl.c:1838
void SPI_commit(void)
Definition: spi.c:321
char * message
Definition: elog.h:378

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

Referenced by pltcl_init_interp().

◆ pltcl_construct_errorCode()

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

Definition at line 1838 of file pltcl.c.

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

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

◆ pltcl_CreateFileHandler()

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

Definition at line 369 of file pltcl.c.

371 {
372 }

Referenced by _PG_init().

◆ pltcl_DeleteFileHandler()

static void pltcl_DeleteFileHandler ( int  fd)
static

Definition at line 375 of file pltcl.c.

376 {
377 }

Referenced by _PG_init().

◆ pltcl_elog()

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

Definition at line 1751 of file pltcl.c.

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

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

◆ pltcl_event_trigger_handler()

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

Definition at line 1309 of file pltcl.c.

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

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

◆ pltcl_fetch_interp()

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

Definition at line 559 of file pltcl.c.

560 {
561  Oid user_id;
562  pltcl_interp_desc *interp_desc;
563  bool found;
564 
565  /* Find or create the interpreter hashtable entry for this userid */
566  if (pltrusted)
567  user_id = GetUserId();
568  else
569  user_id = InvalidOid;
570 
571  interp_desc = hash_search(pltcl_interp_htab, &user_id,
572  HASH_ENTER,
573  &found);
574  if (!found)
575  interp_desc->interp = NULL;
576 
577  /* If we haven't yet successfully made an interpreter, try to do that */
578  if (!interp_desc->interp)
579  pltcl_init_interp(interp_desc, prolang, pltrusted);
580 
581  return interp_desc;
582 }
static void pltcl_init_interp(pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
Definition: pltcl.c:486

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

Referenced by compile_pltcl_function().

◆ pltcl_FinalizeNotifier()

static void pltcl_FinalizeNotifier ( ClientData  clientData)
static

Definition at line 354 of file pltcl.c.

355 {
356 }

Referenced by _PG_init().

◆ pltcl_func_handler()

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

Definition at line 793 of file pltcl.c.

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

References ReturnSetInfo::allowedModes, pltcl_proc_desc::arg_is_rowtype, pltcl_proc_desc::arg_out_func, Assert(), pltcl_call_state::attinmeta, castNode, compile_pltcl_function(), CreateTupleDescCopy(), CurrentResourceOwner, DatumGetHeapTupleHeader, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog(), ereport, errcode(), errmsg(), ERROR, pltcl_proc_desc::fn_refcount, pltcl_proc_desc::fn_retisdomain, pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, get_call_result_type(), HeapTupleGetDatum(), HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, i, if(), 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().

◆ pltcl_get_condition_name()

static const char * pltcl_get_condition_name ( int  sqlstate)
static

Definition at line 1983 of file pltcl.c.

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

References exception_name_map, i, and TclExceptionNameMap::label.

Referenced by pltcl_construct_errorCode().

◆ pltcl_handler()

static Datum pltcl_handler ( PG_FUNCTION_ARGS  ,
bool  pltrusted 
)
static

Definition at line 719 of file pltcl.c.

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

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

Referenced by pltcl_call_handler(), and pltclu_call_handler().

◆ pltcl_init_interp()

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

Definition at line 486 of file pltcl.c.

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

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

Referenced by pltcl_fetch_interp().

◆ pltcl_init_tuple_store()

static void pltcl_init_tuple_store ( pltcl_call_state call_state)
static

Definition at line 3253 of file pltcl.c.

3254 {
3255  ReturnSetInfo *rsi = call_state->rsi;
3256  MemoryContext oldcxt;
3257  ResourceOwner oldowner;
3258 
3259  /* Should be in a SRF */
3260  Assert(rsi);
3261  /* Should be first time through */
3262  Assert(!call_state->tuple_store);
3263  Assert(!call_state->attinmeta);
3264 
3265  /* We expect caller to provide an appropriate result tupdesc */
3266  Assert(rsi->expectedDesc);
3267  call_state->ret_tupdesc = rsi->expectedDesc;
3268 
3269  /*
3270  * Switch to the right memory context and resource owner for storing the
3271  * tuplestore. If we're within a subtransaction opened for an exception
3272  * block, for example, we must still create the tuplestore in the resource
3273  * owner that was active when this function was entered, and not in the
3274  * subtransaction's resource owner.
3275  */
3276  oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
3277  oldowner = CurrentResourceOwner;
3279 
3280  call_state->tuple_store =
3282  false, work_mem);
3283 
3284  /* Build attinmeta in this context, too */
3285  call_state->attinmeta = TupleDescGetAttInMetadata(call_state->ret_tupdesc);
3286 
3287  CurrentResourceOwner = oldowner;
3288  MemoryContextSwitchTo(oldcxt);
3289 }
@ SFRM_Materialize_Random
Definition: execnodes.h:310
int work_mem
Definition: globals.c:125
TupleDesc expectedDesc
Definition: execnodes.h:325
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318

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

◆ pltcl_InitNotifier()

static ClientData pltcl_InitNotifier ( void  )
static

Definition at line 346 of file pltcl.c.

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

Referenced by _PG_init().

◆ pltcl_process_SPI_result()

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

Definition at line 2426 of file pltcl.c.

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

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

◆ pltcl_quote()

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

Definition at line 2001 of file pltcl.c.

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

References palloc(), and pfree().

Referenced by pltcl_init_interp().

◆ pltcl_returnnext()

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

Definition at line 2147 of file pltcl.c.

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

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

Referenced by pltcl_init_interp().

◆ pltcl_returnnull()

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

Definition at line 2109 of file pltcl.c.

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

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

Referenced by pltcl_init_interp().

◆ pltcl_rollback()

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

Definition at line 2967 of file pltcl.c.

2969 {
2970  MemoryContext oldcontext = CurrentMemoryContext;
2971 
2972  PG_TRY();
2973  {
2974  SPI_rollback();
2975  }
2976  PG_CATCH();
2977  {
2978  ErrorData *edata;
2979 
2980  /* Save error info */
2981  MemoryContextSwitchTo(oldcontext);
2982  edata = CopyErrorData();
2983  FlushErrorState();
2984 
2985  /* Pass the error data to Tcl */
2986  pltcl_construct_errorCode(interp, edata);
2987  UTF_BEGIN;
2988  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2989  UTF_END;
2990  FreeErrorData(edata);
2991 
2992  return TCL_ERROR;
2993  }
2994  PG_END_TRY();
2995 
2996  return TCL_OK;
2997 }
void SPI_rollback(void)
Definition: spi.c:414

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

Referenced by pltcl_init_interp().

◆ pltcl_ServiceModeHook()

static void pltcl_ServiceModeHook ( int  mode)
static

Definition at line 380 of file pltcl.c.

381 {
382 }

Referenced by _PG_init().

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

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

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

Referenced by pltcl_process_SPI_result().

◆ pltcl_SetTimer()

static void pltcl_SetTimer ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 359 of file pltcl.c.

360 {
361 }

Referenced by _PG_init().

◆ pltcl_SPI_execute()

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

Definition at line 2317 of file pltcl.c.

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

References CurrentMemoryContext, CurrentResourceOwner, pltcl_proc_desc::fn_readonly, i, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_current_call_state, 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().

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

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

References pltcl_query_desc::arginfuncs, pltcl_query_desc::argtypioparams, CurrentMemoryContext, CurrentResourceOwner, pltcl_proc_desc::fn_readonly, i, InputFunctionCall(), pltcl_proc_desc::interp_desc, j, pltcl_query_desc::nargs, palloc(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_query_desc::plan, pltcl_current_call_state, 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().

◆ pltcl_SPI_prepare()

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

Definition at line 2537 of file pltcl.c.

2539 {
2540  volatile MemoryContext plan_cxt = NULL;
2541  int nargs;
2542  Tcl_Obj **argsObj;
2543  pltcl_query_desc *qdesc;
2544  int i;
2545  Tcl_HashEntry *hashent;
2546  int hashnew;
2547  Tcl_HashTable *query_hash;
2548  MemoryContext oldcontext = CurrentMemoryContext;
2550 
2551  /************************************************************
2552  * Check the call syntax
2553  ************************************************************/
2554  if (objc != 3)
2555  {
2556  Tcl_WrongNumArgs(interp, 1, objv, "query argtypes");
2557  return TCL_ERROR;
2558  }
2559 
2560  /************************************************************
2561  * Split the argument type list
2562  ************************************************************/
2563  if (Tcl_ListObjGetElements(interp, objv[2], &nargs, &argsObj) != TCL_OK)
2564  return TCL_ERROR;
2565 
2566  /************************************************************
2567  * Allocate the new querydesc structure
2568  *
2569  * struct qdesc and subsidiary data all live in plan_cxt. Note that if the
2570  * function is recompiled for whatever reason, permanent memory leaks
2571  * occur. FIXME someday.
2572  ************************************************************/
2574  "PL/Tcl spi_prepare query",
2576  MemoryContextSwitchTo(plan_cxt);
2577  qdesc = (pltcl_query_desc *) palloc0(sizeof(pltcl_query_desc));
2578  snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
2579  qdesc->nargs = nargs;
2580  qdesc->argtypes = (Oid *) palloc(nargs * sizeof(Oid));
2581  qdesc->arginfuncs = (FmgrInfo *) palloc(nargs * sizeof(FmgrInfo));
2582  qdesc->argtypioparams = (Oid *) palloc(nargs * sizeof(Oid));
2583  MemoryContextSwitchTo(oldcontext);
2584 
2585  /************************************************************
2586  * Execute the prepare inside a sub-transaction, so we can cope with
2587  * errors sanely
2588  ************************************************************/
2589 
2590  pltcl_subtrans_begin(oldcontext, oldowner);
2591 
2592  PG_TRY();
2593  {
2594  /************************************************************
2595  * Resolve argument type names and then look them up by oid
2596  * in the system cache, and remember the required information
2597  * for input conversion.
2598  ************************************************************/
2599  for (i = 0; i < nargs; i++)
2600  {
2601  Oid typId,
2602  typInput,
2603  typIOParam;
2604  int32 typmod;
2605 
2606  parseTypeString(Tcl_GetString(argsObj[i]), &typId, &typmod, false);
2607 
2608  getTypeInputInfo(typId, &typInput, &typIOParam);
2609 
2610  qdesc->argtypes[i] = typId;
2611  fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
2612  qdesc->argtypioparams[i] = typIOParam;
2613  }
2614 
2615  /************************************************************
2616  * Prepare the plan and check for errors
2617  ************************************************************/
2618  UTF_BEGIN;
2619  qdesc->plan = SPI_prepare(UTF_U2E(Tcl_GetString(objv[1])),
2620  nargs, qdesc->argtypes);
2621  UTF_END;
2622 
2623  if (qdesc->plan == NULL)
2624  elog(ERROR, "SPI_prepare() failed");
2625 
2626  /************************************************************
2627  * Save the plan into permanent memory (right now it's in the
2628  * SPI procCxt, which will go away at function end).
2629  ************************************************************/
2630  if (SPI_keepplan(qdesc->plan))
2631  elog(ERROR, "SPI_keepplan() failed");
2632 
2633  pltcl_subtrans_commit(oldcontext, oldowner);
2634  }
2635  PG_CATCH();
2636  {
2637  pltcl_subtrans_abort(interp, oldcontext, oldowner);
2638 
2639  MemoryContextDelete(plan_cxt);
2640 
2641  return TCL_ERROR;
2642  }
2643  PG_END_TRY();
2644 
2645  /************************************************************
2646  * Insert a hashtable entry for the plan and return
2647  * the key to the caller
2648  ************************************************************/
2650 
2651  hashent = Tcl_CreateHashEntry(query_hash, qdesc->qname, &hashnew);
2652  Tcl_SetHashValue(hashent, (ClientData) qdesc);
2653 
2654  /* qname is ASCII, so no need for encoding conversion */
2655  Tcl_SetObjResult(interp, Tcl_NewStringObj(qdesc->qname, -1));
2656  return TCL_OK;
2657 }
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2832
void parseTypeString(const char *str, Oid *typeid_p, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:780
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:858
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:974
char qname[20]
Definition: pltcl.c:166
Oid * argtypes
Definition: pltcl.c:169

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_current_call_state, 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().

◆ pltcl_subtrans_abort()

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

Definition at line 2288 of file pltcl.c.

2290 {
2291  ErrorData *edata;
2292 
2293  /* Save error info */
2294  MemoryContextSwitchTo(oldcontext);
2295  edata = CopyErrorData();
2296  FlushErrorState();
2297 
2298  /* Abort the inner transaction */
2300  MemoryContextSwitchTo(oldcontext);
2301  CurrentResourceOwner = oldowner;
2302 
2303  /* Pass the error data to Tcl */
2304  pltcl_construct_errorCode(interp, edata);
2305  UTF_BEGIN;
2306  Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2307  UTF_END;
2308  FreeErrorData(edata);
2309 }
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4625

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

◆ pltcl_subtrans_begin()

static void pltcl_subtrans_begin ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2270 of file pltcl.c.

2271 {
2273 
2274  /* Want to run inside function's memory context */
2275  MemoryContextSwitchTo(oldcontext);
2276 }

References BeginInternalSubTransaction(), and MemoryContextSwitchTo().

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

◆ pltcl_subtrans_commit()

static void pltcl_subtrans_commit ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2279 of file pltcl.c.

2280 {
2281  /* Commit the inner transaction, return to outer xact context */
2283  MemoryContextSwitchTo(oldcontext);
2284  CurrentResourceOwner = oldowner;
2285 }
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4591

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

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

◆ pltcl_subtransaction()

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

Definition at line 2880 of file pltcl.c.

2882 {
2883  MemoryContext oldcontext = CurrentMemoryContext;
2885  int retcode;
2886 
2887  if (objc != 2)
2888  {
2889  Tcl_WrongNumArgs(interp, 1, objv, "command");
2890  return TCL_ERROR;
2891  }
2892 
2893  /*
2894  * Note: we don't use pltcl_subtrans_begin and friends here because we
2895  * don't want the error handling in pltcl_subtrans_abort. But otherwise
2896  * the processing should be about the same as in those functions.
2897  */
2899  MemoryContextSwitchTo(oldcontext);
2900 
2901  retcode = Tcl_EvalObjEx(interp, objv[1], 0);
2902 
2903  if (retcode == TCL_ERROR)
2904  {
2905  /* Rollback the subtransaction */
2907  }
2908  else
2909  {
2910  /* Commit the subtransaction */
2912  }
2913 
2914  /* In either case, restore previous memory context and resource owner */
2915  MemoryContextSwitchTo(oldcontext);
2916  CurrentResourceOwner = oldowner;
2917 
2918  return retcode;
2919 }

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

Referenced by pltcl_init_interp().

◆ pltcl_trigger_handler()

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

Definition at line 1049 of file pltcl.c.

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

References Assert(), compile_pltcl_function(), DatumGetCString(), DirectFunctionCall1, elog(), ereport, errcode(), errmsg(), ERROR, pltcl_proc_desc::fn_refcount, i, if(), pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, NameStr, 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().

◆ pltcl_WaitForEvent()

static int pltcl_WaitForEvent ( CONST86 Tcl_Time *  timePtr)
static

Definition at line 385 of file pltcl.c.

386 {
387  return 0;
388 }

Referenced by _PG_init().

◆ pltclu_call_handler()

Datum pltclu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 708 of file pltcl.c.

709 {
710  return pltcl_handler(fcinfo, false);
711 }

References pltcl_handler().

◆ start_proc_error_callback()

static void start_proc_error_callback ( void *  arg)
static

Definition at line 676 of file pltcl.c.

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

References arg, and errcontext.

Referenced by call_pltcl_start_proc().

◆ throw_tcl_error()

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

Definition at line 1360 of file pltcl.c.

1361 {
1362  /*
1363  * Caution is needed here because Tcl_GetVar could overwrite the
1364  * interpreter result (even though it's not really supposed to), and we
1365  * can't control the order of evaluation of ereport arguments. Hence, make
1366  * real sure we have our own copy of the result string before invoking
1367  * Tcl_GetVar.
1368  */
1369  char *emsg;
1370  char *econtext;
1371 
1372  emsg = pstrdup(utf_u2e(Tcl_GetStringResult(interp)));
1373  econtext = utf_u2e(Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY));
1374  ereport(ERROR,
1375  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1376  errmsg("%s", emsg),
1377  errcontext("%s\nin PL/Tcl function \"%s\"",
1378  econtext, proname)));
1379 }
NameData proname
Definition: pg_proc.h:35

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

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

◆ utf_e2u()

static char* utf_e2u ( const char *  src)
inlinestatic

Definition at line 81 of file pltcl.c.

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

References pg_server_to_any(), and PG_UTF8.

Referenced by pltcl_event_trigger_handler(), and pltcl_trigger_handler().

◆ utf_u2e()

static char* utf_u2e ( const char *  src)
inlinestatic

Definition at line 75 of file pltcl.c.

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

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

Variable Documentation

◆ exception_name_map

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

Definition at line 256 of file pltcl.c.

Referenced by pltcl_get_condition_name().

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 43 of file pltcl.c.

◆ pltcl_current_call_state

pltcl_call_state* pltcl_current_call_state = NULL
static

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

Referenced by _PG_init(), and pltcl_fetch_interp().

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

Referenced by _PG_init(), and compile_pltcl_function().

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