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