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