PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pltcl.c File Reference
#include "postgres.h"
#include <tcl.h>
#include <unistd.h>
#include <fcntl.h>
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "parser/parse_func.h"
#include "parser/parse_type.h"
#include "pgstat.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/regproc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "pltclerrcodes.h"
Include dependency graph for pltcl.c:

Go to the source code of this file.

Data Structures

struct  pltcl_interp_desc
 
struct  pltcl_proc_desc
 
struct  pltcl_query_desc
 
struct  pltcl_proc_key
 
struct  pltcl_proc_ptr
 
struct  pltcl_call_state
 
struct  TclExceptionNameMap
 

Macros

#define HAVE_TCL_VERSION(maj, min)
 
#define CONST86
 
#define TEXTDOMAIN   PG_TEXTDOMAIN("pltcl")
 
#define UTF_BEGIN
 
#define UTF_END
 
#define UTF_U2E(x)    (_pltcl_utf_dst = utf_u2e(_pltcl_utf_src = (x)))
 
#define UTF_E2U(x)    (_pltcl_utf_dst = utf_e2u(_pltcl_utf_src = (x)))
 

Typedefs

typedef int Tcl_Size
 
typedef struct pltcl_interp_desc pltcl_interp_desc
 
typedef struct pltcl_proc_desc pltcl_proc_desc
 
typedef struct pltcl_query_desc pltcl_query_desc
 
typedef struct pltcl_proc_key pltcl_proc_key
 
typedef struct pltcl_proc_ptr pltcl_proc_ptr
 
typedef struct pltcl_call_state pltcl_call_state
 

Functions

 PG_MODULE_MAGIC_EXT (.name="pltcl",.version=PG_VERSION)
 
static charutf_u2e (const char *src)
 
static charutf_e2u (const char *src)
 
static void pltcl_init_interp (pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
 
static pltcl_interp_descpltcl_fetch_interp (Oid prolang, bool pltrusted)
 
static void call_pltcl_start_proc (Oid prolang, bool pltrusted)
 
static void start_proc_error_callback (void *arg)
 
static Datum pltcl_handler (PG_FUNCTION_ARGS, bool pltrusted)
 
static Datum pltcl_func_handler (PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
 
static HeapTuple pltcl_trigger_handler (PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
 
static void pltcl_event_trigger_handler (PG_FUNCTION_ARGS, pltcl_call_state *call_state, bool pltrusted)
 
static void throw_tcl_error (Tcl_Interp *interp, const char *proname)
 
static pltcl_proc_desccompile_pltcl_function (Oid fn_oid, Oid tgreloid, bool is_event_trigger, bool pltrusted)
 
static int pltcl_elog (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static void pltcl_construct_errorCode (Tcl_Interp *interp, ErrorData *edata)
 
static const charpltcl_get_condition_name (int sqlstate)
 
static int pltcl_quote (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_argisnull (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_returnnull (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_returnnext (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_SPI_execute (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_process_SPI_result (Tcl_Interp *interp, const char *arrayname, Tcl_Obj *loop_body, int spi_rc, SPITupleTable *tuptable, uint64 ntuples)
 
static int pltcl_SPI_prepare (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_SPI_execute_plan (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_subtransaction (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_commit (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static int pltcl_rollback (ClientData cdata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 
static void pltcl_subtrans_begin (MemoryContext oldcontext, ResourceOwner oldowner)
 
static void pltcl_subtrans_commit (MemoryContext oldcontext, ResourceOwner oldowner)
 
static void pltcl_subtrans_abort (Tcl_Interp *interp, MemoryContext oldcontext, ResourceOwner oldowner)
 
static void pltcl_set_tuple_values (Tcl_Interp *interp, const char *arrayname, uint64 tupno, HeapTuple tuple, TupleDesc tupdesc)
 
static Tcl_Objpltcl_build_tuple_argument (HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
 
static HeapTuple pltcl_build_tuple_result (Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc, pltcl_call_state *call_state)
 
static void pltcl_init_tuple_store (pltcl_call_state *call_state)
 
static ClientData pltcl_InitNotifier (void)
 
static void pltcl_FinalizeNotifier (ClientData clientData)
 
static void pltcl_SetTimer (CONST86 Tcl_Time *timePtr)
 
static void pltcl_AlertNotifier (ClientData clientData)
 
static void pltcl_CreateFileHandler (int fd, int mask, Tcl_FileProc *proc, ClientData clientData)
 
static void pltcl_DeleteFileHandler (int fd)
 
static void pltcl_ServiceModeHook (int mode)
 
static int pltcl_WaitForEvent (CONST86 Tcl_Time *timePtr)
 
void _PG_init (void)
 
 PG_FUNCTION_INFO_V1 (pltcl_call_handler)
 
Datum pltcl_call_handler (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (pltclu_call_handler)
 
Datum pltclu_call_handler (PG_FUNCTION_ARGS)
 

Variables

static charpltcl_start_proc = NULL
 
static charpltclu_start_proc = NULL
 
static bool pltcl_pm_init_done = false
 
static Tcl_Interppltcl_hold_interp = NULL
 
static HTABpltcl_interp_htab = NULL
 
static HTABpltcl_proc_htab = NULL
 
static pltcl_call_statepltcl_current_call_state = NULL
 
static const TclExceptionNameMap exception_name_map []
 

Macro Definition Documentation

◆ CONST86

#define CONST86

Definition at line 58 of file pltcl.c.

◆ HAVE_TCL_VERSION

#define HAVE_TCL_VERSION (   maj,
  min 
)
Value:
static int fb(int x)

Definition at line 47 of file pltcl.c.

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

◆ TEXTDOMAIN

#define TEXTDOMAIN   PG_TEXTDOMAIN("pltcl")

Definition at line 67 of file pltcl.c.

◆ UTF_BEGIN

#define UTF_BEGIN
Value:
do { \
const char *_pltcl_utf_src = NULL; \

Definition at line 92 of file pltcl.c.

93 { \
94 const char *_pltcl_utf_src = NULL; \
95 char *_pltcl_utf_dst = NULL

◆ UTF_E2U

#define UTF_E2U (   x)     (_pltcl_utf_dst = utf_e2u(_pltcl_utf_src = (x)))

Definition at line 105 of file pltcl.c.

◆ UTF_END

#define UTF_END
Value:
if (_pltcl_utf_src != (const char *) _pltcl_utf_dst) \
} while (0)

Definition at line 97 of file pltcl.c.

◆ UTF_U2E

#define UTF_U2E (   x)     (_pltcl_utf_dst = utf_u2e(_pltcl_utf_src = (x)))

Definition at line 102 of file pltcl.c.

Typedef Documentation

◆ pltcl_call_state

◆ pltcl_interp_desc

◆ pltcl_proc_desc

◆ pltcl_proc_key

◆ pltcl_proc_ptr

◆ pltcl_query_desc

◆ Tcl_Size

Definition at line 62 of file pltcl.c.

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 408 of file pltcl.c.

409{
412
413 /* Be sure we do initialization only once (should be redundant now) */
415 return;
416
418
419#ifdef WIN32
420 /* Required on win32 to prevent error loading init.tcl */
422#endif
423
424 /*
425 * Override the functions in the Notifier subsystem. See comments above.
426 */
427 notifier.setTimerProc = pltcl_SetTimer;
428 notifier.waitForEventProc = pltcl_WaitForEvent;
429 notifier.createFileHandlerProc = pltcl_CreateFileHandler;
430 notifier.deleteFileHandlerProc = pltcl_DeleteFileHandler;
431 notifier.initNotifierProc = pltcl_InitNotifier;
432 notifier.finalizeNotifierProc = pltcl_FinalizeNotifier;
433 notifier.alertNotifierProc = pltcl_AlertNotifier;
434 notifier.serviceModeHookProc = pltcl_ServiceModeHook;
436
437 /************************************************************
438 * Create the dummy hold interpreter to prevent close of
439 * stdout and stderr on DeleteInterp
440 ************************************************************/
442 elog(ERROR, "could not create dummy Tcl interpreter");
444 elog(ERROR, "could not initialize dummy Tcl interpreter");
445
446 /************************************************************
447 * Create the hash table for working interpreters
448 ************************************************************/
449 hash_ctl.keysize = sizeof(Oid);
450 hash_ctl.entrysize = sizeof(pltcl_interp_desc);
451 pltcl_interp_htab = hash_create("PL/Tcl interpreters",
452 8,
453 &hash_ctl,
455
456 /************************************************************
457 * Create the hash table for function lookup
458 ************************************************************/
459 hash_ctl.keysize = sizeof(pltcl_proc_key);
460 hash_ctl.entrysize = sizeof(pltcl_proc_ptr);
461 pltcl_proc_htab = hash_create("PL/Tcl functions",
462 100,
463 &hash_ctl,
465
466 /************************************************************
467 * Define PL/Tcl's custom GUCs
468 ************************************************************/
469 DefineCustomStringVariable("pltcl.start_proc",
470 gettext_noop("PL/Tcl function to call once when pltcl is first used."),
471 NULL,
473 NULL,
474 PGC_SUSET, 0,
475 NULL, NULL, NULL);
476 DefineCustomStringVariable("pltclu.start_proc",
477 gettext_noop("PL/TclU function to call once when pltclu is first used."),
478 NULL,
480 NULL,
481 PGC_SUSET, 0,
482 NULL, NULL, NULL);
483
484 MarkGUCPrefixReserved("pltcl");
485 MarkGUCPrefixReserved("pltclu");
486
487 pltcl_pm_init_done = true;
488}

References DefineCustomStringVariable(), elog, ERROR, fb(), gettext_noop, HASH_BLOBS, hash_create(), HASH_ELEM, MarkGUCPrefixReserved(), pg_bindtextdomain(), PGC_SUSET, pltcl_AlertNotifier(), pltcl_CreateFileHandler(), pltcl_DeleteFileHandler(), pltcl_FinalizeNotifier(), pltcl_hold_interp, pltcl_InitNotifier(), pltcl_interp_htab, pltcl_pm_init_done, pltcl_proc_htab, pltcl_ServiceModeHook(), pltcl_SetTimer(), pltcl_start_proc, pltcl_WaitForEvent(), pltclu_start_proc, and TEXTDOMAIN.

◆ call_pltcl_start_proc()

static void call_pltcl_start_proc ( Oid  prolang,
bool  pltrusted 
)
static

Definition at line 597 of file pltcl.c.

598{
599 LOCAL_FCINFO(fcinfo, 0);
600 char *start_proc;
601 const char *gucname;
602 ErrorContextCallback errcallback;
603 List *namelist;
604 Oid procOid;
608 FmgrInfo finfo;
610
611 /* select appropriate GUC */
613 gucname = pltrusted ? "pltcl.start_proc" : "pltclu.start_proc";
614
615 /* Nothing to do if it's empty or unset */
616 if (start_proc == NULL || start_proc[0] == '\0')
617 return;
618
619 /* Set up errcontext callback to make errors more helpful */
621 errcallback.arg = unconstify(char *, gucname);
622 errcallback.previous = error_context_stack;
623 error_context_stack = &errcallback;
624
625 /* Parse possibly-qualified identifier and look up the function */
627 procOid = LookupFuncName(namelist, 0, NULL, false);
628
629 /* Current user must have permission to call function */
631 if (aclresult != ACLCHECK_OK)
633
634 /* Get the function's pg_proc entry */
637 elog(ERROR, "cache lookup failed for function %u", procOid);
639
640 /* It must be same language as the function we're currently calling */
641 if (procStruct->prolang != prolang)
644 errmsg("function \"%s\" is in the wrong language",
645 start_proc)));
646
647 /*
648 * It must not be SECURITY DEFINER, either. This together with the
649 * language match check ensures that the function will execute in the same
650 * Tcl interpreter we just finished initializing.
651 */
652 if (procStruct->prosecdef)
655 errmsg("function \"%s\" must not be SECURITY DEFINER",
656 start_proc)));
657
658 /* A-OK */
660
661 /*
662 * Call the function using the normal SQL function call mechanism. We
663 * could perhaps cheat and jump directly to pltcl_handler(), but it seems
664 * better to do it this way so that the call is exposed to, eg, call
665 * statistics collection.
666 */
668 fmgr_info(procOid, &finfo);
669 InitFunctionCallInfoData(*fcinfo, &finfo,
670 0,
673 (void) FunctionCallInvoke(fcinfo);
675
676 /* Pop the error context stack */
677 error_context_stack = errcallback.previous;
678}

References ACL_EXECUTE, aclcheck_error(), ACLCHECK_OK, ErrorContextCallback::arg, ErrorContextCallback::callback, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, fb(), fmgr_info(), FunctionCallInvoke, GETSTRUCT(), GetUserId(), HeapTupleIsValid, InitFunctionCallInfoData, InvalidOid, InvokeFunctionExecuteHook, LOCAL_FCINFO, LookupFuncName(), object_aclcheck(), OBJECT_FUNCTION, ObjectIdGetDatum(), pgstat_end_function_usage(), pgstat_init_function_usage(), pltcl_start_proc, pltclu_start_proc, ErrorContextCallback::previous, ReleaseSysCache(), SearchSysCache1(), start_proc_error_callback(), stringToQualifiedNameList(), and unconstify.

Referenced by pltcl_init_interp().

◆ compile_pltcl_function()

static pltcl_proc_desc * compile_pltcl_function ( Oid  fn_oid,
Oid  tgreloid,
bool  is_event_trigger,
bool  pltrusted 
)
static

Definition at line 1417 of file pltcl.c.

1419{
1422 pltcl_proc_key proc_key;
1423 pltcl_proc_ptr *proc_ptr;
1424 bool found;
1425 pltcl_proc_desc *prodesc;
1427 volatile MemoryContext proc_cxt = NULL;
1431
1432 /* We'll need the pg_proc tuple in any case... */
1435 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1437
1438 /*
1439 * Look up function in pltcl_proc_htab; if it's not there, create an entry
1440 * and set the entry's proc_ptr to NULL.
1441 */
1442 proc_key.proc_id = fn_oid;
1443 proc_key.is_trigger = OidIsValid(tgreloid);
1444 proc_key.user_id = pltrusted ? GetUserId() : InvalidOid;
1445
1446 proc_ptr = hash_search(pltcl_proc_htab, &proc_key,
1447 HASH_ENTER,
1448 &found);
1449 if (!found)
1450 proc_ptr->proc_ptr = NULL;
1451
1452 prodesc = proc_ptr->proc_ptr;
1453
1454 /************************************************************
1455 * If it's present, must check whether it's still up to date.
1456 * This is needed because CREATE OR REPLACE FUNCTION can modify the
1457 * function's pg_proc entry without changing its OID.
1458 ************************************************************/
1459 if (prodesc != NULL &&
1460 prodesc->internal_proname != NULL &&
1461 prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
1462 ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self))
1463 {
1464 /* It's still up-to-date, so we can use it */
1466 return prodesc;
1467 }
1468
1469 /************************************************************
1470 * If we haven't found it in the hashtable, we analyze
1471 * the functions arguments and returntype and store
1472 * the in-/out-functions in the prodesc block and create
1473 * a new hashtable entry for it.
1474 *
1475 * Then we load the procedure into the Tcl interpreter.
1476 ************************************************************/
1480 PG_TRY();
1481 {
1482 bool is_trigger = OidIsValid(tgreloid);
1484 const char *user_proname;
1485 const char *internal_proname;
1486 bool need_underscore;
1491 char *proc_source;
1492 char buf[48];
1493 pltcl_interp_desc *interp_desc;
1494 Tcl_Interp *interp;
1495 int i;
1496 int tcl_rc;
1497 MemoryContext oldcontext;
1498
1499 /************************************************************
1500 * Identify the interpreter to use for the function
1501 ************************************************************/
1502 interp_desc = pltcl_fetch_interp(procStruct->prolang, pltrusted);
1503 interp = interp_desc->interp;
1504
1505 /************************************************************
1506 * If redefining the function, try to remove the old internal
1507 * procedure from Tcl's namespace. The point of this is partly to
1508 * allow re-use of the same internal proc name, and partly to avoid
1509 * leaking the Tcl procedure object if we end up not choosing the same
1510 * name. We assume that Tcl is smart enough to not physically delete
1511 * the procedure object if it's currently being executed.
1512 ************************************************************/
1513 if (prodesc != NULL &&
1514 prodesc->internal_proname != NULL)
1515 {
1516 /* We simply ignore any error */
1517 (void) Tcl_DeleteCommand(interp, prodesc->internal_proname);
1518 /* Don't do this more than once */
1519 prodesc->internal_proname = NULL;
1520 }
1521
1522 /************************************************************
1523 * Build the proc name we'll use in error messages.
1524 ************************************************************/
1525 user_proname = format_procedure(fn_oid);
1526
1527 /************************************************************
1528 * Build the internal proc name from the user_proname and/or OID.
1529 * The internal name must be all-ASCII since we don't want to deal
1530 * with encoding conversions. We don't want to worry about Tcl
1531 * quoting rules either, so use only the characters of the function
1532 * name that are ASCII alphanumerics, plus underscores to separate
1533 * function name and arguments. If what we end up with isn't
1534 * unique (that is, it matches some existing Tcl command name),
1535 * append the function OID (perhaps repeatedly) so that it is unique.
1536 ************************************************************/
1537
1538 /* For historical reasons, use a function-type-specific prefix */
1539 if (is_event_trigger)
1541 "__PLTcl_evttrigger_", -1);
1542 else if (is_trigger)
1544 "__PLTcl_trigger_", -1);
1545 else
1547 "__PLTcl_proc_", -1);
1548 /* Now add what we can from the user_proname */
1549 need_underscore = false;
1550 for (const char *ptr = user_proname; *ptr; ptr++)
1551 {
1552 if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1553 "abcdefghijklmnopqrstuvwxyz"
1554 "0123456789_", *ptr) != NULL)
1555 {
1556 /* Done this way to avoid adding a trailing underscore */
1557 if (need_underscore)
1558 {
1560 need_underscore = false;
1561 }
1563 }
1564 else if (strchr("(, ", *ptr) != NULL)
1565 need_underscore = true;
1566 }
1567 /* If this name already exists, append fn_oid; repeat as needed */
1568 while (Tcl_GetCommandInfo(interp,
1570 &cmdinfo))
1571 {
1572 snprintf(buf, sizeof(buf), "_%u", fn_oid);
1574 }
1575 internal_proname = Tcl_DStringValue(&proc_internal_name);
1576
1577 /************************************************************
1578 * Allocate a context that will hold all PG data for the procedure.
1579 ************************************************************/
1581 "PL/Tcl function",
1583
1584 /************************************************************
1585 * Allocate and fill a new procedure description block.
1586 * struct prodesc and subsidiary data must all live in proc_cxt.
1587 ************************************************************/
1588 oldcontext = MemoryContextSwitchTo(proc_cxt);
1590 prodesc->user_proname = pstrdup(user_proname);
1592 prodesc->internal_proname = pstrdup(internal_proname);
1593 prodesc->fn_cxt = proc_cxt;
1594 prodesc->fn_refcount = 0;
1595 prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
1596 prodesc->fn_tid = procTup->t_self;
1597 prodesc->nargs = procStruct->pronargs;
1598 prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
1599 prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
1600 MemoryContextSwitchTo(oldcontext);
1601
1602 /* Remember if function is STABLE/IMMUTABLE */
1603 prodesc->fn_readonly =
1604 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1605 /* And whether it is trusted */
1606 prodesc->lanpltrusted = pltrusted;
1607 /* Save the associated interpreter, too */
1608 prodesc->interp_desc = interp_desc;
1609
1610 /************************************************************
1611 * Get the required information for input conversion of the
1612 * return value.
1613 ************************************************************/
1614 if (!is_trigger && !is_event_trigger)
1615 {
1616 Oid rettype = procStruct->prorettype;
1617
1620 elog(ERROR, "cache lookup failed for type %u", rettype);
1622
1623 /* Disallow pseudotype result, except VOID and RECORD */
1624 if (typeStruct->typtype == TYPTYPE_PSEUDO)
1625 {
1626 if (rettype == VOIDOID ||
1627 rettype == RECORDOID)
1628 /* okay */ ;
1629 else if (rettype == TRIGGEROID ||
1630 rettype == EVENT_TRIGGEROID)
1631 ereport(ERROR,
1633 errmsg("trigger functions can only be called as triggers")));
1634 else
1635 ereport(ERROR,
1637 errmsg("PL/Tcl functions cannot return type %s",
1638 format_type_be(rettype))));
1639 }
1640
1641 prodesc->result_typid = rettype;
1642 fmgr_info_cxt(typeStruct->typinput,
1643 &(prodesc->result_in_func),
1644 proc_cxt);
1646
1647 prodesc->fn_retisset = procStruct->proretset;
1648 prodesc->fn_retistuple = type_is_rowtype(rettype);
1649 prodesc->fn_retisdomain = (typeStruct->typtype == TYPTYPE_DOMAIN);
1650 prodesc->domain_info = NULL;
1651
1653 }
1654
1655 /************************************************************
1656 * Get the required information for output conversion
1657 * of all procedure arguments, and set up argument naming info.
1658 ************************************************************/
1659 if (!is_trigger && !is_event_trigger)
1660 {
1661 proc_internal_args[0] = '\0';
1662 for (i = 0; i < prodesc->nargs; i++)
1663 {
1664 Oid argtype = procStruct->proargtypes.values[i];
1665
1668 elog(ERROR, "cache lookup failed for type %u", argtype);
1670
1671 /* Disallow pseudotype argument, except RECORD */
1672 if (typeStruct->typtype == TYPTYPE_PSEUDO &&
1673 argtype != RECORDOID)
1674 ereport(ERROR,
1676 errmsg("PL/Tcl functions cannot accept type %s",
1677 format_type_be(argtype))));
1678
1679 if (type_is_rowtype(argtype))
1680 {
1681 prodesc->arg_is_rowtype[i] = true;
1682 snprintf(buf, sizeof(buf), "__PLTcl_Tup_%d", i + 1);
1683 }
1684 else
1685 {
1686 prodesc->arg_is_rowtype[i] = false;
1687 fmgr_info_cxt(typeStruct->typoutput,
1688 &(prodesc->arg_out_func[i]),
1689 proc_cxt);
1690 snprintf(buf, sizeof(buf), "%d", i + 1);
1691 }
1692
1693 if (i > 0)
1696
1698 }
1699 }
1700 else if (is_trigger)
1701 {
1702 /* trigger procedure has fixed args */
1704 "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");
1705 }
1706 else if (is_event_trigger)
1707 {
1708 /* event trigger procedure has fixed args */
1709 strcpy(proc_internal_args, "TG_event TG_tag");
1710 }
1711
1712 /************************************************************
1713 * Create the tcl command to define the internal
1714 * procedure
1715 *
1716 * Leave this code as DString - performance is not critical here,
1717 * and we don't want to duplicate the knowledge of the Tcl quoting
1718 * rules that's embedded in Tcl_DStringAppendElement.
1719 ************************************************************/
1721 Tcl_DStringAppendElement(&proc_internal_def, internal_proname);
1723
1724 /************************************************************
1725 * prefix procedure body with
1726 * upvar #0 <internal_proname> GD
1727 * and with appropriate setting of arguments
1728 ************************************************************/
1729 Tcl_DStringAppend(&proc_internal_body, "upvar #0 ", -1);
1730 Tcl_DStringAppend(&proc_internal_body, internal_proname, -1);
1732 if (is_trigger)
1733 {
1735 "array set NEW $__PLTcl_Tup_NEW\n", -1);
1737 "array set OLD $__PLTcl_Tup_OLD\n", -1);
1739 "set i 0\n"
1740 "set v 0\n"
1741 "foreach v $args {\n"
1742 " incr i\n"
1743 " set $i $v\n"
1744 "}\n"
1745 "unset i v\n\n", -1);
1746 }
1747 else if (is_event_trigger)
1748 {
1749 /* no argument support for event triggers */
1750 }
1751 else
1752 {
1753 for (i = 0; i < prodesc->nargs; i++)
1754 {
1755 if (prodesc->arg_is_rowtype[i])
1756 {
1757 snprintf(buf, sizeof(buf),
1758 "array set %d $__PLTcl_Tup_%d\n",
1759 i + 1, i + 1);
1761 }
1762 }
1763 }
1764
1765 /************************************************************
1766 * Add user's function definition to proc body
1767 ************************************************************/
1770 proc_source = TextDatumGetCString(prosrcdatum);
1771 UTF_BEGIN;
1772 Tcl_DStringAppend(&proc_internal_body, UTF_E2U(proc_source), -1);
1773 UTF_END;
1774 pfree(proc_source);
1777
1778 /************************************************************
1779 * Create the procedure in the interpreter
1780 ************************************************************/
1781 tcl_rc = Tcl_EvalEx(interp,
1785 if (tcl_rc != TCL_OK)
1786 ereport(ERROR,
1788 errmsg("could not create internal procedure \"%s\": %s",
1789 internal_proname,
1790 utf_u2e(Tcl_GetStringResult(interp)))));
1791 }
1792 PG_CATCH();
1793 {
1794 /*
1795 * If we failed anywhere above, clean up whatever got allocated. It
1796 * should all be in the proc_cxt, except for the DStrings.
1797 */
1798 if (proc_cxt)
1803 PG_RE_THROW();
1804 }
1805 PG_END_TRY();
1806
1807 /*
1808 * Install the new proc description block in the hashtable, incrementing
1809 * its refcount (the hashtable link counts as a reference). Then, if
1810 * there was a previous definition of the function, decrement that one's
1811 * refcount, and delete it if no longer referenced. The order of
1812 * operations here is important: if something goes wrong during the
1813 * MemoryContextDelete, leaking some memory for the old definition is OK,
1814 * but we don't want to corrupt the live hashtable entry. (Likewise,
1815 * freeing the DStrings is pretty low priority if that happens.)
1816 */
1817 old_prodesc = proc_ptr->proc_ptr;
1818
1819 proc_ptr->proc_ptr = prodesc;
1820 prodesc->fn_refcount++;
1821
1822 if (old_prodesc != NULL)
1823 {
1824 Assert(old_prodesc->fn_refcount > 0);
1825 if (--old_prodesc->fn_refcount == 0)
1827 }
1828
1832
1834
1835 return prodesc;
1836}

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, pltcl_proc_desc::arg_is_rowtype, pltcl_proc_desc::arg_out_func, Assert, buf, pltcl_proc_desc::domain_info, elog, ereport, errcode(), errmsg(), ERROR, fb(), fmgr_info_cxt(), pltcl_proc_desc::fn_cxt, pltcl_proc_desc::fn_readonly, pltcl_proc_desc::fn_refcount, pltcl_proc_desc::fn_retisdomain, pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, pltcl_proc_desc::fn_tid, pltcl_proc_desc::fn_xmin, format_procedure(), format_type_be(), FUNC_MAX_ARGS, GETSTRUCT(), getTypeIOParam(), GetUserId(), HASH_ENTER, hash_search(), HeapTupleHeaderGetRawXmin(), HeapTupleIsValid, i, pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, InvalidOid, pltcl_proc_key::is_trigger, ItemPointerEquals(), pltcl_proc_desc::lanpltrusted, MemoryContextDelete(), MemoryContextSetIdentifier(), MemoryContextSwitchTo(), pltcl_proc_desc::nargs, ObjectIdGetDatum(), OidIsValid, palloc0(), palloc0_object, pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pltcl_fetch_interp(), pltcl_proc_htab, pltcl_proc_key::proc_id, pltcl_proc_ptr::proc_ptr, pstrdup(), ReleaseSysCache(), pltcl_proc_desc::result_in_func, pltcl_proc_desc::result_typid, pltcl_proc_desc::result_typioparam, SearchSysCache1(), snprintf, SysCacheGetAttrNotNull(), TextDatumGetCString, TopMemoryContext, type_is_rowtype(), pltcl_proc_key::user_id, pltcl_proc_desc::user_proname, UTF_BEGIN, UTF_E2U, UTF_END, and utf_u2e().

Referenced by pltcl_event_trigger_handler(), pltcl_func_handler(), and pltcl_trigger_handler().

◆ PG_FUNCTION_INFO_V1() [1/2]

PG_FUNCTION_INFO_V1 ( pltcl_call_handler  )

◆ PG_FUNCTION_INFO_V1() [2/2]

PG_FUNCTION_INFO_V1 ( pltclu_call_handler  )

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "pltcl",
version = PG_VERSION 
)

◆ pltcl_AlertNotifier()

static void pltcl_AlertNotifier ( ClientData  clientData)
static

Definition at line 372 of file pltcl.c.

373{
374}

Referenced by _PG_init().

◆ pltcl_argisnull()

static int pltcl_argisnull ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2147 of file pltcl.c.

2149{
2150 int argno;
2152
2153 /************************************************************
2154 * Check call syntax
2155 ************************************************************/
2156 if (objc != 2)
2157 {
2158 Tcl_WrongNumArgs(interp, 1, objv, "argno");
2159 return TCL_ERROR;
2160 }
2161
2162 /************************************************************
2163 * Check that we're called as a normal function
2164 ************************************************************/
2165 if (fcinfo == NULL)
2166 {
2167 Tcl_SetObjResult(interp,
2168 Tcl_NewStringObj("argisnull cannot be used in triggers", -1));
2169 return TCL_ERROR;
2170 }
2171
2172 /************************************************************
2173 * Get the argument number
2174 ************************************************************/
2175 if (Tcl_GetIntFromObj(interp, objv[1], &argno) != TCL_OK)
2176 return TCL_ERROR;
2177
2178 /************************************************************
2179 * Check that the argno is valid
2180 ************************************************************/
2181 argno--;
2182 if (argno < 0 || argno >= fcinfo->nargs)
2183 {
2184 Tcl_SetObjResult(interp,
2185 Tcl_NewStringObj("argno out of range", -1));
2186 return TCL_ERROR;
2187 }
2188
2189 /************************************************************
2190 * Get the requested NULL state
2191 ************************************************************/
2193 return TCL_OK;
2194}

References fb(), pltcl_call_state::fcinfo, FunctionCallInfoBaseData::nargs, PG_ARGISNULL, and pltcl_current_call_state.

Referenced by pltcl_init_interp().

◆ pltcl_build_tuple_argument()

static Tcl_Obj * pltcl_build_tuple_argument ( HeapTuple  tuple,
TupleDesc  tupdesc,
bool  include_generated 
)
static

Definition at line 3188 of file pltcl.c.

3189{
3191 int i;
3192 char *outputstr;
3193 Datum attr;
3194 bool isnull;
3195 char *attname;
3196 Oid typoutput;
3197 bool typisvarlena;
3198
3199 for (i = 0; i < tupdesc->natts; i++)
3200 {
3202
3203 /* ignore dropped attributes */
3204 if (att->attisdropped)
3205 continue;
3206
3207 if (att->attgenerated)
3208 {
3209 /* don't include unless requested */
3210 if (!include_generated)
3211 continue;
3212 /* never include virtual columns */
3213 if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
3214 continue;
3215 }
3216
3217 /************************************************************
3218 * Get the attribute name
3219 ************************************************************/
3220 attname = NameStr(att->attname);
3221
3222 /************************************************************
3223 * Get the attributes value
3224 ************************************************************/
3225 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3226
3227 /************************************************************
3228 * If there is a value, append the attribute name and the
3229 * value to the list
3230 *
3231 * Hmmm - Null attributes will cause functions to
3232 * crash if they don't expect them - need something
3233 * smarter here.
3234 ************************************************************/
3235 if (!isnull)
3236 {
3237 getTypeOutputInfo(att->atttypid,
3238 &typoutput, &typisvarlena);
3239 outputstr = OidOutputFunctionCall(typoutput, attr);
3240 UTF_BEGIN;
3243 UTF_END;
3244 UTF_BEGIN;
3247 UTF_END;
3249 }
3250 }
3251
3252 return retobj;
3253}

References attname, fb(), getTypeOutputInfo(), heap_getattr(), i, NameStr, TupleDescData::natts, OidOutputFunctionCall(), pfree(), TupleDescAttr(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_func_handler(), and pltcl_trigger_handler().

◆ pltcl_build_tuple_result()

static HeapTuple pltcl_build_tuple_result ( Tcl_Interp interp,
Tcl_Obj **  kvObjv,
int  kvObjc,
pltcl_call_state call_state 
)
static

Definition at line 3267 of file pltcl.c.

3269{
3270 HeapTuple tuple;
3271 TupleDesc tupdesc;
3272 AttInMetadata *attinmeta;
3273 char **values;
3274 int i;
3275
3276 if (call_state->ret_tupdesc)
3277 {
3278 tupdesc = call_state->ret_tupdesc;
3279 attinmeta = call_state->attinmeta;
3280 }
3281 else if (call_state->trigdata)
3282 {
3283 tupdesc = RelationGetDescr(call_state->trigdata->tg_relation);
3284 attinmeta = TupleDescGetAttInMetadata(tupdesc);
3285 }
3286 else
3287 {
3288 elog(ERROR, "PL/Tcl function does not return a tuple");
3289 tupdesc = NULL; /* keep compiler quiet */
3290 attinmeta = NULL;
3291 }
3292
3293 values = (char **) palloc0(tupdesc->natts * sizeof(char *));
3294
3295 if (kvObjc % 2 != 0)
3296 ereport(ERROR,
3298 errmsg("column name/value list must have even number of elements")));
3299
3300 for (i = 0; i < kvObjc; i += 2)
3301 {
3302 char *fieldName = utf_u2e(Tcl_GetString(kvObjv[i]));
3303 int attn = SPI_fnumber(tupdesc, fieldName);
3304
3305 /*
3306 * We silently ignore ".tupno", if it's present but doesn't match any
3307 * actual output column. This allows direct use of a row returned by
3308 * pltcl_set_tuple_values().
3309 */
3311 {
3312 if (strcmp(fieldName, ".tupno") == 0)
3313 continue;
3314 ereport(ERROR,
3316 errmsg("column name/value list contains nonexistent column name \"%s\"",
3317 fieldName)));
3318 }
3319
3320 if (attn <= 0)
3321 ereport(ERROR,
3323 errmsg("cannot set system attribute \"%s\"",
3324 fieldName)));
3325
3326 if (TupleDescAttr(tupdesc, attn - 1)->attgenerated)
3327 ereport(ERROR,
3329 errmsg("cannot set generated column \"%s\"",
3330 fieldName)));
3331
3332 values[attn - 1] = utf_u2e(Tcl_GetString(kvObjv[i + 1]));
3333 }
3334
3335 tuple = BuildTupleFromCStrings(attinmeta, values);
3336
3337 /* if result type is domain-over-composite, check domain constraints */
3338 if (call_state->prodesc->fn_retisdomain)
3339 domain_check(HeapTupleGetDatum(tuple), false,
3340 call_state->prodesc->result_typid,
3341 &call_state->prodesc->domain_info,
3342 call_state->prodesc->fn_cxt);
3343
3344 return tuple;
3345}

References BuildTupleFromCStrings(), domain_check(), elog, ereport, errcode(), errmsg(), ERROR, fb(), HeapTupleGetDatum(), i, TupleDescData::natts, palloc0(), RelationGetDescr, SPI_ERROR_NOATTRIBUTE, SPI_fnumber(), TupleDescAttr(), TupleDescGetAttInMetadata(), utf_u2e(), and values.

Referenced by pltcl_func_handler(), pltcl_returnnext(), and pltcl_trigger_handler().

◆ pltcl_call_handler()

Datum pltcl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 704 of file pltcl.c.

705{
706 return pltcl_handler(fcinfo, true);
707}

References pltcl_handler().

◆ pltcl_commit()

static int pltcl_commit ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 3023 of file pltcl.c.

3025{
3027
3028 PG_TRY();
3029 {
3030 SPI_commit();
3031 }
3032 PG_CATCH();
3033 {
3035
3036 /* Save error info */
3037 MemoryContextSwitchTo(oldcontext);
3038 edata = CopyErrorData();
3040
3041 /* Pass the error data to Tcl */
3043 UTF_BEGIN;
3044 Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
3045 UTF_END;
3047
3048 return TCL_ERROR;
3049 }
3050 PG_END_TRY();
3051
3052 return TCL_OK;
3053}

References CopyErrorData(), CurrentMemoryContext, fb(), FlushErrorState(), FreeErrorData(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_construct_errorCode(), SPI_commit(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_init_interp().

◆ pltcl_construct_errorCode()

static void pltcl_construct_errorCode ( Tcl_Interp interp,
ErrorData edata 
)
static

Definition at line 1930 of file pltcl.c.

1931{
1932 Tcl_Obj *obj = Tcl_NewObj();
1933
1934 Tcl_ListObjAppendElement(interp, obj,
1935 Tcl_NewStringObj("POSTGRES", -1));
1936 Tcl_ListObjAppendElement(interp, obj,
1938 Tcl_ListObjAppendElement(interp, obj,
1939 Tcl_NewStringObj("SQLSTATE", -1));
1940 Tcl_ListObjAppendElement(interp, obj,
1941 Tcl_NewStringObj(unpack_sql_state(edata->sqlerrcode), -1));
1942 Tcl_ListObjAppendElement(interp, obj,
1943 Tcl_NewStringObj("condition", -1));
1944 Tcl_ListObjAppendElement(interp, obj,
1946 Tcl_ListObjAppendElement(interp, obj,
1947 Tcl_NewStringObj("message", -1));
1948 UTF_BEGIN;
1949 Tcl_ListObjAppendElement(interp, obj,
1950 Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1951 UTF_END;
1952 if (edata->detail)
1953 {
1954 Tcl_ListObjAppendElement(interp, obj,
1955 Tcl_NewStringObj("detail", -1));
1956 UTF_BEGIN;
1957 Tcl_ListObjAppendElement(interp, obj,
1958 Tcl_NewStringObj(UTF_E2U(edata->detail), -1));
1959 UTF_END;
1960 }
1961 if (edata->hint)
1962 {
1963 Tcl_ListObjAppendElement(interp, obj,
1964 Tcl_NewStringObj("hint", -1));
1965 UTF_BEGIN;
1966 Tcl_ListObjAppendElement(interp, obj,
1967 Tcl_NewStringObj(UTF_E2U(edata->hint), -1));
1968 UTF_END;
1969 }
1970 if (edata->context)
1971 {
1972 Tcl_ListObjAppendElement(interp, obj,
1973 Tcl_NewStringObj("context", -1));
1974 UTF_BEGIN;
1975 Tcl_ListObjAppendElement(interp, obj,
1976 Tcl_NewStringObj(UTF_E2U(edata->context), -1));
1977 UTF_END;
1978 }
1979 if (edata->schema_name)
1980 {
1981 Tcl_ListObjAppendElement(interp, obj,
1982 Tcl_NewStringObj("schema", -1));
1983 UTF_BEGIN;
1984 Tcl_ListObjAppendElement(interp, obj,
1985 Tcl_NewStringObj(UTF_E2U(edata->schema_name), -1));
1986 UTF_END;
1987 }
1988 if (edata->table_name)
1989 {
1990 Tcl_ListObjAppendElement(interp, obj,
1991 Tcl_NewStringObj("table", -1));
1992 UTF_BEGIN;
1993 Tcl_ListObjAppendElement(interp, obj,
1994 Tcl_NewStringObj(UTF_E2U(edata->table_name), -1));
1995 UTF_END;
1996 }
1997 if (edata->column_name)
1998 {
1999 Tcl_ListObjAppendElement(interp, obj,
2000 Tcl_NewStringObj("column", -1));
2001 UTF_BEGIN;
2002 Tcl_ListObjAppendElement(interp, obj,
2003 Tcl_NewStringObj(UTF_E2U(edata->column_name), -1));
2004 UTF_END;
2005 }
2006 if (edata->datatype_name)
2007 {
2008 Tcl_ListObjAppendElement(interp, obj,
2009 Tcl_NewStringObj("datatype", -1));
2010 UTF_BEGIN;
2011 Tcl_ListObjAppendElement(interp, obj,
2012 Tcl_NewStringObj(UTF_E2U(edata->datatype_name), -1));
2013 UTF_END;
2014 }
2015 if (edata->constraint_name)
2016 {
2017 Tcl_ListObjAppendElement(interp, obj,
2018 Tcl_NewStringObj("constraint", -1));
2019 UTF_BEGIN;
2020 Tcl_ListObjAppendElement(interp, obj,
2021 Tcl_NewStringObj(UTF_E2U(edata->constraint_name), -1));
2022 UTF_END;
2023 }
2024 /* cursorpos is never interesting here; report internal query/pos */
2025 if (edata->internalquery)
2026 {
2027 Tcl_ListObjAppendElement(interp, obj,
2028 Tcl_NewStringObj("statement", -1));
2029 UTF_BEGIN;
2030 Tcl_ListObjAppendElement(interp, obj,
2031 Tcl_NewStringObj(UTF_E2U(edata->internalquery), -1));
2032 UTF_END;
2033 }
2034 if (edata->internalpos > 0)
2035 {
2036 Tcl_ListObjAppendElement(interp, obj,
2037 Tcl_NewStringObj("cursor_position", -1));
2038 Tcl_ListObjAppendElement(interp, obj,
2039 Tcl_NewIntObj(edata->internalpos));
2040 }
2041 if (edata->filename)
2042 {
2043 Tcl_ListObjAppendElement(interp, obj,
2044 Tcl_NewStringObj("filename", -1));
2045 UTF_BEGIN;
2046 Tcl_ListObjAppendElement(interp, obj,
2047 Tcl_NewStringObj(UTF_E2U(edata->filename), -1));
2048 UTF_END;
2049 }
2050 if (edata->lineno > 0)
2051 {
2052 Tcl_ListObjAppendElement(interp, obj,
2053 Tcl_NewStringObj("lineno", -1));
2054 Tcl_ListObjAppendElement(interp, obj,
2055 Tcl_NewIntObj(edata->lineno));
2056 }
2057 if (edata->funcname)
2058 {
2059 Tcl_ListObjAppendElement(interp, obj,
2060 Tcl_NewStringObj("funcname", -1));
2061 UTF_BEGIN;
2062 Tcl_ListObjAppendElement(interp, obj,
2063 Tcl_NewStringObj(UTF_E2U(edata->funcname), -1));
2064 UTF_END;
2065 }
2066
2067 Tcl_SetObjErrorCode(interp, obj);
2068}

References fb(), pltcl_get_condition_name(), unpack_sql_state(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_commit(), pltcl_elog(), pltcl_rollback(), and pltcl_subtrans_abort().

◆ pltcl_CreateFileHandler()

static void pltcl_CreateFileHandler ( int  fd,
int  mask,
Tcl_FileProc proc,
ClientData  clientData 
)
static

Definition at line 377 of file pltcl.c.

379{
380}

Referenced by _PG_init().

◆ pltcl_DeleteFileHandler()

static void pltcl_DeleteFileHandler ( int  fd)
static

Definition at line 383 of file pltcl.c.

384{
385}

Referenced by _PG_init().

◆ pltcl_elog()

static int pltcl_elog ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 1843 of file pltcl.c.

1845{
1846 volatile int level;
1847 MemoryContext oldcontext;
1848 int priIndex;
1849
1850 static const char *logpriorities[] = {
1851 "DEBUG", "LOG", "INFO", "NOTICE",
1852 "WARNING", "ERROR", "FATAL", (const char *) NULL
1853 };
1854
1855 static const int loglevels[] = {
1856 DEBUG2, LOG, INFO, NOTICE,
1858 };
1859
1860 if (objc != 3)
1861 {
1862 Tcl_WrongNumArgs(interp, 1, objv, "level msg");
1863 return TCL_ERROR;
1864 }
1865
1866 if (Tcl_GetIndexFromObj(interp, objv[1], logpriorities, "priority",
1868 return TCL_ERROR;
1869
1870 level = loglevels[priIndex];
1871
1872 if (level == ERROR)
1873 {
1874 /*
1875 * We just pass the error back to Tcl. If it's not caught, it'll
1876 * eventually get converted to a PG error when we reach the call
1877 * handler.
1878 */
1879 Tcl_SetObjResult(interp, objv[2]);
1880 return TCL_ERROR;
1881 }
1882
1883 /*
1884 * For non-error messages, just pass 'em to ereport(). We do not expect
1885 * that this will fail, but just on the off chance it does, report the
1886 * error back to Tcl. Note we are assuming that ereport() can't have any
1887 * internal failures that are so bad as to require a transaction abort.
1888 *
1889 * This path is also used for FATAL errors, which aren't going to come
1890 * back to us at all.
1891 */
1892 oldcontext = CurrentMemoryContext;
1893 PG_TRY();
1894 {
1895 UTF_BEGIN;
1896 ereport(level,
1898 errmsg("%s", UTF_U2E(Tcl_GetString(objv[2])))));
1899 UTF_END;
1900 }
1901 PG_CATCH();
1902 {
1904
1905 /* Must reset elog.c's state */
1906 MemoryContextSwitchTo(oldcontext);
1907 edata = CopyErrorData();
1909
1910 /* Pass the error data to Tcl */
1912 UTF_BEGIN;
1913 Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1914 UTF_END;
1916
1917 return TCL_ERROR;
1918 }
1919 PG_END_TRY();
1920
1921 return TCL_OK;
1922}

References CopyErrorData(), CurrentMemoryContext, DEBUG2, ereport, errcode(), errmsg(), ERROR, FATAL, fb(), FlushErrorState(), FreeErrorData(), INFO, LOG, MemoryContextSwitchTo(), NOTICE, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_construct_errorCode(), UTF_BEGIN, UTF_E2U, UTF_END, UTF_U2E, and WARNING.

Referenced by pltcl_init_interp().

◆ pltcl_event_trigger_handler()

static void pltcl_event_trigger_handler ( PG_FUNCTION_ARGS  ,
pltcl_call_state call_state,
bool  pltrusted 
)
static

Definition at line 1318 of file pltcl.c.

1320{
1321 pltcl_proc_desc *prodesc;
1322 Tcl_Interp *volatile interp;
1323 EventTriggerData *tdata = (EventTriggerData *) fcinfo->context;
1325 int tcl_rc;
1326
1327 /* Connect to SPI manager */
1328 SPI_connect();
1329
1330 /* Find or compile the function */
1331 prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1332 InvalidOid, true, pltrusted);
1333
1334 call_state->prodesc = prodesc;
1335 prodesc->fn_refcount++;
1336
1337 interp = prodesc->interp_desc->interp;
1338
1339 /* Create the tcl command and call the internal proc */
1340 tcl_cmd = Tcl_NewObj();
1343 Tcl_NewStringObj(prodesc->internal_proname, -1));
1345 Tcl_NewStringObj(utf_e2u(tdata->event), -1));
1348 -1));
1349
1351
1352 /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1354
1355 /* Check for errors reported by Tcl. */
1356 if (tcl_rc != TCL_OK)
1357 throw_tcl_error(interp, prodesc->user_proname);
1358
1359 if (SPI_finish() != SPI_OK_FINISH)
1360 elog(ERROR, "SPI_finish() failed");
1361}

References compile_pltcl_function(), elog, ERROR, fb(), pltcl_proc_desc::fn_refcount, GetCommandTagName(), pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, InvalidOid, SPI_connect(), SPI_finish(), SPI_OK_FINISH, throw_tcl_error(), pltcl_proc_desc::user_proname, and utf_e2u().

Referenced by pltcl_handler().

◆ pltcl_fetch_interp()

static pltcl_interp_desc * pltcl_fetch_interp ( Oid  prolang,
bool  pltrusted 
)
static

Definition at line 567 of file pltcl.c.

568{
569 Oid user_id;
570 pltcl_interp_desc *interp_desc;
571 bool found;
572
573 /* Find or create the interpreter hashtable entry for this userid */
574 if (pltrusted)
575 user_id = GetUserId();
576 else
577 user_id = InvalidOid;
578
579 interp_desc = hash_search(pltcl_interp_htab, &user_id,
581 &found);
582 if (!found)
583 interp_desc->interp = NULL;
584
585 /* If we haven't yet successfully made an interpreter, try to do that */
586 if (!interp_desc->interp)
587 pltcl_init_interp(interp_desc, prolang, pltrusted);
588
589 return interp_desc;
590}

References fb(), GetUserId(), HASH_ENTER, hash_search(), pltcl_interp_desc::interp, InvalidOid, pltcl_init_interp(), and pltcl_interp_htab.

Referenced by compile_pltcl_function().

◆ pltcl_FinalizeNotifier()

static void pltcl_FinalizeNotifier ( ClientData  clientData)
static

Definition at line 362 of file pltcl.c.

363{
364}

Referenced by _PG_init().

◆ pltcl_func_handler()

static Datum pltcl_func_handler ( PG_FUNCTION_ARGS  ,
pltcl_call_state call_state,
bool  pltrusted 
)
static

Definition at line 801 of file pltcl.c.

803{
804 bool nonatomic;
805 pltcl_proc_desc *prodesc;
806 Tcl_Interp *volatile interp;
808 int i;
809 int tcl_rc;
810 Datum retval;
811
812 nonatomic = fcinfo->context &&
813 IsA(fcinfo->context, CallContext) &&
814 !castNode(CallContext, fcinfo->context)->atomic;
815
816 /* Connect to SPI manager */
818
819 /* Find or compile the function */
820 prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid, InvalidOid,
821 false, pltrusted);
822
823 call_state->prodesc = prodesc;
824 prodesc->fn_refcount++;
825
826 interp = prodesc->interp_desc->interp;
827
828 /*
829 * If we're a SRF, check caller can handle materialize mode, and save
830 * relevant info into call_state. We must ensure that the returned
831 * tuplestore is owned by the caller's context, even if we first create it
832 * inside a subtransaction.
833 */
834 if (prodesc->fn_retisset)
835 {
836 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
837
838 if (!rsi || !IsA(rsi, ReturnSetInfo))
841 errmsg("set-valued function called in context that cannot accept a set")));
842
843 if (!(rsi->allowedModes & SFRM_Materialize))
846 errmsg("materialize mode required, but it is not allowed in this context")));
847
848 call_state->rsi = rsi;
849 call_state->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
850 call_state->tuple_store_owner = CurrentResourceOwner;
851 }
852
853 /************************************************************
854 * Create the tcl command to call the internal
855 * proc in the Tcl interpreter
856 ************************************************************/
859 Tcl_NewStringObj(prodesc->internal_proname, -1));
860
861 /* We hold a refcount on tcl_cmd just to be sure it stays around */
863
864 /************************************************************
865 * Add all call arguments to the command
866 ************************************************************/
867 PG_TRY();
868 {
869 for (i = 0; i < prodesc->nargs; i++)
870 {
871 if (prodesc->arg_is_rowtype[i])
872 {
873 /**************************************************
874 * For tuple values, add a list for 'array set ...'
875 **************************************************/
876 if (fcinfo->args[i].isnull)
878 else
879 {
881 Oid tupType;
883 TupleDesc tupdesc;
886
887 td = DatumGetHeapTupleHeader(fcinfo->args[i].value);
888 /* Extract rowtype info and find a tupdesc */
892 /* Build a temporary HeapTuple control structure */
894 tmptup.t_data = td;
895
896 list_tmp = pltcl_build_tuple_argument(&tmptup, tupdesc, true);
898
899 ReleaseTupleDesc(tupdesc);
900 }
901 }
902 else
903 {
904 /**************************************************
905 * Single values are added as string element
906 * of their external representation
907 **************************************************/
908 if (fcinfo->args[i].isnull)
910 else
911 {
912 char *tmp;
913
914 tmp = OutputFunctionCall(&prodesc->arg_out_func[i],
915 fcinfo->args[i].value);
916 UTF_BEGIN;
918 Tcl_NewStringObj(UTF_E2U(tmp), -1));
919 UTF_END;
920 pfree(tmp);
921 }
922 }
923 }
924 }
925 PG_CATCH();
926 {
927 /* Release refcount to free tcl_cmd */
929 PG_RE_THROW();
930 }
931 PG_END_TRY();
932
933 /************************************************************
934 * Call the Tcl function
935 *
936 * We assume no PG error can be thrown directly from this call.
937 ************************************************************/
939
940 /* Release refcount to free tcl_cmd (and all subsidiary objects) */
942
943 /************************************************************
944 * Check for errors reported by Tcl.
945 ************************************************************/
946 if (tcl_rc != TCL_OK)
947 throw_tcl_error(interp, prodesc->user_proname);
948
949 /************************************************************
950 * Disconnect from SPI manager and then create the return
951 * value datum (if the input function does a palloc for it
952 * this must not be allocated in the SPI memory context
953 * because SPI_finish would free it). But don't try to call
954 * the result_in_func if we've been told to return a NULL;
955 * the Tcl result may not be a valid value of the result type
956 * in that case.
957 ************************************************************/
958 if (SPI_finish() != SPI_OK_FINISH)
959 elog(ERROR, "SPI_finish() failed");
960
961 if (prodesc->fn_retisset)
962 {
963 ReturnSetInfo *rsi = call_state->rsi;
964
965 /* We already checked this is OK */
967
968 /* If we produced any tuples, send back the result */
969 if (call_state->tuple_store)
970 {
971 rsi->setResult = call_state->tuple_store;
972 if (call_state->ret_tupdesc)
973 {
975
976 oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
977 rsi->setDesc = CreateTupleDescCopy(call_state->ret_tupdesc);
979 }
980 }
981 retval = (Datum) 0;
982 fcinfo->isnull = true;
983 }
984 else if (fcinfo->isnull)
985 {
986 retval = InputFunctionCall(&prodesc->result_in_func,
987 NULL,
988 prodesc->result_typioparam,
989 -1);
990 }
991 else if (prodesc->fn_retistuple)
992 {
993 TupleDesc td;
998
999 /*
1000 * Set up data about result type. XXX it's tempting to consider
1001 * caching this in the prodesc, in the common case where the rowtype
1002 * is determined by the function not the calling query. But we'd have
1003 * to be able to deal with ADD/DROP/ALTER COLUMN events when the
1004 * result type is a named composite type, so it's not exactly trivial.
1005 * Maybe worth improving someday.
1006 */
1007 switch (get_call_result_type(fcinfo, NULL, &td))
1008 {
1009 case TYPEFUNC_COMPOSITE:
1010 /* success */
1011 break;
1013 Assert(prodesc->fn_retisdomain);
1014 break;
1015 case TYPEFUNC_RECORD:
1016 /* failed to determine actual type of RECORD */
1017 ereport(ERROR,
1019 errmsg("function returning record called in context "
1020 "that cannot accept type record")));
1021 break;
1022 default:
1023 /* result type isn't composite? */
1024 elog(ERROR, "return type must be a row type");
1025 break;
1026 }
1027
1028 Assert(!call_state->ret_tupdesc);
1029 Assert(!call_state->attinmeta);
1030 call_state->ret_tupdesc = td;
1031 call_state->attinmeta = TupleDescGetAttInMetadata(td);
1032
1033 /* Convert function result to tuple */
1034 resultObj = Tcl_GetObjResult(interp);
1036 ereport(ERROR,
1038 errmsg("could not parse function return value: %s",
1039 utf_u2e(Tcl_GetStringResult(interp)))));
1040
1042 call_state);
1043 retval = HeapTupleGetDatum(tup);
1044 }
1045 else
1046 retval = InputFunctionCall(&prodesc->result_in_func,
1048 prodesc->result_typioparam,
1049 -1);
1050
1051 return retval;
1052}

References ReturnSetInfo::allowedModes, pltcl_proc_desc::arg_is_rowtype, pltcl_proc_desc::arg_out_func, Assert, castNode, compile_pltcl_function(), CreateTupleDescCopy(), CurrentResourceOwner, DatumGetHeapTupleHeader, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, fb(), pltcl_proc_desc::fn_refcount, pltcl_proc_desc::fn_retisdomain, pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, get_call_result_type(), HeapTupleGetDatum(), HeapTupleHeaderGetDatumLength(), HeapTupleHeaderGetTypeId(), HeapTupleHeaderGetTypMod(), i, InputFunctionCall(), pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, InvalidOid, IsA, lookup_rowtype_tupdesc(), MemoryContextSwitchTo(), pltcl_proc_desc::nargs, OutputFunctionCall(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pltcl_build_tuple_argument(), pltcl_build_tuple_result(), ReleaseTupleDesc, pltcl_proc_desc::result_in_func, pltcl_proc_desc::result_typioparam, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SPI_connect_ext(), SPI_finish(), SPI_OK_FINISH, SPI_OPT_NONATOMIC, throw_tcl_error(), TupleDescGetAttInMetadata(), TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, TYPEFUNC_RECORD, pltcl_proc_desc::user_proname, UTF_BEGIN, UTF_E2U, UTF_END, and utf_u2e().

Referenced by pltcl_handler().

◆ pltcl_get_condition_name()

static const char * pltcl_get_condition_name ( int  sqlstate)
static

Definition at line 2075 of file pltcl.c.

2076{
2077 int i;
2078
2079 for (i = 0; exception_name_map[i].label != NULL; i++)
2080 {
2081 if (exception_name_map[i].sqlerrstate == sqlstate)
2082 return exception_name_map[i].label;
2083 }
2084 return "unrecognized_sqlstate";
2085}

References exception_name_map, fb(), i, and TclExceptionNameMap::label.

Referenced by pltcl_construct_errorCode().

◆ pltcl_handler()

static Datum pltcl_handler ( PG_FUNCTION_ARGS  ,
bool  pltrusted 
)
static

Definition at line 727 of file pltcl.c.

728{
729 Datum retval = (Datum) 0;
732
733 /*
734 * Initialize current_call_state to nulls/zeroes; in particular, set its
735 * prodesc pointer to null. Anything that sets it non-null should
736 * increase the prodesc's fn_refcount at the same time. We'll decrease
737 * the refcount, and then delete the prodesc if it's no longer referenced,
738 * on the way out of this function. This ensures that prodescs live as
739 * long as needed even if somebody replaces the originating pg_proc row
740 * while they're executing.
741 */
743
744 /*
745 * Ensure that static pointer is saved/restored properly
746 */
749
750 PG_TRY();
751 {
752 /*
753 * Determine if called as function or trigger and call appropriate
754 * subhandler
755 */
756 if (CALLED_AS_TRIGGER(fcinfo))
757 {
758 /* invoke the trigger handler */
761 pltrusted));
762 }
763 else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
764 {
765 /* invoke the event trigger handler */
767 retval = (Datum) 0;
768 }
769 else
770 {
771 /* invoke the regular function handler */
772 current_call_state.fcinfo = fcinfo;
773 retval = pltcl_func_handler(fcinfo, &current_call_state, pltrusted);
774 }
775 }
776 PG_FINALLY();
777 {
778 /* Restore static pointer, then clean up the prodesc refcount if any */
779 /*
780 * (We're being paranoid in case an error is thrown in context
781 * deletion)
782 */
784 if (current_call_state.prodesc != NULL)
785 {
786 Assert(current_call_state.prodesc->fn_refcount > 0);
787 if (--current_call_state.prodesc->fn_refcount == 0)
789 }
790 }
791 PG_END_TRY();
792
793 return retval;
794}

References Assert, CALLED_AS_EVENT_TRIGGER, CALLED_AS_TRIGGER, fb(), MemoryContextDelete(), PG_END_TRY, PG_FINALLY, PG_TRY, pltcl_current_call_state, pltcl_event_trigger_handler(), pltcl_func_handler(), pltcl_trigger_handler(), and PointerGetDatum().

Referenced by pltcl_call_handler(), and pltclu_call_handler().

◆ pltcl_init_interp()

static void pltcl_init_interp ( pltcl_interp_desc interp_desc,
Oid  prolang,
bool  pltrusted 
)
static

Definition at line 494 of file pltcl.c.

495{
496 Tcl_Interp *interp;
497 char interpname[32];
498
499 /************************************************************
500 * Create the Tcl interpreter subsidiary to pltcl_hold_interp.
501 * Note: Tcl automatically does Tcl_Init in the untrusted case,
502 * and it's not wanted in the trusted case.
503 ************************************************************/
504 snprintf(interpname, sizeof(interpname), "subsidiary_%u", interp_desc->user_id);
506 pltrusted ? 1 : 0)) == NULL)
507 elog(ERROR, "could not create subsidiary Tcl interpreter");
508
509 /************************************************************
510 * Initialize the query hash table associated with interpreter
511 ************************************************************/
513
514 /************************************************************
515 * Install the commands for SPI support in the interpreter
516 ************************************************************/
517 Tcl_CreateObjCommand(interp, "elog",
519 Tcl_CreateObjCommand(interp, "quote",
521 Tcl_CreateObjCommand(interp, "argisnull",
523 Tcl_CreateObjCommand(interp, "return_null",
525 Tcl_CreateObjCommand(interp, "return_next",
527 Tcl_CreateObjCommand(interp, "spi_exec",
529 Tcl_CreateObjCommand(interp, "spi_prepare",
531 Tcl_CreateObjCommand(interp, "spi_execp",
533 Tcl_CreateObjCommand(interp, "subtransaction",
535 Tcl_CreateObjCommand(interp, "commit",
537 Tcl_CreateObjCommand(interp, "rollback",
539
540 /************************************************************
541 * Call the appropriate start_proc, if there is one.
542 *
543 * We must set interp_desc->interp before the call, else the start_proc
544 * won't find the interpreter it's supposed to use. But, if the
545 * start_proc fails, we want to abandon use of the interpreter.
546 ************************************************************/
547 PG_TRY();
548 {
549 interp_desc->interp = interp;
550 call_pltcl_start_proc(prolang, pltrusted);
551 }
552 PG_CATCH();
553 {
554 interp_desc->interp = NULL;
555 Tcl_DeleteInterp(interp);
556 PG_RE_THROW();
557 }
558 PG_END_TRY();
559}

References call_pltcl_start_proc(), elog, ERROR, fb(), pltcl_interp_desc::interp, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pltcl_argisnull(), pltcl_commit(), pltcl_elog(), pltcl_hold_interp, pltcl_quote(), pltcl_returnnext(), pltcl_returnnull(), pltcl_rollback(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), pltcl_SPI_prepare(), pltcl_subtransaction(), pltcl_interp_desc::query_hash, snprintf, and pltcl_interp_desc::user_id.

Referenced by pltcl_fetch_interp().

◆ pltcl_init_tuple_store()

static void pltcl_init_tuple_store ( pltcl_call_state call_state)
static

Definition at line 3351 of file pltcl.c.

3352{
3353 ReturnSetInfo *rsi = call_state->rsi;
3355 ResourceOwner oldowner;
3356
3357 /* Should be in a SRF */
3358 Assert(rsi);
3359 /* Should be first time through */
3360 Assert(!call_state->tuple_store);
3361 Assert(!call_state->attinmeta);
3362
3363 /* We expect caller to provide an appropriate result tupdesc */
3364 Assert(rsi->expectedDesc);
3365 call_state->ret_tupdesc = rsi->expectedDesc;
3366
3367 /*
3368 * Switch to the right memory context and resource owner for storing the
3369 * tuplestore. If we're within a subtransaction opened for an exception
3370 * block, for example, we must still create the tuplestore in the resource
3371 * owner that was active when this function was entered, and not in the
3372 * subtransaction's resource owner.
3373 */
3374 oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
3375 oldowner = CurrentResourceOwner;
3376 CurrentResourceOwner = call_state->tuple_store_owner;
3377
3378 call_state->tuple_store =
3380 false, work_mem);
3381
3382 /* Build attinmeta in this context, too */
3383 call_state->attinmeta = TupleDescGetAttInMetadata(call_state->ret_tupdesc);
3384
3385 CurrentResourceOwner = oldowner;
3387}

References ReturnSetInfo::allowedModes, Assert, CurrentResourceOwner, ReturnSetInfo::expectedDesc, fb(), MemoryContextSwitchTo(), SFRM_Materialize_Random, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), and work_mem.

Referenced by pltcl_returnnext().

◆ pltcl_InitNotifier()

static ClientData pltcl_InitNotifier ( void  )
static

Definition at line 354 of file pltcl.c.

355{
356 static int fakeThreadKey; /* To give valid address for ClientData */
357
358 return (ClientData) &(fakeThreadKey);
359}

References fb().

Referenced by _PG_init().

◆ pltcl_process_SPI_result()

static int pltcl_process_SPI_result ( Tcl_Interp interp,
const char arrayname,
Tcl_Obj loop_body,
int  spi_rc,
SPITupleTable tuptable,
uint64  ntuples 
)
static

Definition at line 2518 of file pltcl.c.

2524{
2525 int my_rc = TCL_OK;
2526 int loop_rc;
2527 HeapTuple *tuples;
2528 TupleDesc tupdesc;
2529
2530 switch (spi_rc)
2531 {
2532 case SPI_OK_SELINTO:
2533 case SPI_OK_INSERT:
2534 case SPI_OK_DELETE:
2535 case SPI_OK_UPDATE:
2536 case SPI_OK_MERGE:
2537 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2538 break;
2539
2540 case SPI_OK_UTILITY:
2541 case SPI_OK_REWRITTEN:
2542 if (tuptable == NULL)
2543 {
2544 Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
2545 break;
2546 }
2547 /* fall through for utility returning tuples */
2548 /* FALLTHROUGH */
2549
2550 case SPI_OK_SELECT:
2555
2556 /*
2557 * Process the tuples we got
2558 */
2559 tuples = tuptable->vals;
2560 tupdesc = tuptable->tupdesc;
2561
2562 if (loop_body == NULL)
2563 {
2564 /*
2565 * If there is no loop body given, just set the variables from
2566 * the first tuple (if any)
2567 */
2568 if (ntuples > 0)
2570 tuples[0], tupdesc);
2571 }
2572 else
2573 {
2574 /*
2575 * There is a loop body - process all tuples and evaluate the
2576 * body on each
2577 */
2578 uint64 i;
2579
2580 for (i = 0; i < ntuples; i++)
2581 {
2583 tuples[i], tupdesc);
2584
2585 loop_rc = Tcl_EvalObjEx(interp, loop_body, 0);
2586
2587 if (loop_rc == TCL_OK)
2588 continue;
2589 if (loop_rc == TCL_CONTINUE)
2590 continue;
2591 if (loop_rc == TCL_RETURN)
2592 {
2593 my_rc = TCL_RETURN;
2594 break;
2595 }
2596 if (loop_rc == TCL_BREAK)
2597 break;
2598 my_rc = TCL_ERROR;
2599 break;
2600 }
2601 }
2602
2603 if (my_rc == TCL_OK)
2604 {
2605 Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2606 }
2607 break;
2608
2609 default:
2610 Tcl_AppendResult(interp, "pltcl: SPI_execute failed: ",
2612 my_rc = TCL_ERROR;
2613 break;
2614 }
2615
2616 SPI_freetuptable(tuptable);
2617
2618 return my_rc;
2619}

References fb(), i, pltcl_set_tuple_values(), SPI_freetuptable(), SPI_OK_DELETE, SPI_OK_DELETE_RETURNING, SPI_OK_INSERT, SPI_OK_INSERT_RETURNING, SPI_OK_MERGE, SPI_OK_MERGE_RETURNING, SPI_OK_REWRITTEN, SPI_OK_SELECT, SPI_OK_SELINTO, SPI_OK_UPDATE, SPI_OK_UPDATE_RETURNING, SPI_OK_UTILITY, SPI_result_code_string(), SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by pltcl_SPI_execute(), and pltcl_SPI_execute_plan().

◆ pltcl_quote()

static int pltcl_quote ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2093 of file pltcl.c.

2095{
2096 char *tmp;
2097 const char *cp1;
2098 char *cp2;
2099 Tcl_Size length;
2100
2101 /************************************************************
2102 * Check call syntax
2103 ************************************************************/
2104 if (objc != 2)
2105 {
2106 Tcl_WrongNumArgs(interp, 1, objv, "string");
2107 return TCL_ERROR;
2108 }
2109
2110 /************************************************************
2111 * Allocate space for the maximum the string can
2112 * grow to and initialize pointers
2113 ************************************************************/
2114 cp1 = Tcl_GetStringFromObj(objv[1], &length);
2115 tmp = palloc(length * 2 + 1);
2116 cp2 = tmp;
2117
2118 /************************************************************
2119 * Walk through string and double every quote and backslash
2120 ************************************************************/
2121 while (*cp1)
2122 {
2123 if (*cp1 == '\'')
2124 *cp2++ = '\'';
2125 else
2126 {
2127 if (*cp1 == '\\')
2128 *cp2++ = '\\';
2129 }
2130 *cp2++ = *cp1++;
2131 }
2132
2133 /************************************************************
2134 * Terminate the string and set it as result
2135 ************************************************************/
2136 *cp2 = '\0';
2137 Tcl_SetObjResult(interp, Tcl_NewStringObj(tmp, -1));
2138 pfree(tmp);
2139 return TCL_OK;
2140}

References fb(), palloc(), and pfree().

Referenced by pltcl_init_interp().

◆ pltcl_returnnext()

static int pltcl_returnnext ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2239 of file pltcl.c.

2241{
2243 FunctionCallInfo fcinfo = call_state->fcinfo;
2244 pltcl_proc_desc *prodesc = call_state->prodesc;
2247 volatile int result = TCL_OK;
2248
2249 /*
2250 * Check that we're called as a set-returning function
2251 */
2252 if (fcinfo == NULL)
2253 {
2254 Tcl_SetObjResult(interp,
2255 Tcl_NewStringObj("return_next cannot be used in triggers", -1));
2256 return TCL_ERROR;
2257 }
2258
2259 if (!prodesc->fn_retisset)
2260 {
2261 Tcl_SetObjResult(interp,
2262 Tcl_NewStringObj("return_next cannot be used in non-set-returning functions", -1));
2263 return TCL_ERROR;
2264 }
2265
2266 /*
2267 * Check call syntax
2268 */
2269 if (objc != 2)
2270 {
2271 Tcl_WrongNumArgs(interp, 1, objv, "result");
2272 return TCL_ERROR;
2273 }
2274
2275 /*
2276 * The rest might throw elog(ERROR), so must run in a subtransaction.
2277 *
2278 * A small advantage of using a subtransaction is that it provides a
2279 * short-lived memory context for free, so we needn't worry about leaking
2280 * memory here. To use that context, call BeginInternalSubTransaction
2281 * directly instead of going through pltcl_subtrans_begin.
2282 */
2284 PG_TRY();
2285 {
2286 /* Set up tuple store if first output row */
2287 if (call_state->tuple_store == NULL)
2289
2290 if (prodesc->fn_retistuple)
2291 {
2292 Tcl_Obj **rowObjv;
2294
2295 /* result should be a list, so break it down */
2296 if (Tcl_ListObjGetElements(interp, objv[1], &rowObjc, &rowObjv) == TCL_ERROR)
2297 result = TCL_ERROR;
2298 else
2299 {
2300 HeapTuple tuple;
2301
2302 tuple = pltcl_build_tuple_result(interp, rowObjv, rowObjc,
2303 call_state);
2304 tuplestore_puttuple(call_state->tuple_store, tuple);
2305 }
2306 }
2307 else
2308 {
2309 Datum retval;
2310 bool isNull = false;
2311
2312 /* for paranoia's sake, check that tupdesc has exactly one column */
2313 if (call_state->ret_tupdesc->natts != 1)
2314 elog(ERROR, "wrong result type supplied in return_next");
2315
2316 retval = InputFunctionCall(&prodesc->result_in_func,
2317 utf_u2e((char *) Tcl_GetString(objv[1])),
2318 prodesc->result_typioparam,
2319 -1);
2320 tuplestore_putvalues(call_state->tuple_store, call_state->ret_tupdesc,
2321 &retval, &isNull);
2322 }
2323
2324 pltcl_subtrans_commit(oldcontext, oldowner);
2325 }
2326 PG_CATCH();
2327 {
2328 pltcl_subtrans_abort(interp, oldcontext, oldowner);
2329 return TCL_ERROR;
2330 }
2331 PG_END_TRY();
2332
2333 return result;
2334}

References BeginInternalSubTransaction(), CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, fb(), pltcl_proc_desc::fn_retisset, pltcl_proc_desc::fn_retistuple, InputFunctionCall(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_build_tuple_result(), pltcl_current_call_state, pltcl_init_tuple_store(), pltcl_subtrans_abort(), pltcl_subtrans_commit(), pltcl_proc_desc::result_in_func, pltcl_proc_desc::result_typioparam, tuplestore_puttuple(), tuplestore_putvalues(), and utf_u2e().

Referenced by pltcl_init_interp().

◆ pltcl_returnnull()

static int pltcl_returnnull ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2201 of file pltcl.c.

2203{
2205
2206 /************************************************************
2207 * Check call syntax
2208 ************************************************************/
2209 if (objc != 1)
2210 {
2211 Tcl_WrongNumArgs(interp, 1, objv, "");
2212 return TCL_ERROR;
2213 }
2214
2215 /************************************************************
2216 * Check that we're called as a normal function
2217 ************************************************************/
2218 if (fcinfo == NULL)
2219 {
2220 Tcl_SetObjResult(interp,
2221 Tcl_NewStringObj("return_null cannot be used in triggers", -1));
2222 return TCL_ERROR;
2223 }
2224
2225 /************************************************************
2226 * Set the NULL return flag and cause Tcl to return from the
2227 * procedure.
2228 ************************************************************/
2229 fcinfo->isnull = true;
2230
2231 return TCL_RETURN;
2232}

References fb(), pltcl_call_state::fcinfo, FunctionCallInfoBaseData::isnull, and pltcl_current_call_state.

Referenced by pltcl_init_interp().

◆ pltcl_rollback()

static int pltcl_rollback ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 3062 of file pltcl.c.

3064{
3066
3067 PG_TRY();
3068 {
3069 SPI_rollback();
3070 }
3071 PG_CATCH();
3072 {
3074
3075 /* Save error info */
3076 MemoryContextSwitchTo(oldcontext);
3077 edata = CopyErrorData();
3079
3080 /* Pass the error data to Tcl */
3082 UTF_BEGIN;
3083 Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
3084 UTF_END;
3086
3087 return TCL_ERROR;
3088 }
3089 PG_END_TRY();
3090
3091 return TCL_OK;
3092}

References CopyErrorData(), CurrentMemoryContext, fb(), FlushErrorState(), FreeErrorData(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_construct_errorCode(), SPI_rollback(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_init_interp().

◆ pltcl_ServiceModeHook()

static void pltcl_ServiceModeHook ( int  mode)
static

Definition at line 388 of file pltcl.c.

389{
390}

Referenced by _PG_init().

◆ pltcl_set_tuple_values()

static void pltcl_set_tuple_values ( Tcl_Interp interp,
const char arrayname,
uint64  tupno,
HeapTuple  tuple,
TupleDesc  tupdesc 
)
static

Definition at line 3102 of file pltcl.c.

3104{
3105 int i;
3106 char *outputstr;
3107 Datum attr;
3108 bool isnull;
3109 const char *attname;
3110 Oid typoutput;
3111 bool typisvarlena;
3112 const char **arrptr;
3113 const char **nameptr;
3114 const char *nullname = NULL;
3115
3116 /************************************************************
3117 * Prepare pointers for Tcl_SetVar2Ex() below
3118 ************************************************************/
3119 if (arrayname == NULL)
3120 {
3121 arrptr = &attname;
3122 nameptr = &nullname;
3123 }
3124 else
3125 {
3126 arrptr = &arrayname;
3127 nameptr = &attname;
3128
3129 /*
3130 * When outputting to an array, fill the ".tupno" element with the
3131 * current tuple number. This will be overridden below if ".tupno" is
3132 * in use as an actual field name in the rowtype.
3133 */
3134 Tcl_SetVar2Ex(interp, arrayname, ".tupno", Tcl_NewWideIntObj(tupno), 0);
3135 }
3136
3137 for (i = 0; i < tupdesc->natts; i++)
3138 {
3140
3141 /* ignore dropped attributes */
3142 if (att->attisdropped)
3143 continue;
3144
3145 /************************************************************
3146 * Get the attribute name
3147 ************************************************************/
3148 UTF_BEGIN;
3149 attname = pstrdup(UTF_E2U(NameStr(att->attname)));
3150 UTF_END;
3151
3152 /************************************************************
3153 * Get the attributes value
3154 ************************************************************/
3155 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3156
3157 /************************************************************
3158 * If there is a value, set the variable
3159 * If not, unset it
3160 *
3161 * Hmmm - Null attributes will cause functions to
3162 * crash if they don't expect them - need something
3163 * smarter here.
3164 ************************************************************/
3165 if (!isnull)
3166 {
3167 getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3168 outputstr = OidOutputFunctionCall(typoutput, attr);
3169 UTF_BEGIN;
3170 Tcl_SetVar2Ex(interp, *arrptr, *nameptr,
3172 UTF_END;
3174 }
3175 else
3176 Tcl_UnsetVar2(interp, *arrptr, *nameptr, 0);
3177
3178 pfree(unconstify(char *, attname));
3179 }
3180}

References attname, fb(), getTypeOutputInfo(), heap_getattr(), i, NameStr, TupleDescData::natts, OidOutputFunctionCall(), pfree(), pstrdup(), TupleDescAttr(), unconstify, UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_process_SPI_result().

◆ pltcl_SetTimer()

static void pltcl_SetTimer ( CONST86 Tcl_Time timePtr)
static

Definition at line 367 of file pltcl.c.

368{
369}

Referenced by _PG_init().

◆ pltcl_SPI_execute()

static int pltcl_SPI_execute ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2409 of file pltcl.c.

2411{
2412 int my_rc;
2413 int spi_rc;
2414 int query_idx;
2415 int i;
2416 int optIndex;
2417 int count = 0;
2418 const char *volatile arrayname = NULL;
2419 Tcl_Obj *volatile loop_body = NULL;
2422
2423 enum options
2424 {
2426 };
2427
2428 static const char *options[] = {
2429 "-array", "-count", (const char *) NULL
2430 };
2431
2432 /************************************************************
2433 * Check the call syntax and get the options
2434 ************************************************************/
2435 if (objc < 2)
2436 {
2437 Tcl_WrongNumArgs(interp, 1, objv,
2438 "?-count n? ?-array name? query ?loop body?");
2439 return TCL_ERROR;
2440 }
2441
2442 i = 1;
2443 while (i < objc)
2444 {
2447 break;
2448
2449 if (++i >= objc)
2450 {
2451 Tcl_SetObjResult(interp,
2452 Tcl_NewStringObj("missing argument to -count or -array", -1));
2453 return TCL_ERROR;
2454 }
2455
2456 switch ((enum options) optIndex)
2457 {
2458 case OPT_ARRAY:
2460 break;
2461
2462 case OPT_COUNT:
2463 if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
2464 return TCL_ERROR;
2465 break;
2466 }
2467 }
2468
2469 query_idx = i;
2470 if (query_idx >= objc || query_idx + 2 < objc)
2471 {
2472 Tcl_WrongNumArgs(interp, query_idx - 1, objv, "query ?loop body?");
2473 return TCL_ERROR;
2474 }
2475
2476 if (query_idx + 1 < objc)
2477 loop_body = objv[query_idx + 1];
2478
2479 /************************************************************
2480 * Execute the query inside a sub-transaction, so we can cope with
2481 * errors sanely
2482 ************************************************************/
2483
2484 pltcl_subtrans_begin(oldcontext, oldowner);
2485
2486 PG_TRY();
2487 {
2488 UTF_BEGIN;
2491 UTF_END;
2492
2494 arrayname,
2495 loop_body,
2496 spi_rc,
2499
2500 pltcl_subtrans_commit(oldcontext, oldowner);
2501 }
2502 PG_CATCH();
2503 {
2504 pltcl_subtrans_abort(interp, oldcontext, oldowner);
2505 return TCL_ERROR;
2506 }
2507 PG_END_TRY();
2508
2509 return my_rc;
2510}

References CurrentMemoryContext, CurrentResourceOwner, fb(), pltcl_proc_desc::fn_readonly, i, PG_CATCH, PG_END_TRY, PG_TRY, pltcl_current_call_state, pltcl_process_SPI_result(), pltcl_subtrans_abort(), pltcl_subtrans_begin(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, SPI_execute(), SPI_processed, SPI_tuptable, UTF_BEGIN, UTF_END, and UTF_U2E.

Referenced by pltcl_init_interp().

◆ pltcl_SPI_execute_plan()

static int pltcl_SPI_execute_plan ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2759 of file pltcl.c.

2761{
2762 int my_rc;
2763 int spi_rc;
2764 int i;
2765 int j;
2766 int optIndex;
2769 const char *nulls = NULL;
2770 const char *arrayname = NULL;
2772 int count = 0;
2774 Tcl_Obj **callObjv = NULL;
2778 Tcl_HashTable *query_hash;
2779
2780 enum options
2781 {
2783 };
2784
2785 static const char *options[] = {
2786 "-array", "-count", "-nulls", (const char *) NULL
2787 };
2788
2789 /************************************************************
2790 * Get the options and check syntax
2791 ************************************************************/
2792 i = 1;
2793 while (i < objc)
2794 {
2797 break;
2798
2799 if (++i >= objc)
2800 {
2801 Tcl_SetObjResult(interp,
2802 Tcl_NewStringObj("missing argument to -array, -count or -nulls", -1));
2803 return TCL_ERROR;
2804 }
2805
2806 switch ((enum options) optIndex)
2807 {
2808 case OPT_ARRAY:
2810 break;
2811
2812 case OPT_COUNT:
2813 if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
2814 return TCL_ERROR;
2815 break;
2816
2817 case OPT_NULLS:
2818 nulls = Tcl_GetString(objv[i++]);
2819 break;
2820 }
2821 }
2822
2823 /************************************************************
2824 * Get the prepared plan descriptor by its key
2825 ************************************************************/
2826 if (i >= objc)
2827 {
2828 Tcl_SetObjResult(interp,
2829 Tcl_NewStringObj("missing argument to -count or -array", -1));
2830 return TCL_ERROR;
2831 }
2832
2834
2835 hashent = Tcl_FindHashEntry(query_hash, Tcl_GetString(objv[i]));
2836 if (hashent == NULL)
2837 {
2838 Tcl_AppendResult(interp, "invalid queryid '", Tcl_GetString(objv[i]), "'", NULL);
2839 return TCL_ERROR;
2840 }
2842 i++;
2843
2844 /************************************************************
2845 * If a nulls string is given, check for correct length
2846 ************************************************************/
2847 if (nulls != NULL)
2848 {
2849 if (strlen(nulls) != qdesc->nargs)
2850 {
2851 Tcl_SetObjResult(interp,
2852 Tcl_NewStringObj("length of nulls string doesn't match number of arguments",
2853 -1));
2854 return TCL_ERROR;
2855 }
2856 }
2857
2858 /************************************************************
2859 * If there was an argtype list on preparation, we need
2860 * an argument value list now
2861 ************************************************************/
2862 if (qdesc->nargs > 0)
2863 {
2864 if (i >= objc)
2865 {
2866 Tcl_SetObjResult(interp,
2867 Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
2868 -1));
2869 return TCL_ERROR;
2870 }
2871
2872 /************************************************************
2873 * Split the argument values
2874 ************************************************************/
2875 if (Tcl_ListObjGetElements(interp, objv[i++], &callObjc, &callObjv) != TCL_OK)
2876 return TCL_ERROR;
2877
2878 /************************************************************
2879 * Check that the number of arguments matches
2880 ************************************************************/
2881 if (callObjc != qdesc->nargs)
2882 {
2883 Tcl_SetObjResult(interp,
2884 Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
2885 -1));
2886 return TCL_ERROR;
2887 }
2888 }
2889 else
2890 callObjc = 0;
2891
2892 /************************************************************
2893 * Get loop body if present
2894 ************************************************************/
2895 if (i < objc)
2896 loop_body = objv[i++];
2897
2898 if (i != objc)
2899 {
2900 Tcl_WrongNumArgs(interp, 1, objv,
2901 "?-count n? ?-array name? ?-nulls string? "
2902 "query ?args? ?loop body?");
2903 return TCL_ERROR;
2904 }
2905
2906 /************************************************************
2907 * Execute the plan inside a sub-transaction, so we can cope with
2908 * errors sanely
2909 ************************************************************/
2910
2911 pltcl_subtrans_begin(oldcontext, oldowner);
2912
2913 PG_TRY();
2914 {
2915 /************************************************************
2916 * Setup the value array for SPI_execute_plan() using
2917 * the type specific input functions
2918 ************************************************************/
2919 argvalues = (Datum *) palloc(callObjc * sizeof(Datum));
2920
2921 for (j = 0; j < callObjc; j++)
2922 {
2923 if (nulls && nulls[j] == 'n')
2924 {
2925 argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
2926 NULL,
2927 qdesc->argtypioparams[j],
2928 -1);
2929 }
2930 else
2931 {
2932 UTF_BEGIN;
2933 argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
2935 qdesc->argtypioparams[j],
2936 -1);
2937 UTF_END;
2938 }
2939 }
2940
2941 /************************************************************
2942 * Execute the plan
2943 ************************************************************/
2944 spi_rc = SPI_execute_plan(qdesc->plan, argvalues, nulls,
2946 count);
2947
2949 arrayname,
2950 loop_body,
2951 spi_rc,
2954
2955 pltcl_subtrans_commit(oldcontext, oldowner);
2956 }
2957 PG_CATCH();
2958 {
2959 pltcl_subtrans_abort(interp, oldcontext, oldowner);
2960 return TCL_ERROR;
2961 }
2962 PG_END_TRY();
2963
2964 return my_rc;
2965}

References CurrentMemoryContext, CurrentResourceOwner, fb(), pltcl_proc_desc::fn_readonly, i, InputFunctionCall(), pltcl_proc_desc::interp_desc, j, palloc(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_current_call_state, pltcl_process_SPI_result(), pltcl_subtrans_abort(), pltcl_subtrans_begin(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, pltcl_interp_desc::query_hash, SPI_execute_plan(), SPI_processed, SPI_tuptable, UTF_BEGIN, UTF_END, and UTF_U2E.

Referenced by pltcl_init_interp().

◆ pltcl_SPI_prepare()

static int pltcl_SPI_prepare ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2631 of file pltcl.c.

2633{
2634 volatile MemoryContext plan_cxt = NULL;
2635 Tcl_Size nargs;
2636 Tcl_Obj **argsObj;
2638 int i;
2640 int hashnew;
2641 Tcl_HashTable *query_hash;
2644
2645 /************************************************************
2646 * Check the call syntax
2647 ************************************************************/
2648 if (objc != 3)
2649 {
2650 Tcl_WrongNumArgs(interp, 1, objv, "query argtypes");
2651 return TCL_ERROR;
2652 }
2653
2654 /************************************************************
2655 * Split the argument type list
2656 ************************************************************/
2657 if (Tcl_ListObjGetElements(interp, objv[2], &nargs, &argsObj) != TCL_OK)
2658 return TCL_ERROR;
2659
2660 /************************************************************
2661 * Allocate the new querydesc structure
2662 *
2663 * struct qdesc and subsidiary data all live in plan_cxt. Note that if the
2664 * function is recompiled for whatever reason, permanent memory leaks
2665 * occur. FIXME someday.
2666 ************************************************************/
2668 "PL/Tcl spi_prepare query",
2670 MemoryContextSwitchTo(plan_cxt);
2672 snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
2673 qdesc->nargs = nargs;
2674 qdesc->argtypes = (Oid *) palloc(nargs * sizeof(Oid));
2675 qdesc->arginfuncs = (FmgrInfo *) palloc(nargs * sizeof(FmgrInfo));
2676 qdesc->argtypioparams = (Oid *) palloc(nargs * sizeof(Oid));
2677 MemoryContextSwitchTo(oldcontext);
2678
2679 /************************************************************
2680 * Execute the prepare inside a sub-transaction, so we can cope with
2681 * errors sanely
2682 ************************************************************/
2683
2684 pltcl_subtrans_begin(oldcontext, oldowner);
2685
2686 PG_TRY();
2687 {
2688 /************************************************************
2689 * Resolve argument type names and then look them up by oid
2690 * in the system cache, and remember the required information
2691 * for input conversion.
2692 ************************************************************/
2693 for (i = 0; i < nargs; i++)
2694 {
2695 Oid typId,
2696 typInput,
2697 typIOParam;
2698 int32 typmod;
2699
2701 &typId, &typmod, NULL);
2702
2704
2705 qdesc->argtypes[i] = typId;
2706 fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
2707 qdesc->argtypioparams[i] = typIOParam;
2708 }
2709
2710 /************************************************************
2711 * Prepare the plan and check for errors
2712 ************************************************************/
2713 UTF_BEGIN;
2715 nargs, qdesc->argtypes);
2716 UTF_END;
2717
2718 if (qdesc->plan == NULL)
2719 elog(ERROR, "SPI_prepare() failed");
2720
2721 /************************************************************
2722 * Save the plan into permanent memory (right now it's in the
2723 * SPI procCxt, which will go away at function end).
2724 ************************************************************/
2725 if (SPI_keepplan(qdesc->plan))
2726 elog(ERROR, "SPI_keepplan() failed");
2727
2728 pltcl_subtrans_commit(oldcontext, oldowner);
2729 }
2730 PG_CATCH();
2731 {
2732 pltcl_subtrans_abort(interp, oldcontext, oldowner);
2733
2734 MemoryContextDelete(plan_cxt);
2735
2736 return TCL_ERROR;
2737 }
2738 PG_END_TRY();
2739
2740 /************************************************************
2741 * Insert a hashtable entry for the plan and return
2742 * the key to the caller
2743 ************************************************************/
2745
2746 hashent = Tcl_CreateHashEntry(query_hash, qdesc->qname, &hashnew);
2748
2749 /* qname is ASCII, so no need for encoding conversion */
2750 Tcl_SetObjResult(interp, Tcl_NewStringObj(qdesc->qname, -1));
2751 return TCL_OK;
2752}

References ALLOCSET_SMALL_SIZES, AllocSetContextCreate, CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, fb(), fmgr_info_cxt(), getTypeInputInfo(), i, pltcl_proc_desc::interp_desc, MemoryContextDelete(), MemoryContextSwitchTo(), palloc(), palloc0_object, parseTypeString(), PG_CATCH, PG_END_TRY, PG_TRY, pltcl_current_call_state, pltcl_subtrans_abort(), pltcl_subtrans_begin(), pltcl_subtrans_commit(), pltcl_call_state::prodesc, pltcl_interp_desc::query_hash, snprintf, SPI_keepplan(), SPI_prepare(), TopMemoryContext, UTF_BEGIN, UTF_END, and UTF_U2E.

Referenced by pltcl_init_interp().

◆ pltcl_subtrans_abort()

static void pltcl_subtrans_abort ( Tcl_Interp interp,
MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2380 of file pltcl.c.

2382{
2384
2385 /* Save error info */
2386 MemoryContextSwitchTo(oldcontext);
2387 edata = CopyErrorData();
2389
2390 /* Abort the inner transaction */
2392 MemoryContextSwitchTo(oldcontext);
2393 CurrentResourceOwner = oldowner;
2394
2395 /* Pass the error data to Tcl */
2397 UTF_BEGIN;
2398 Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2399 UTF_END;
2401}

References CopyErrorData(), CurrentResourceOwner, fb(), FlushErrorState(), FreeErrorData(), MemoryContextSwitchTo(), pltcl_construct_errorCode(), RollbackAndReleaseCurrentSubTransaction(), UTF_BEGIN, UTF_E2U, and UTF_END.

Referenced by pltcl_returnnext(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

◆ pltcl_subtrans_begin()

static void pltcl_subtrans_begin ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2362 of file pltcl.c.

2363{
2365
2366 /* Want to run inside function's memory context */
2367 MemoryContextSwitchTo(oldcontext);
2368}

References BeginInternalSubTransaction(), fb(), and MemoryContextSwitchTo().

Referenced by pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

◆ pltcl_subtrans_commit()

static void pltcl_subtrans_commit ( MemoryContext  oldcontext,
ResourceOwner  oldowner 
)
static

Definition at line 2371 of file pltcl.c.

2372{
2373 /* Commit the inner transaction, return to outer xact context */
2375 MemoryContextSwitchTo(oldcontext);
2376 CurrentResourceOwner = oldowner;
2377}

References CurrentResourceOwner, MemoryContextSwitchTo(), and ReleaseCurrentSubTransaction().

Referenced by pltcl_returnnext(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), and pltcl_SPI_prepare().

◆ pltcl_subtransaction()

static int pltcl_subtransaction ( ClientData  cdata,
Tcl_Interp interp,
int  objc,
Tcl_Obj *const  objv[] 
)
static

Definition at line 2975 of file pltcl.c.

2977{
2980 int retcode;
2981
2982 if (objc != 2)
2983 {
2984 Tcl_WrongNumArgs(interp, 1, objv, "command");
2985 return TCL_ERROR;
2986 }
2987
2988 /*
2989 * Note: we don't use pltcl_subtrans_begin and friends here because we
2990 * don't want the error handling in pltcl_subtrans_abort. But otherwise
2991 * the processing should be about the same as in those functions.
2992 */
2994 MemoryContextSwitchTo(oldcontext);
2995
2996 retcode = Tcl_EvalObjEx(interp, objv[1], 0);
2997
2998 if (retcode == TCL_ERROR)
2999 {
3000 /* Rollback the subtransaction */
3002 }
3003 else
3004 {
3005 /* Commit the subtransaction */
3007 }
3008
3009 /* In either case, restore previous memory context and resource owner */
3010 MemoryContextSwitchTo(oldcontext);
3011 CurrentResourceOwner = oldowner;
3012
3013 return retcode;
3014}

References BeginInternalSubTransaction(), CurrentMemoryContext, CurrentResourceOwner, fb(), MemoryContextSwitchTo(), ReleaseCurrentSubTransaction(), and RollbackAndReleaseCurrentSubTransaction().

Referenced by pltcl_init_interp().

◆ pltcl_trigger_handler()

static HeapTuple pltcl_trigger_handler ( PG_FUNCTION_ARGS  ,
pltcl_call_state call_state,
bool  pltrusted 
)
static

Definition at line 1059 of file pltcl.c.

1061{
1062 pltcl_proc_desc *prodesc;
1063 Tcl_Interp *volatile interp;
1064 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1065 char *stroid;
1066 TupleDesc tupdesc;
1067 volatile HeapTuple rettup;
1070 int tcl_rc;
1071 int i;
1072 const char *result;
1076
1077 call_state->trigdata = trigdata;
1078
1079 /* Connect to SPI manager */
1080 SPI_connect();
1081
1082 /* Make transition tables visible to this SPI connection */
1083 rc = SPI_register_trigger_data(trigdata);
1084 Assert(rc >= 0);
1085
1086 /* Find or compile the function */
1087 prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1088 RelationGetRelid(trigdata->tg_relation),
1089 false, /* not an event trigger */
1090 pltrusted);
1091
1092 call_state->prodesc = prodesc;
1093 prodesc->fn_refcount++;
1094
1095 interp = prodesc->interp_desc->interp;
1096
1097 tupdesc = RelationGetDescr(trigdata->tg_relation);
1098
1099 /************************************************************
1100 * Create the tcl command to call the internal
1101 * proc in the interpreter
1102 ************************************************************/
1103 tcl_cmd = Tcl_NewObj();
1105
1106 PG_TRY();
1107 {
1108 /* The procedure name (note this is all ASCII, so no utf_e2u) */
1110 Tcl_NewStringObj(prodesc->internal_proname, -1));
1111
1112 /* The trigger name for argument TG_name */
1114 Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgname), -1));
1115
1116 /* The oid of the trigger relation for argument TG_relid */
1117 /* Consider not converting to a string for more performance? */
1119 ObjectIdGetDatum(trigdata->tg_relation->rd_id)));
1122 pfree(stroid);
1123
1124 /* The name of the table the trigger is acting on: TG_table_name */
1125 stroid = SPI_getrelname(trigdata->tg_relation);
1128 pfree(stroid);
1129
1130 /* The schema of the table the trigger is acting on: TG_table_schema */
1131 stroid = SPI_getnspname(trigdata->tg_relation);
1134 pfree(stroid);
1135
1136 /* A list of attribute names for argument TG_relatts */
1139 for (i = 0; i < tupdesc->natts; i++)
1140 {
1142
1143 if (att->attisdropped)
1145 else
1147 Tcl_NewStringObj(utf_e2u(NameStr(att->attname)), -1));
1148 }
1150
1151 /* The when part of the event for TG_when */
1152 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
1154 Tcl_NewStringObj("BEFORE", -1));
1155 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
1157 Tcl_NewStringObj("AFTER", -1));
1158 else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
1160 Tcl_NewStringObj("INSTEAD OF", -1));
1161 else
1162 elog(ERROR, "unrecognized WHEN tg_event: %u", trigdata->tg_event);
1163
1164 /* The level part of the event for TG_level */
1165 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1166 {
1168 Tcl_NewStringObj("ROW", -1));
1169
1170 /*
1171 * Now the command part of the event for TG_op and data for NEW
1172 * and OLD
1173 *
1174 * Note: In BEFORE trigger, stored generated columns are not
1175 * computed yet, so don't make them accessible in NEW row.
1176 */
1177 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1178 {
1180 Tcl_NewStringObj("INSERT", -1));
1181
1183 pltcl_build_tuple_argument(trigdata->tg_trigtuple,
1184 tupdesc,
1185 !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
1187
1188 rettup = trigdata->tg_trigtuple;
1189 }
1190 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1191 {
1193 Tcl_NewStringObj("DELETE", -1));
1194
1197 pltcl_build_tuple_argument(trigdata->tg_trigtuple,
1198 tupdesc,
1199 true));
1200
1201 rettup = trigdata->tg_trigtuple;
1202 }
1203 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1204 {
1206 Tcl_NewStringObj("UPDATE", -1));
1207
1209 pltcl_build_tuple_argument(trigdata->tg_newtuple,
1210 tupdesc,
1211 !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
1213 pltcl_build_tuple_argument(trigdata->tg_trigtuple,
1214 tupdesc,
1215 true));
1216
1217 rettup = trigdata->tg_newtuple;
1218 }
1219 else
1220 elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
1221 }
1222 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
1223 {
1225 Tcl_NewStringObj("STATEMENT", -1));
1226
1227 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1229 Tcl_NewStringObj("INSERT", -1));
1230 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1232 Tcl_NewStringObj("DELETE", -1));
1233 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1235 Tcl_NewStringObj("UPDATE", -1));
1236 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
1238 Tcl_NewStringObj("TRUNCATE", -1));
1239 else
1240 elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
1241
1244
1245 rettup = (HeapTuple) NULL;
1246 }
1247 else
1248 elog(ERROR, "unrecognized LEVEL tg_event: %u", trigdata->tg_event);
1249
1250 /* Finally append the arguments from CREATE TRIGGER */
1251 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
1253 Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgargs[i]), -1));
1254 }
1255 PG_CATCH();
1256 {
1258 PG_RE_THROW();
1259 }
1260 PG_END_TRY();
1261
1262 /************************************************************
1263 * Call the Tcl function
1264 *
1265 * We assume no PG error can be thrown directly from this call.
1266 ************************************************************/
1268
1269 /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1271
1272 /************************************************************
1273 * Check for errors reported by Tcl.
1274 ************************************************************/
1275 if (tcl_rc != TCL_OK)
1276 throw_tcl_error(interp, prodesc->user_proname);
1277
1278 /************************************************************
1279 * Exit SPI environment.
1280 ************************************************************/
1281 if (SPI_finish() != SPI_OK_FINISH)
1282 elog(ERROR, "SPI_finish() failed");
1283
1284 /************************************************************
1285 * The return value from the procedure might be one of
1286 * the magic strings OK or SKIP, or a list from array get.
1287 * We can check for OK or SKIP without worrying about encoding.
1288 ************************************************************/
1289 result = Tcl_GetStringResult(interp);
1290
1291 if (strcmp(result, "OK") == 0)
1292 return rettup;
1293 if (strcmp(result, "SKIP") == 0)
1294 return (HeapTuple) NULL;
1295
1296 /************************************************************
1297 * Otherwise, the return value should be a column name/value list
1298 * specifying the modified tuple to return.
1299 ************************************************************/
1300 if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
1302 ereport(ERROR,
1304 errmsg("could not parse trigger return value: %s",
1305 utf_u2e(Tcl_GetStringResult(interp)))));
1306
1307 /* Convert function result to tuple */
1309 call_state);
1310
1311 return rettup;
1312}

References Assert, compile_pltcl_function(), DatumGetCString(), DirectFunctionCall1, elog, ereport, errcode(), errmsg(), ERROR, fb(), pltcl_proc_desc::fn_refcount, i, pltcl_proc_desc::internal_proname, pltcl_interp_desc::interp, pltcl_proc_desc::interp_desc, NameStr, TupleDescData::natts, ObjectIdGetDatum(), oidout(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PG_USED_FOR_ASSERTS_ONLY, pltcl_build_tuple_argument(), pltcl_build_tuple_result(), RelationData::rd_id, RelationGetDescr, RelationGetRelid, SPI_connect(), SPI_finish(), SPI_getnspname(), SPI_getrelname(), SPI_OK_FINISH, SPI_register_trigger_data(), TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, Trigger::tgargs, Trigger::tgname, Trigger::tgnargs, throw_tcl_error(), TRIGGER_FIRED_AFTER, TRIGGER_FIRED_BEFORE, TRIGGER_FIRED_BY_DELETE, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_TRUNCATE, TRIGGER_FIRED_BY_UPDATE, TRIGGER_FIRED_FOR_ROW, TRIGGER_FIRED_FOR_STATEMENT, TRIGGER_FIRED_INSTEAD, TupleDescAttr(), pltcl_proc_desc::user_proname, utf_e2u(), and utf_u2e().

Referenced by pltcl_handler().

◆ pltcl_WaitForEvent()

static int pltcl_WaitForEvent ( CONST86 Tcl_Time timePtr)
static

Definition at line 393 of file pltcl.c.

394{
395 return 0;
396}

Referenced by _PG_init().

◆ pltclu_call_handler()

Datum pltclu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 716 of file pltcl.c.

717{
718 return pltcl_handler(fcinfo, false);
719}

References pltcl_handler().

◆ start_proc_error_callback()

static void start_proc_error_callback ( void arg)
static

Definition at line 684 of file pltcl.c.

685{
686 const char *gucname = (const char *) arg;
687
688 /* translator: %s is "pltcl.start_proc" or "pltclu.start_proc" */
689 errcontext("processing %s parameter", gucname);
690}

References arg, and errcontext.

Referenced by call_pltcl_start_proc().

◆ throw_tcl_error()

static void throw_tcl_error ( Tcl_Interp interp,
const char proname 
)
static

Definition at line 1372 of file pltcl.c.

1373{
1374 /*
1375 * Caution is needed here because Tcl_GetVar could overwrite the
1376 * interpreter result (even though it's not really supposed to), and we
1377 * can't control the order of evaluation of ereport arguments. Hence, make
1378 * real sure we have our own copy of the result string before invoking
1379 * Tcl_GetVar.
1380 */
1381 char *emsg;
1382 char *econtext;
1383 int emsglen;
1384
1386 econtext = utf_u2e(Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY));
1387
1388 /*
1389 * Typically, the first line of errorInfo matches the primary error
1390 * message (the interpreter result); don't print that twice if so.
1391 */
1392 emsglen = strlen(emsg);
1393 if (strncmp(emsg, econtext, emsglen) == 0 &&
1394 econtext[emsglen] == '\n')
1395 econtext += emsglen + 1;
1396
1397 /* Tcl likes to prefix the next line with some spaces, too */
1398 while (*econtext == ' ')
1399 econtext++;
1400
1401 /* Note: proname will already contain quoting if any is needed */
1402 ereport(ERROR,
1404 errmsg("%s", emsg),
1405 errcontext("%s\nin PL/Tcl function %s",
1406 econtext, proname)));
1407}

References ereport, errcode(), errcontext, errmsg(), ERROR, fb(), proname, pstrdup(), and utf_u2e().

Referenced by pltcl_event_trigger_handler(), pltcl_func_handler(), and pltcl_trigger_handler().

◆ utf_e2u()

static char * utf_e2u ( const char src)
inlinestatic

Definition at line 87 of file pltcl.c.

88{
89 return pg_server_to_any(src, strlen(src), PG_UTF8);
90}

References fb(), pg_server_to_any(), and PG_UTF8.

Referenced by pltcl_event_trigger_handler(), and pltcl_trigger_handler().

◆ utf_u2e()

static char * utf_u2e ( const char src)
inlinestatic

Variable Documentation

◆ exception_name_map

const TclExceptionNameMap exception_name_map[]
static
Initial value:
= {
{NULL, 0}
}

Definition at line 264 of file pltcl.c.

264 {
265#include "pltclerrcodes.h"
266 {NULL, 0}
267};

Referenced by pltcl_get_condition_name().

◆ pltcl_current_call_state

◆ pltcl_hold_interp

Tcl_Interp* pltcl_hold_interp = NULL
static

Definition at line 248 of file pltcl.c.

Referenced by _PG_init(), and pltcl_init_interp().

◆ pltcl_interp_htab

HTAB* pltcl_interp_htab = NULL
static

Definition at line 249 of file pltcl.c.

Referenced by _PG_init(), and pltcl_fetch_interp().

◆ pltcl_pm_init_done

bool pltcl_pm_init_done = false
static

Definition at line 247 of file pltcl.c.

Referenced by _PG_init().

◆ pltcl_proc_htab

HTAB* pltcl_proc_htab = NULL
static

Definition at line 250 of file pltcl.c.

Referenced by _PG_init(), and compile_pltcl_function().

◆ pltcl_start_proc

char* pltcl_start_proc = NULL
static

Definition at line 245 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().

◆ pltclu_start_proc

char* pltclu_start_proc = NULL
static

Definition at line 246 of file pltcl.c.

Referenced by _PG_init(), and call_pltcl_start_proc().