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