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