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