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