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