Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * spi.c
4 : : * Server Programming Interface
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/executor/spi.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/htup_details.h"
18 : : #include "access/printtup.h"
19 : : #include "access/sysattr.h"
20 : : #include "access/xact.h"
21 : : #include "catalog/heap.h"
22 : : #include "catalog/pg_type.h"
23 : : #include "commands/trigger.h"
24 : : #include "executor/executor.h"
25 : : #include "executor/spi_priv.h"
26 : : #include "tcop/pquery.h"
27 : : #include "tcop/utility.h"
28 : : #include "utils/builtins.h"
29 : : #include "utils/datum.h"
30 : : #include "utils/lsyscache.h"
31 : : #include "utils/memutils.h"
32 : : #include "utils/rel.h"
33 : : #include "utils/snapmgr.h"
34 : : #include "utils/syscache.h"
35 : : #include "utils/tuplestore.h"
36 : : #include "utils/typcache.h"
37 : :
38 : :
39 : : /*
40 : : * These global variables are part of the API for various SPI functions
41 : : * (a horrible API choice, but it's too late now). To reduce the risk of
42 : : * interference between different SPI callers, we save and restore them
43 : : * when entering/exiting a SPI nesting level.
44 : : */
45 : : uint64 SPI_processed = 0;
46 : : SPITupleTable *SPI_tuptable = NULL;
47 : : int SPI_result = 0;
48 : :
49 : : static _SPI_connection *_SPI_stack = NULL;
50 : : static _SPI_connection *_SPI_current = NULL;
51 : : static int _SPI_stack_depth = 0; /* allocated size of _SPI_stack */
52 : : static int _SPI_connected = -1; /* current stack index */
53 : :
54 : : typedef struct SPICallbackArg
55 : : {
56 : : const char *query;
57 : : RawParseMode mode;
58 : : } SPICallbackArg;
59 : :
60 : : static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
61 : : ParamListInfo paramLI, bool read_only);
62 : :
63 : : static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan);
64 : :
65 : : static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan);
66 : :
67 : : static int _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
68 : : Snapshot snapshot, Snapshot crosscheck_snapshot,
69 : : bool fire_triggers);
70 : :
71 : : static ParamListInfo _SPI_convert_params(int nargs, const Oid *argtypes,
72 : : const Datum *Values, const char *Nulls);
73 : :
74 : : static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount);
75 : :
76 : : static void _SPI_error_callback(void *arg);
77 : :
78 : : static void _SPI_cursor_operation(Portal portal,
79 : : FetchDirection direction, long count,
80 : : DestReceiver *dest);
81 : :
82 : : static SPIPlanPtr _SPI_make_plan_non_temp(SPIPlanPtr plan);
83 : : static SPIPlanPtr _SPI_save_plan(SPIPlanPtr plan);
84 : :
85 : : static int _SPI_begin_call(bool use_exec);
86 : : static int _SPI_end_call(bool use_exec);
87 : : static MemoryContext _SPI_execmem(void);
88 : : static MemoryContext _SPI_procmem(void);
89 : : static bool _SPI_checktuples(void);
90 : :
91 : :
92 : : /* =================== interface functions =================== */
93 : :
94 : : int
95 : 9188 : SPI_connect(void)
96 : : {
97 : 9188 : return SPI_connect_ext(0);
98 : : }
99 : :
100 : : int
101 : 68295 : SPI_connect_ext(int options)
102 : : {
103 : : int newdepth;
104 : :
105 : : /* Enlarge stack if necessary */
106 [ + + ]: 68295 : if (_SPI_stack == NULL)
107 : : {
108 [ + - - + ]: 1111 : if (_SPI_connected != -1 || _SPI_stack_depth != 0)
109 [ # # ]: 0 : elog(ERROR, "SPI stack corrupted");
110 : 1111 : newdepth = 16;
111 : 1111 : _SPI_stack = (_SPI_connection *)
112 : 1111 : MemoryContextAlloc(TopMemoryContext,
113 : : newdepth * sizeof(_SPI_connection));
114 : 1111 : _SPI_stack_depth = newdepth;
115 : : }
116 : : else
117 : : {
118 [ + - - + ]: 67184 : if (_SPI_stack_depth <= 0 || _SPI_stack_depth <= _SPI_connected)
119 [ # # ]: 0 : elog(ERROR, "SPI stack corrupted");
120 [ + + ]: 67184 : if (_SPI_stack_depth == _SPI_connected + 1)
121 : : {
122 : 13 : newdepth = _SPI_stack_depth * 2;
123 : 13 : _SPI_stack = repalloc_array(_SPI_stack, _SPI_connection, newdepth);
124 : 13 : _SPI_stack_depth = newdepth;
125 : : }
126 : : }
127 : :
128 : : /* Enter new stack level */
129 : 68295 : _SPI_connected++;
130 : : Assert(_SPI_connected >= 0 && _SPI_connected < _SPI_stack_depth);
131 : :
132 : 68295 : _SPI_current = &(_SPI_stack[_SPI_connected]);
133 : 68295 : _SPI_current->processed = 0;
134 : 68295 : _SPI_current->tuptable = NULL;
135 : 68295 : _SPI_current->execSubid = InvalidSubTransactionId;
136 : 68295 : slist_init(&_SPI_current->tuptables);
137 : 68295 : _SPI_current->procCxt = NULL; /* in case we fail to create 'em */
138 : 68295 : _SPI_current->execCxt = NULL;
139 : 68295 : _SPI_current->connectSubid = GetCurrentSubTransactionId();
140 : 68295 : _SPI_current->queryEnv = NULL;
141 : 68295 : _SPI_current->atomic = (options & SPI_OPT_NONATOMIC ? false : true);
142 : 68295 : _SPI_current->internal_xact = false;
143 : 68295 : _SPI_current->outer_processed = SPI_processed;
144 : 68295 : _SPI_current->outer_tuptable = SPI_tuptable;
145 : 68295 : _SPI_current->outer_result = SPI_result;
146 : :
147 : : /*
148 : : * Create memory contexts for this procedure
149 : : *
150 : : * In atomic contexts (the normal case), we use TopTransactionContext,
151 : : * otherwise PortalContext, so that it lives across transaction
152 : : * boundaries.
153 : : *
154 : : * XXX It could be better to use PortalContext as the parent context in
155 : : * all cases, but we may not be inside a portal (consider deferred-trigger
156 : : * execution). Perhaps CurTransactionContext could be an option? For now
157 : : * it doesn't matter because we clean up explicitly in AtEOSubXact_SPI();
158 : : * but see also AtEOXact_SPI().
159 : : */
160 [ + + ]: 68295 : _SPI_current->procCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : PortalContext,
161 : : "SPI Proc",
162 : : ALLOCSET_DEFAULT_SIZES);
163 [ + + ]: 68295 : _SPI_current->execCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : _SPI_current->procCxt,
164 : : "SPI Exec",
165 : : ALLOCSET_DEFAULT_SIZES);
166 : : /* ... and switch to procedure's context */
167 : 68295 : _SPI_current->savedcxt = MemoryContextSwitchTo(_SPI_current->procCxt);
168 : :
169 : : /*
170 : : * Reset API global variables so that current caller cannot accidentally
171 : : * depend on state of an outer caller.
172 : : */
173 : 68295 : SPI_processed = 0;
174 : 68295 : SPI_tuptable = NULL;
175 : 68295 : SPI_result = 0;
176 : :
177 : 68295 : return SPI_OK_CONNECT;
178 : : }
179 : :
180 : : int
181 : 66721 : SPI_finish(void)
182 : : {
183 : : int res;
184 : :
185 : 66721 : res = _SPI_begin_call(false); /* just check we're connected */
186 [ - + ]: 66721 : if (res < 0)
187 : 0 : return res;
188 : :
189 : : /* Restore memory context as it was before procedure call */
190 : 66721 : MemoryContextSwitchTo(_SPI_current->savedcxt);
191 : :
192 : : /* Release memory used in procedure call (including tuptables) */
193 : 66721 : MemoryContextDelete(_SPI_current->execCxt);
194 : 66721 : _SPI_current->execCxt = NULL;
195 : 66721 : MemoryContextDelete(_SPI_current->procCxt);
196 : 66721 : _SPI_current->procCxt = NULL;
197 : :
198 : : /*
199 : : * Restore outer API variables, especially SPI_tuptable which is probably
200 : : * pointing at a just-deleted tuptable
201 : : */
202 : 66721 : SPI_processed = _SPI_current->outer_processed;
203 : 66721 : SPI_tuptable = _SPI_current->outer_tuptable;
204 : 66721 : SPI_result = _SPI_current->outer_result;
205 : :
206 : : /* Exit stack level */
207 : 66721 : _SPI_connected--;
208 [ + + ]: 66721 : if (_SPI_connected < 0)
209 : 56286 : _SPI_current = NULL;
210 : : else
211 : 10435 : _SPI_current = &(_SPI_stack[_SPI_connected]);
212 : :
213 : 66721 : return SPI_OK_FINISH;
214 : : }
215 : :
216 : : /*
217 : : * SPI_start_transaction is a no-op, kept for backwards compatibility.
218 : : * SPI callers are *always* inside a transaction.
219 : : */
220 : : void
221 : 0 : SPI_start_transaction(void)
222 : : {
223 : 0 : }
224 : :
225 : : static void
226 : 2144 : _SPI_commit(bool chain)
227 : : {
228 : 2144 : MemoryContext oldcontext = CurrentMemoryContext;
229 : : SavedTransactionCharacteristics savetc;
230 : :
231 : : /*
232 : : * Complain if we are in a context that doesn't permit transaction
233 : : * termination. (Note: here and _SPI_rollback should be the only places
234 : : * that throw ERRCODE_INVALID_TRANSACTION_TERMINATION, so that callers can
235 : : * test for that with security that they know what happened.)
236 : : */
237 [ + + ]: 2144 : if (_SPI_current->atomic)
238 [ + - ]: 16 : ereport(ERROR,
239 : : (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
240 : : errmsg("invalid transaction termination")));
241 : :
242 : : /*
243 : : * This restriction is required by PLs implemented on top of SPI. They
244 : : * use subtransactions to establish exception blocks that are supposed to
245 : : * be rolled back together if there is an error. Terminating the
246 : : * top-level transaction in such a block violates that idea. A future PL
247 : : * implementation might have different ideas about this, in which case
248 : : * this restriction would have to be refined or the check possibly be
249 : : * moved out of SPI into the PLs. Note however that the code below relies
250 : : * on not being within a subtransaction.
251 : : */
252 [ + + ]: 2128 : if (IsSubTransaction())
253 [ + - ]: 3 : ereport(ERROR,
254 : : (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
255 : : errmsg("cannot commit while a subtransaction is active")));
256 : :
257 [ + + ]: 2125 : if (chain)
258 : 2 : SaveTransactionCharacteristics(&savetc);
259 : :
260 : : /* Catch any error occurring during the COMMIT */
261 [ + + ]: 2125 : PG_TRY();
262 : : {
263 : : /* Protect current SPI stack entry against deletion */
264 : 2125 : _SPI_current->internal_xact = true;
265 : :
266 : : /*
267 : : * Hold any pinned portals that any PLs might be using. We have to do
268 : : * this before changing transaction state, since this will run
269 : : * user-defined code that might throw an error.
270 : : */
271 : 2125 : HoldPinnedPortals();
272 : :
273 : : /* Release snapshots associated with portals */
274 : 2124 : ForgetPortalSnapshots();
275 : :
276 : : /* Do the deed */
277 : 2124 : CommitTransactionCommand();
278 : :
279 : : /* Immediately start a new transaction */
280 : 2117 : StartTransactionCommand();
281 [ + + ]: 2117 : if (chain)
282 : 2 : RestoreTransactionCharacteristics(&savetc);
283 : :
284 : 2117 : MemoryContextSwitchTo(oldcontext);
285 : :
286 : 2117 : _SPI_current->internal_xact = false;
287 : : }
288 : 8 : PG_CATCH();
289 : : {
290 : : ErrorData *edata;
291 : :
292 : : /* Save error info in caller's context */
293 : 8 : MemoryContextSwitchTo(oldcontext);
294 : 8 : edata = CopyErrorData();
295 : 8 : FlushErrorState();
296 : :
297 : : /*
298 : : * Abort the failed transaction. If this fails too, we'll just
299 : : * propagate the error out ... there's not that much we can do.
300 : : */
301 : 8 : AbortCurrentTransaction();
302 : :
303 : : /* ... and start a new one */
304 : 8 : StartTransactionCommand();
305 [ - + ]: 8 : if (chain)
306 : 0 : RestoreTransactionCharacteristics(&savetc);
307 : :
308 : 8 : MemoryContextSwitchTo(oldcontext);
309 : :
310 : 8 : _SPI_current->internal_xact = false;
311 : :
312 : : /* Now that we've cleaned up the transaction, re-throw the error */
313 : 8 : ReThrowError(edata);
314 : : }
315 [ - + ]: 2117 : PG_END_TRY();
316 : 2117 : }
317 : :
318 : : void
319 : 2142 : SPI_commit(void)
320 : : {
321 : 2142 : _SPI_commit(false);
322 : 2115 : }
323 : :
324 : : void
325 : 2 : SPI_commit_and_chain(void)
326 : : {
327 : 2 : _SPI_commit(true);
328 : 2 : }
329 : :
330 : : static void
331 : 98 : _SPI_rollback(bool chain)
332 : : {
333 : 98 : MemoryContext oldcontext = CurrentMemoryContext;
334 : : SavedTransactionCharacteristics savetc;
335 : :
336 : : /* see comments in _SPI_commit() */
337 [ - + ]: 98 : if (_SPI_current->atomic)
338 [ # # ]: 0 : ereport(ERROR,
339 : : (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
340 : : errmsg("invalid transaction termination")));
341 : :
342 : : /* see comments in _SPI_commit() */
343 [ + + ]: 98 : if (IsSubTransaction())
344 [ + - ]: 2 : ereport(ERROR,
345 : : (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
346 : : errmsg("cannot roll back while a subtransaction is active")));
347 : :
348 [ + + ]: 96 : if (chain)
349 : 2 : SaveTransactionCharacteristics(&savetc);
350 : :
351 : : /* Catch any error occurring during the ROLLBACK */
352 [ + + ]: 96 : PG_TRY();
353 : : {
354 : : /* Protect current SPI stack entry against deletion */
355 : 96 : _SPI_current->internal_xact = true;
356 : :
357 : : /*
358 : : * Hold any pinned portals that any PLs might be using. We have to do
359 : : * this before changing transaction state, since this will run
360 : : * user-defined code that might throw an error, and in any case
361 : : * couldn't be run in an already-aborted transaction.
362 : : */
363 : 96 : HoldPinnedPortals();
364 : :
365 : : /* Release snapshots associated with portals */
366 : 94 : ForgetPortalSnapshots();
367 : :
368 : : /* Do the deed */
369 : 94 : AbortCurrentTransaction();
370 : :
371 : : /* Immediately start a new transaction */
372 : 94 : StartTransactionCommand();
373 [ + + ]: 94 : if (chain)
374 : 2 : RestoreTransactionCharacteristics(&savetc);
375 : :
376 : 94 : MemoryContextSwitchTo(oldcontext);
377 : :
378 : 94 : _SPI_current->internal_xact = false;
379 : : }
380 : 2 : PG_CATCH();
381 : : {
382 : : ErrorData *edata;
383 : :
384 : : /* Save error info in caller's context */
385 : 2 : MemoryContextSwitchTo(oldcontext);
386 : 2 : edata = CopyErrorData();
387 : 2 : FlushErrorState();
388 : :
389 : : /*
390 : : * Try again to abort the failed transaction. If this fails too,
391 : : * we'll just propagate the error out ... there's not that much we can
392 : : * do.
393 : : */
394 : 2 : AbortCurrentTransaction();
395 : :
396 : : /* ... and start a new one */
397 : 2 : StartTransactionCommand();
398 [ - + ]: 2 : if (chain)
399 : 0 : RestoreTransactionCharacteristics(&savetc);
400 : :
401 : 2 : MemoryContextSwitchTo(oldcontext);
402 : :
403 : 2 : _SPI_current->internal_xact = false;
404 : :
405 : : /* Now that we've cleaned up the transaction, re-throw the error */
406 : 2 : ReThrowError(edata);
407 : : }
408 [ - + ]: 94 : PG_END_TRY();
409 : 94 : }
410 : :
411 : : void
412 : 96 : SPI_rollback(void)
413 : : {
414 : 96 : _SPI_rollback(false);
415 : 92 : }
416 : :
417 : : void
418 : 2 : SPI_rollback_and_chain(void)
419 : : {
420 : 2 : _SPI_rollback(true);
421 : 2 : }
422 : :
423 : : /*
424 : : * Clean up SPI state at transaction commit or abort.
425 : : */
426 : : void
427 : 667234 : AtEOXact_SPI(bool isCommit)
428 : : {
429 : 667234 : bool found = false;
430 : :
431 : : /*
432 : : * Pop stack entries, stopping if we find one marked internal_xact (that
433 : : * one belongs to the caller of SPI_commit or SPI_rollback).
434 : : */
435 [ + + ]: 668669 : while (_SPI_connected >= 0)
436 : : {
437 : 3656 : _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
438 : :
439 [ + + ]: 3656 : if (connection->internal_xact)
440 : 2221 : break;
441 : :
442 : 1435 : found = true;
443 : :
444 : : /*
445 : : * We need not release the procedure's memory contexts explicitly, as
446 : : * they'll go away automatically when their parent context does; see
447 : : * notes in SPI_connect_ext.
448 : : */
449 : :
450 : : /*
451 : : * Restore outer global variables and pop the stack entry. Unlike
452 : : * SPI_finish(), we don't risk switching to memory contexts that might
453 : : * be already gone.
454 : : */
455 : 1435 : SPI_processed = connection->outer_processed;
456 : 1435 : SPI_tuptable = connection->outer_tuptable;
457 : 1435 : SPI_result = connection->outer_result;
458 : :
459 : 1435 : _SPI_connected--;
460 [ + + ]: 1435 : if (_SPI_connected < 0)
461 : 1403 : _SPI_current = NULL;
462 : : else
463 : 32 : _SPI_current = &(_SPI_stack[_SPI_connected]);
464 : : }
465 : :
466 : : /* We should only find entries to pop during an ABORT. */
467 [ + + - + ]: 667234 : if (found && isCommit)
468 [ # # ]: 0 : ereport(WARNING,
469 : : (errcode(ERRCODE_WARNING),
470 : : errmsg("transaction left non-empty SPI stack"),
471 : : errhint("Check for missing \"SPI_finish\" calls.")));
472 : 667234 : }
473 : :
474 : : /*
475 : : * Clean up SPI state at subtransaction commit or abort.
476 : : *
477 : : * During commit, there shouldn't be any unclosed entries remaining from
478 : : * the current subtransaction; we emit a warning if any are found.
479 : : */
480 : : void
481 : 12776 : AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
482 : : {
483 : 12776 : bool found = false;
484 : :
485 [ + + ]: 12915 : while (_SPI_connected >= 0)
486 : : {
487 : 10212 : _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
488 : :
489 [ + + ]: 10212 : if (connection->connectSubid != mySubid)
490 : 10073 : break; /* couldn't be any underneath it either */
491 : :
492 [ - + ]: 139 : if (connection->internal_xact)
493 : 0 : break;
494 : :
495 : 139 : found = true;
496 : :
497 : : /*
498 : : * Release procedure memory explicitly (see note in SPI_connect)
499 : : */
500 [ + - ]: 139 : if (connection->execCxt)
501 : : {
502 : 139 : MemoryContextDelete(connection->execCxt);
503 : 139 : connection->execCxt = NULL;
504 : : }
505 [ + - ]: 139 : if (connection->procCxt)
506 : : {
507 : 139 : MemoryContextDelete(connection->procCxt);
508 : 139 : connection->procCxt = NULL;
509 : : }
510 : :
511 : : /*
512 : : * Restore outer global variables and pop the stack entry. Unlike
513 : : * SPI_finish(), we don't risk switching to memory contexts that might
514 : : * be already gone.
515 : : */
516 : 139 : SPI_processed = connection->outer_processed;
517 : 139 : SPI_tuptable = connection->outer_tuptable;
518 : 139 : SPI_result = connection->outer_result;
519 : :
520 : 139 : _SPI_connected--;
521 [ + + ]: 139 : if (_SPI_connected < 0)
522 : 48 : _SPI_current = NULL;
523 : : else
524 : 91 : _SPI_current = &(_SPI_stack[_SPI_connected]);
525 : : }
526 : :
527 [ + + - + ]: 12776 : if (found && isCommit)
528 [ # # ]: 0 : ereport(WARNING,
529 : : (errcode(ERRCODE_WARNING),
530 : : errmsg("subtransaction left non-empty SPI stack"),
531 : : errhint("Check for missing \"SPI_finish\" calls.")));
532 : :
533 : : /*
534 : : * If we are aborting a subtransaction and there is an open SPI context
535 : : * surrounding the subxact, clean up to prevent memory leakage.
536 : : */
537 [ + + + + ]: 12776 : if (_SPI_current && !isCommit)
538 : : {
539 : : slist_mutable_iter siter;
540 : :
541 : : /*
542 : : * Throw away executor state if current executor operation was started
543 : : * within current subxact (essentially, force a _SPI_end_call(true)).
544 : : */
545 [ + + ]: 3680 : if (_SPI_current->execSubid >= mySubid)
546 : : {
547 : 3156 : _SPI_current->execSubid = InvalidSubTransactionId;
548 : 3156 : MemoryContextReset(_SPI_current->execCxt);
549 : : }
550 : :
551 : : /* throw away any tuple tables created within current subxact */
552 [ + + + + : 9242 : slist_foreach_modify(siter, &_SPI_current->tuptables)
+ + ]
553 : : {
554 : : SPITupleTable *tuptable;
555 : :
556 : 5562 : tuptable = slist_container(SPITupleTable, next, siter.cur);
557 [ + + ]: 5562 : if (tuptable->subid >= mySubid)
558 : : {
559 : : /*
560 : : * If we used SPI_freetuptable() here, its internal search of
561 : : * the tuptables list would make this operation O(N^2).
562 : : * Instead, just free the tuptable manually. This should
563 : : * match what SPI_freetuptable() does.
564 : : */
565 : 2986 : slist_delete_current(&siter);
566 [ + + ]: 2986 : if (tuptable == _SPI_current->tuptable)
567 : 2982 : _SPI_current->tuptable = NULL;
568 [ + + ]: 2986 : if (tuptable == SPI_tuptable)
569 : 4 : SPI_tuptable = NULL;
570 : 2986 : MemoryContextDelete(tuptable->tuptabcxt);
571 : : }
572 : : }
573 : : }
574 : 12776 : }
575 : :
576 : : /*
577 : : * Are we executing inside a procedure (that is, a nonatomic SPI context)?
578 : : */
579 : : bool
580 : 661216 : SPI_inside_nonatomic_context(void)
581 : : {
582 [ + + ]: 661216 : if (_SPI_current == NULL)
583 : 658995 : return false; /* not in any SPI context at all */
584 : : /* these tests must match _SPI_commit's opinion of what's atomic: */
585 [ - + ]: 2221 : if (_SPI_current->atomic)
586 : 0 : return false; /* it's atomic (ie function not procedure) */
587 [ - + ]: 2221 : if (IsSubTransaction())
588 : 0 : return false; /* if within subtransaction, it's atomic */
589 : 2221 : return true;
590 : : }
591 : :
592 : :
593 : : /* Parse, plan, and execute a query string */
594 : : int
595 : 858 : SPI_execute(const char *src, bool read_only, long tcount)
596 : : {
597 : : _SPI_plan plan;
598 : : SPIExecuteOptions options;
599 : : int res;
600 : :
601 [ + - - + ]: 858 : if (src == NULL || tcount < 0)
602 : 0 : return SPI_ERROR_ARGUMENT;
603 : :
604 : 858 : res = _SPI_begin_call(true);
605 [ - + ]: 858 : if (res < 0)
606 : 0 : return res;
607 : :
608 : 858 : memset(&plan, 0, sizeof(_SPI_plan));
609 : 858 : plan.magic = _SPI_PLAN_MAGIC;
610 : 858 : plan.parse_mode = RAW_PARSE_DEFAULT;
611 : 858 : plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
612 : :
613 : 858 : _SPI_prepare_oneshot_plan(src, &plan);
614 : :
615 : 850 : memset(&options, 0, sizeof(options));
616 : 850 : options.read_only = read_only;
617 : 850 : options.tcount = tcount;
618 : :
619 : 850 : res = _SPI_execute_plan(&plan, &options,
620 : : InvalidSnapshot, InvalidSnapshot,
621 : : true);
622 : :
623 : 823 : _SPI_end_call(true);
624 : 823 : return res;
625 : : }
626 : :
627 : : /* Obsolete version of SPI_execute */
628 : : int
629 : 325 : SPI_exec(const char *src, long tcount)
630 : : {
631 : 325 : return SPI_execute(src, false, tcount);
632 : : }
633 : :
634 : : /* Parse, plan, and execute a query string, with extensible options */
635 : : int
636 : 11324 : SPI_execute_extended(const char *src,
637 : : const SPIExecuteOptions *options)
638 : : {
639 : : int res;
640 : : _SPI_plan plan;
641 : :
642 [ + - - + ]: 11324 : if (src == NULL || options == NULL)
643 : 0 : return SPI_ERROR_ARGUMENT;
644 : :
645 : 11324 : res = _SPI_begin_call(true);
646 [ - + ]: 11324 : if (res < 0)
647 : 0 : return res;
648 : :
649 : 11324 : memset(&plan, 0, sizeof(_SPI_plan));
650 : 11324 : plan.magic = _SPI_PLAN_MAGIC;
651 : 11324 : plan.parse_mode = RAW_PARSE_DEFAULT;
652 : 11324 : plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
653 [ + + ]: 11324 : if (options->params)
654 : : {
655 : 289 : plan.parserSetup = options->params->parserSetup;
656 : 289 : plan.parserSetupArg = options->params->parserSetupArg;
657 : : }
658 : :
659 : 11324 : _SPI_prepare_oneshot_plan(src, &plan);
660 : :
661 : 11324 : res = _SPI_execute_plan(&plan, options,
662 : : InvalidSnapshot, InvalidSnapshot,
663 : : true);
664 : :
665 : 11165 : _SPI_end_call(true);
666 : 11165 : return res;
667 : : }
668 : :
669 : : /* Execute a previously prepared plan */
670 : : int
671 : 2647 : SPI_execute_plan(SPIPlanPtr plan, const Datum *Values, const char *Nulls,
672 : : bool read_only, long tcount)
673 : : {
674 : : SPIExecuteOptions options;
675 : : int res;
676 : :
677 [ + - + - : 2647 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
- + ]
678 : 0 : return SPI_ERROR_ARGUMENT;
679 : :
680 [ + + - + ]: 2647 : if (plan->nargs > 0 && Values == NULL)
681 : 0 : return SPI_ERROR_PARAM;
682 : :
683 : 2647 : res = _SPI_begin_call(true);
684 [ - + ]: 2647 : if (res < 0)
685 : 0 : return res;
686 : :
687 : 2647 : memset(&options, 0, sizeof(options));
688 : 2647 : options.params = _SPI_convert_params(plan->nargs, plan->argtypes,
689 : : Values, Nulls);
690 : 2647 : options.read_only = read_only;
691 : 2647 : options.tcount = tcount;
692 : :
693 : 2647 : res = _SPI_execute_plan(plan, &options,
694 : : InvalidSnapshot, InvalidSnapshot,
695 : : true);
696 : :
697 : 2647 : _SPI_end_call(true);
698 : 2647 : return res;
699 : : }
700 : :
701 : : /* Obsolete version of SPI_execute_plan */
702 : : int
703 : 0 : SPI_execp(SPIPlanPtr plan, const Datum *Values, const char *Nulls, long tcount)
704 : : {
705 : 0 : return SPI_execute_plan(plan, Values, Nulls, false, tcount);
706 : : }
707 : :
708 : : /* Execute a previously prepared plan */
709 : : int
710 : 1744 : SPI_execute_plan_extended(SPIPlanPtr plan,
711 : : const SPIExecuteOptions *options)
712 : : {
713 : : int res;
714 : :
715 [ + - + - : 1744 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || options == NULL)
- + ]
716 : 0 : return SPI_ERROR_ARGUMENT;
717 : :
718 : 1744 : res = _SPI_begin_call(true);
719 [ - + ]: 1744 : if (res < 0)
720 : 0 : return res;
721 : :
722 : 1744 : res = _SPI_execute_plan(plan, options,
723 : : InvalidSnapshot, InvalidSnapshot,
724 : : true);
725 : :
726 : 1738 : _SPI_end_call(true);
727 : 1738 : return res;
728 : : }
729 : :
730 : : /* Execute a previously prepared plan */
731 : : int
732 : 48948 : SPI_execute_plan_with_paramlist(SPIPlanPtr plan, ParamListInfo params,
733 : : bool read_only, long tcount)
734 : : {
735 : : SPIExecuteOptions options;
736 : : int res;
737 : :
738 [ + - + - : 48948 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
- + ]
739 : 0 : return SPI_ERROR_ARGUMENT;
740 : :
741 : 48948 : res = _SPI_begin_call(true);
742 [ - + ]: 48948 : if (res < 0)
743 : 0 : return res;
744 : :
745 : 48948 : memset(&options, 0, sizeof(options));
746 : 48948 : options.params = params;
747 : 48948 : options.read_only = read_only;
748 : 48948 : options.tcount = tcount;
749 : :
750 : 48948 : res = _SPI_execute_plan(plan, &options,
751 : : InvalidSnapshot, InvalidSnapshot,
752 : : true);
753 : :
754 : 45900 : _SPI_end_call(true);
755 : 45900 : return res;
756 : : }
757 : :
758 : : /*
759 : : * SPI_execute_snapshot -- identical to SPI_execute_plan, except that we allow
760 : : * the caller to specify exactly which snapshots to use, which will be
761 : : * registered here. Also, the caller may specify that AFTER triggers should be
762 : : * queued as part of the outer query rather than being fired immediately at the
763 : : * end of the command.
764 : : *
765 : : * This is currently not documented in spi.sgml because it is only intended
766 : : * for use by RI triggers.
767 : : *
768 : : * Passing snapshot == InvalidSnapshot will select the normal behavior of
769 : : * fetching a new snapshot for each query.
770 : : */
771 : : int
772 : 3315 : SPI_execute_snapshot(SPIPlanPtr plan,
773 : : const Datum *Values, const char *Nulls,
774 : : Snapshot snapshot, Snapshot crosscheck_snapshot,
775 : : bool read_only, bool fire_triggers, long tcount)
776 : : {
777 : : SPIExecuteOptions options;
778 : : int res;
779 : :
780 [ + - + - : 3315 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
- + ]
781 : 0 : return SPI_ERROR_ARGUMENT;
782 : :
783 [ + + - + ]: 3315 : if (plan->nargs > 0 && Values == NULL)
784 : 0 : return SPI_ERROR_PARAM;
785 : :
786 : 3315 : res = _SPI_begin_call(true);
787 [ - + ]: 3315 : if (res < 0)
788 : 0 : return res;
789 : :
790 : 3315 : memset(&options, 0, sizeof(options));
791 : 3315 : options.params = _SPI_convert_params(plan->nargs, plan->argtypes,
792 : : Values, Nulls);
793 : 3315 : options.read_only = read_only;
794 : 3315 : options.tcount = tcount;
795 : :
796 : 3315 : res = _SPI_execute_plan(plan, &options,
797 : : snapshot, crosscheck_snapshot,
798 : : fire_triggers);
799 : :
800 : 3305 : _SPI_end_call(true);
801 : 3305 : return res;
802 : : }
803 : :
804 : : /*
805 : : * SPI_execute_with_args -- plan and execute a query with supplied arguments
806 : : *
807 : : * This is functionally equivalent to SPI_prepare followed by
808 : : * SPI_execute_plan.
809 : : */
810 : : int
811 : 0 : SPI_execute_with_args(const char *src,
812 : : int nargs, const Oid *argtypes,
813 : : const Datum *Values, const char *Nulls,
814 : : bool read_only, long tcount)
815 : : {
816 : : int res;
817 : : _SPI_plan plan;
818 : : ParamListInfo paramLI;
819 : : SPIExecuteOptions options;
820 : :
821 [ # # # # : 0 : if (src == NULL || nargs < 0 || tcount < 0)
# # ]
822 : 0 : return SPI_ERROR_ARGUMENT;
823 : :
824 [ # # # # : 0 : if (nargs > 0 && (argtypes == NULL || Values == NULL))
# # ]
825 : 0 : return SPI_ERROR_PARAM;
826 : :
827 : 0 : res = _SPI_begin_call(true);
828 [ # # ]: 0 : if (res < 0)
829 : 0 : return res;
830 : :
831 : 0 : memset(&plan, 0, sizeof(_SPI_plan));
832 : 0 : plan.magic = _SPI_PLAN_MAGIC;
833 : 0 : plan.parse_mode = RAW_PARSE_DEFAULT;
834 : 0 : plan.cursor_options = CURSOR_OPT_PARALLEL_OK;
835 : 0 : plan.nargs = nargs;
836 : 0 : plan.argtypes = argtypes;
837 : 0 : plan.parserSetup = NULL;
838 : 0 : plan.parserSetupArg = NULL;
839 : :
840 : 0 : paramLI = _SPI_convert_params(nargs, argtypes,
841 : : Values, Nulls);
842 : :
843 : 0 : _SPI_prepare_oneshot_plan(src, &plan);
844 : :
845 : 0 : memset(&options, 0, sizeof(options));
846 : 0 : options.params = paramLI;
847 : 0 : options.read_only = read_only;
848 : 0 : options.tcount = tcount;
849 : :
850 : 0 : res = _SPI_execute_plan(&plan, &options,
851 : : InvalidSnapshot, InvalidSnapshot,
852 : : true);
853 : :
854 : 0 : _SPI_end_call(true);
855 : 0 : return res;
856 : : }
857 : :
858 : : SPIPlanPtr
859 : 2428 : SPI_prepare(const char *src, int nargs, const Oid *argtypes)
860 : : {
861 : 2428 : return SPI_prepare_cursor(src, nargs, argtypes, 0);
862 : : }
863 : :
864 : : SPIPlanPtr
865 : 2428 : SPI_prepare_cursor(const char *src, int nargs, const Oid *argtypes,
866 : : int cursorOptions)
867 : : {
868 : : _SPI_plan plan;
869 : : SPIPlanPtr result;
870 : :
871 [ + - + - : 2428 : if (src == NULL || nargs < 0 || (nargs > 0 && argtypes == NULL))
+ + - + ]
872 : : {
873 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
874 : 0 : return NULL;
875 : : }
876 : :
877 : 2428 : SPI_result = _SPI_begin_call(true);
878 [ - + ]: 2428 : if (SPI_result < 0)
879 : 0 : return NULL;
880 : :
881 : 2428 : memset(&plan, 0, sizeof(_SPI_plan));
882 : 2428 : plan.magic = _SPI_PLAN_MAGIC;
883 : 2428 : plan.parse_mode = RAW_PARSE_DEFAULT;
884 : 2428 : plan.cursor_options = cursorOptions;
885 : 2428 : plan.nargs = nargs;
886 : 2428 : plan.argtypes = argtypes;
887 : 2428 : plan.parserSetup = NULL;
888 : 2428 : plan.parserSetupArg = NULL;
889 : :
890 : 2428 : _SPI_prepare_plan(src, &plan);
891 : :
892 : : /* copy plan to procedure context */
893 : 2427 : result = _SPI_make_plan_non_temp(&plan);
894 : :
895 : 2427 : _SPI_end_call(true);
896 : :
897 : 2427 : return result;
898 : : }
899 : :
900 : : SPIPlanPtr
901 : 18286 : SPI_prepare_extended(const char *src,
902 : : const SPIPrepareOptions *options)
903 : : {
904 : : _SPI_plan plan;
905 : : SPIPlanPtr result;
906 : :
907 [ + - - + ]: 18286 : if (src == NULL || options == NULL)
908 : : {
909 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
910 : 0 : return NULL;
911 : : }
912 : :
913 : 18286 : SPI_result = _SPI_begin_call(true);
914 [ - + ]: 18286 : if (SPI_result < 0)
915 : 0 : return NULL;
916 : :
917 : 18286 : memset(&plan, 0, sizeof(_SPI_plan));
918 : 18286 : plan.magic = _SPI_PLAN_MAGIC;
919 : 18286 : plan.parse_mode = options->parseMode;
920 : 18286 : plan.cursor_options = options->cursorOptions;
921 : 18286 : plan.nargs = 0;
922 : 18286 : plan.argtypes = NULL;
923 : 18286 : plan.parserSetup = options->parserSetup;
924 : 18286 : plan.parserSetupArg = options->parserSetupArg;
925 : :
926 : 18286 : _SPI_prepare_plan(src, &plan);
927 : :
928 : : /* copy plan to procedure context */
929 : 18225 : result = _SPI_make_plan_non_temp(&plan);
930 : :
931 : 18225 : _SPI_end_call(true);
932 : :
933 : 18225 : return result;
934 : : }
935 : :
936 : : SPIPlanPtr
937 : 0 : SPI_prepare_params(const char *src,
938 : : ParserSetupHook parserSetup,
939 : : void *parserSetupArg,
940 : : int cursorOptions)
941 : : {
942 : : _SPI_plan plan;
943 : : SPIPlanPtr result;
944 : :
945 [ # # ]: 0 : if (src == NULL)
946 : : {
947 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
948 : 0 : return NULL;
949 : : }
950 : :
951 : 0 : SPI_result = _SPI_begin_call(true);
952 [ # # ]: 0 : if (SPI_result < 0)
953 : 0 : return NULL;
954 : :
955 : 0 : memset(&plan, 0, sizeof(_SPI_plan));
956 : 0 : plan.magic = _SPI_PLAN_MAGIC;
957 : 0 : plan.parse_mode = RAW_PARSE_DEFAULT;
958 : 0 : plan.cursor_options = cursorOptions;
959 : 0 : plan.nargs = 0;
960 : 0 : plan.argtypes = NULL;
961 : 0 : plan.parserSetup = parserSetup;
962 : 0 : plan.parserSetupArg = parserSetupArg;
963 : :
964 : 0 : _SPI_prepare_plan(src, &plan);
965 : :
966 : : /* copy plan to procedure context */
967 : 0 : result = _SPI_make_plan_non_temp(&plan);
968 : :
969 : 0 : _SPI_end_call(true);
970 : :
971 : 0 : return result;
972 : : }
973 : :
974 : : int
975 : 19625 : SPI_keepplan(SPIPlanPtr plan)
976 : : {
977 : : ListCell *lc;
978 : :
979 [ + - + - ]: 19625 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
980 [ + - - + ]: 19625 : plan->saved || plan->oneshot)
981 : 0 : return SPI_ERROR_ARGUMENT;
982 : :
983 : : /*
984 : : * Mark it saved, reparent it under CacheMemoryContext, and mark all the
985 : : * component CachedPlanSources as saved. This sequence cannot fail
986 : : * partway through, so there's no risk of long-term memory leakage.
987 : : */
988 : 19625 : plan->saved = true;
989 : 19625 : MemoryContextSetParent(plan->plancxt, CacheMemoryContext);
990 : :
991 [ + - + + : 39250 : foreach(lc, plan->plancache_list)
+ + ]
992 : : {
993 : 19625 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
994 : :
995 : 19625 : SaveCachedPlan(plansource);
996 : : }
997 : :
998 : 19625 : return 0;
999 : : }
1000 : :
1001 : : SPIPlanPtr
1002 : 0 : SPI_saveplan(SPIPlanPtr plan)
1003 : : {
1004 : : SPIPlanPtr newplan;
1005 : :
1006 [ # # # # ]: 0 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1007 : : {
1008 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1009 : 0 : return NULL;
1010 : : }
1011 : :
1012 : 0 : SPI_result = _SPI_begin_call(false); /* don't change context */
1013 [ # # ]: 0 : if (SPI_result < 0)
1014 : 0 : return NULL;
1015 : :
1016 : 0 : newplan = _SPI_save_plan(plan);
1017 : :
1018 : 0 : SPI_result = _SPI_end_call(false);
1019 : :
1020 : 0 : return newplan;
1021 : : }
1022 : :
1023 : : int
1024 : 4485 : SPI_freeplan(SPIPlanPtr plan)
1025 : : {
1026 : : ListCell *lc;
1027 : :
1028 [ + - - + ]: 4485 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1029 : 0 : return SPI_ERROR_ARGUMENT;
1030 : :
1031 : : /* Release the plancache entries */
1032 [ + - + + : 8970 : foreach(lc, plan->plancache_list)
+ + ]
1033 : : {
1034 : 4485 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
1035 : :
1036 : 4485 : DropCachedPlan(plansource);
1037 : : }
1038 : :
1039 : : /* Now get rid of the _SPI_plan and subsidiary data in its plancxt */
1040 : 4485 : MemoryContextDelete(plan->plancxt);
1041 : :
1042 : 4485 : return 0;
1043 : : }
1044 : :
1045 : : HeapTuple
1046 : 1384 : SPI_copytuple(HeapTuple tuple)
1047 : : {
1048 : : MemoryContext oldcxt;
1049 : : HeapTuple ctuple;
1050 : :
1051 [ - + ]: 1384 : if (tuple == NULL)
1052 : : {
1053 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1054 : 0 : return NULL;
1055 : : }
1056 : :
1057 [ - + ]: 1384 : if (_SPI_current == NULL)
1058 : : {
1059 : 0 : SPI_result = SPI_ERROR_UNCONNECTED;
1060 : 0 : return NULL;
1061 : : }
1062 : :
1063 : 1384 : oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
1064 : :
1065 : 1384 : ctuple = heap_copytuple(tuple);
1066 : :
1067 : 1384 : MemoryContextSwitchTo(oldcxt);
1068 : :
1069 : 1384 : return ctuple;
1070 : : }
1071 : :
1072 : : HeapTupleHeader
1073 : 3270 : SPI_returntuple(HeapTuple tuple, TupleDesc tupdesc)
1074 : : {
1075 : : MemoryContext oldcxt;
1076 : : HeapTupleHeader dtup;
1077 : :
1078 [ + - - + ]: 3270 : if (tuple == NULL || tupdesc == NULL)
1079 : : {
1080 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1081 : 0 : return NULL;
1082 : : }
1083 : :
1084 [ - + ]: 3270 : if (_SPI_current == NULL)
1085 : : {
1086 : 0 : SPI_result = SPI_ERROR_UNCONNECTED;
1087 : 0 : return NULL;
1088 : : }
1089 : :
1090 : : /* For RECORD results, make sure a typmod has been assigned */
1091 [ + + ]: 3270 : if (tupdesc->tdtypeid == RECORDOID &&
1092 [ - + ]: 3261 : tupdesc->tdtypmod < 0)
1093 : 0 : assign_record_type_typmod(tupdesc);
1094 : :
1095 : 3270 : oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
1096 : :
1097 : 3270 : dtup = DatumGetHeapTupleHeader(heap_copy_tuple_as_datum(tuple, tupdesc));
1098 : :
1099 : 3270 : MemoryContextSwitchTo(oldcxt);
1100 : :
1101 : 3270 : return dtup;
1102 : : }
1103 : :
1104 : : HeapTuple
1105 : 0 : SPI_modifytuple(Relation rel, HeapTuple tuple, int natts, const int *attnum,
1106 : : const Datum *Values, const char *Nulls)
1107 : : {
1108 : : MemoryContext oldcxt;
1109 : : HeapTuple mtuple;
1110 : : int numberOfAttributes;
1111 : : Datum *v;
1112 : : bool *n;
1113 : : int i;
1114 : :
1115 [ # # # # : 0 : if (rel == NULL || tuple == NULL || natts < 0 || attnum == NULL || Values == NULL)
# # # # #
# ]
1116 : : {
1117 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1118 : 0 : return NULL;
1119 : : }
1120 : :
1121 [ # # ]: 0 : if (_SPI_current == NULL)
1122 : : {
1123 : 0 : SPI_result = SPI_ERROR_UNCONNECTED;
1124 : 0 : return NULL;
1125 : : }
1126 : :
1127 : 0 : oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
1128 : :
1129 : 0 : SPI_result = 0;
1130 : :
1131 : 0 : numberOfAttributes = rel->rd_att->natts;
1132 : 0 : v = palloc_array(Datum, numberOfAttributes);
1133 : 0 : n = palloc_array(bool, numberOfAttributes);
1134 : :
1135 : : /* fetch old values and nulls */
1136 : 0 : heap_deform_tuple(tuple, rel->rd_att, v, n);
1137 : :
1138 : : /* replace values and nulls */
1139 [ # # ]: 0 : for (i = 0; i < natts; i++)
1140 : : {
1141 [ # # # # ]: 0 : if (attnum[i] <= 0 || attnum[i] > numberOfAttributes)
1142 : : break;
1143 : 0 : v[attnum[i] - 1] = Values[i];
1144 [ # # # # ]: 0 : n[attnum[i] - 1] = (Nulls && Nulls[i] == 'n');
1145 : : }
1146 : :
1147 [ # # ]: 0 : if (i == natts) /* no errors in *attnum */
1148 : : {
1149 : 0 : mtuple = heap_form_tuple(rel->rd_att, v, n);
1150 : :
1151 : : /*
1152 : : * copy the identification info of the old tuple: t_ctid, t_self, and
1153 : : * OID (if any)
1154 : : */
1155 : 0 : mtuple->t_data->t_ctid = tuple->t_data->t_ctid;
1156 : 0 : mtuple->t_self = tuple->t_self;
1157 : 0 : mtuple->t_tableOid = tuple->t_tableOid;
1158 : : }
1159 : : else
1160 : : {
1161 : 0 : mtuple = NULL;
1162 : 0 : SPI_result = SPI_ERROR_NOATTRIBUTE;
1163 : : }
1164 : :
1165 : 0 : pfree(v);
1166 : 0 : pfree(n);
1167 : :
1168 : 0 : MemoryContextSwitchTo(oldcxt);
1169 : :
1170 : 0 : return mtuple;
1171 : : }
1172 : :
1173 : : int
1174 : 13129 : SPI_fnumber(TupleDesc tupdesc, const char *fname)
1175 : : {
1176 : : int res;
1177 : : const FormData_pg_attribute *sysatt;
1178 : :
1179 [ + + ]: 71050 : for (res = 0; res < tupdesc->natts; res++)
1180 : : {
1181 : 71043 : Form_pg_attribute attr = TupleDescAttr(tupdesc, res);
1182 : :
1183 [ + + ]: 71043 : if (namestrcmp(&attr->attname, fname) == 0 &&
1184 [ + - ]: 13122 : !attr->attisdropped)
1185 : 13122 : return res + 1;
1186 : : }
1187 : :
1188 : 7 : sysatt = SystemAttributeByName(fname);
1189 [ - + ]: 7 : if (sysatt != NULL)
1190 : 0 : return sysatt->attnum;
1191 : :
1192 : : /* SPI_ERROR_NOATTRIBUTE is different from all sys column numbers */
1193 : 7 : return SPI_ERROR_NOATTRIBUTE;
1194 : : }
1195 : :
1196 : : char *
1197 : 644 : SPI_fname(TupleDesc tupdesc, int fnumber)
1198 : : {
1199 : : const FormData_pg_attribute *att;
1200 : :
1201 : 644 : SPI_result = 0;
1202 : :
1203 [ + - + - : 644 : if (fnumber > tupdesc->natts || fnumber == 0 ||
- + ]
1204 : : fnumber <= FirstLowInvalidHeapAttributeNumber)
1205 : : {
1206 : 0 : SPI_result = SPI_ERROR_NOATTRIBUTE;
1207 : 0 : return NULL;
1208 : : }
1209 : :
1210 [ + - ]: 644 : if (fnumber > 0)
1211 : 644 : att = TupleDescAttr(tupdesc, fnumber - 1);
1212 : : else
1213 : 0 : att = SystemAttributeDefinition(fnumber);
1214 : :
1215 : 644 : return pstrdup(NameStr(att->attname));
1216 : : }
1217 : :
1218 : : char *
1219 : 5617 : SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
1220 : : {
1221 : : Datum val;
1222 : : bool isnull;
1223 : : Oid typoid,
1224 : : foutoid;
1225 : : bool typisvarlena;
1226 : :
1227 : 5617 : SPI_result = 0;
1228 : :
1229 [ + - + - : 5617 : if (fnumber > tupdesc->natts || fnumber == 0 ||
- + ]
1230 : : fnumber <= FirstLowInvalidHeapAttributeNumber)
1231 : : {
1232 : 0 : SPI_result = SPI_ERROR_NOATTRIBUTE;
1233 : 0 : return NULL;
1234 : : }
1235 : :
1236 : 5617 : val = heap_getattr(tuple, fnumber, tupdesc, &isnull);
1237 [ + + ]: 5617 : if (isnull)
1238 : 66 : return NULL;
1239 : :
1240 [ + - ]: 5551 : if (fnumber > 0)
1241 : 5551 : typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1242 : : else
1243 : 0 : typoid = (SystemAttributeDefinition(fnumber))->atttypid;
1244 : :
1245 : 5551 : getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
1246 : :
1247 : 5551 : return OidOutputFunctionCall(foutoid, val);
1248 : : }
1249 : :
1250 : : Datum
1251 : 33876 : SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
1252 : : {
1253 : 33876 : SPI_result = 0;
1254 : :
1255 [ + - + - : 33876 : if (fnumber > tupdesc->natts || fnumber == 0 ||
- + ]
1256 : : fnumber <= FirstLowInvalidHeapAttributeNumber)
1257 : : {
1258 : 0 : SPI_result = SPI_ERROR_NOATTRIBUTE;
1259 : 0 : *isnull = true;
1260 : 0 : return (Datum) 0;
1261 : : }
1262 : :
1263 : 33876 : return heap_getattr(tuple, fnumber, tupdesc, isnull);
1264 : : }
1265 : :
1266 : : char *
1267 : 0 : SPI_gettype(TupleDesc tupdesc, int fnumber)
1268 : : {
1269 : : Oid typoid;
1270 : : HeapTuple typeTuple;
1271 : : char *result;
1272 : :
1273 : 0 : SPI_result = 0;
1274 : :
1275 [ # # # # : 0 : if (fnumber > tupdesc->natts || fnumber == 0 ||
# # ]
1276 : : fnumber <= FirstLowInvalidHeapAttributeNumber)
1277 : : {
1278 : 0 : SPI_result = SPI_ERROR_NOATTRIBUTE;
1279 : 0 : return NULL;
1280 : : }
1281 : :
1282 [ # # ]: 0 : if (fnumber > 0)
1283 : 0 : typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1284 : : else
1285 : 0 : typoid = (SystemAttributeDefinition(fnumber))->atttypid;
1286 : :
1287 : 0 : typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid));
1288 : :
1289 [ # # ]: 0 : if (!HeapTupleIsValid(typeTuple))
1290 : : {
1291 : 0 : SPI_result = SPI_ERROR_TYPUNKNOWN;
1292 : 0 : return NULL;
1293 : : }
1294 : :
1295 : 0 : result = pstrdup(NameStr(((Form_pg_type) GETSTRUCT(typeTuple))->typname));
1296 : 0 : ReleaseSysCache(typeTuple);
1297 : 0 : return result;
1298 : : }
1299 : :
1300 : : /*
1301 : : * Get the data type OID for a column.
1302 : : *
1303 : : * There's nothing similar for typmod and typcollation. The rare consumers
1304 : : * thereof should inspect the TupleDesc directly.
1305 : : */
1306 : : Oid
1307 : 782 : SPI_gettypeid(TupleDesc tupdesc, int fnumber)
1308 : : {
1309 : 782 : SPI_result = 0;
1310 : :
1311 [ + - + - : 782 : if (fnumber > tupdesc->natts || fnumber == 0 ||
- + ]
1312 : : fnumber <= FirstLowInvalidHeapAttributeNumber)
1313 : : {
1314 : 0 : SPI_result = SPI_ERROR_NOATTRIBUTE;
1315 : 0 : return InvalidOid;
1316 : : }
1317 : :
1318 [ + - ]: 782 : if (fnumber > 0)
1319 : 782 : return TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1320 : : else
1321 : 0 : return (SystemAttributeDefinition(fnumber))->atttypid;
1322 : : }
1323 : :
1324 : : char *
1325 : 185 : SPI_getrelname(Relation rel)
1326 : : {
1327 : 185 : return pstrdup(RelationGetRelationName(rel));
1328 : : }
1329 : :
1330 : : char *
1331 : 142 : SPI_getnspname(Relation rel)
1332 : : {
1333 : 142 : return get_namespace_name(RelationGetNamespace(rel));
1334 : : }
1335 : :
1336 : : void *
1337 : 24 : SPI_palloc(Size size)
1338 : : {
1339 [ - + ]: 24 : if (_SPI_current == NULL)
1340 [ # # ]: 0 : elog(ERROR, "SPI_palloc called while not connected to SPI");
1341 : :
1342 : 24 : return MemoryContextAlloc(_SPI_current->savedcxt, size);
1343 : : }
1344 : :
1345 : : void *
1346 : 0 : SPI_repalloc(void *pointer, Size size)
1347 : : {
1348 : : /* No longer need to worry which context chunk was in... */
1349 : 0 : return repalloc(pointer, size);
1350 : : }
1351 : :
1352 : : void
1353 : 0 : SPI_pfree(void *pointer)
1354 : : {
1355 : : /* No longer need to worry which context chunk was in... */
1356 : 0 : pfree(pointer);
1357 : 0 : }
1358 : :
1359 : : Datum
1360 : 3738 : SPI_datumTransfer(Datum value, bool typByVal, int typLen)
1361 : : {
1362 : : MemoryContext oldcxt;
1363 : : Datum result;
1364 : :
1365 [ - + ]: 3738 : if (_SPI_current == NULL)
1366 [ # # ]: 0 : elog(ERROR, "SPI_datumTransfer called while not connected to SPI");
1367 : :
1368 : 3738 : oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
1369 : :
1370 : 3738 : result = datumTransfer(value, typByVal, typLen);
1371 : :
1372 : 3738 : MemoryContextSwitchTo(oldcxt);
1373 : :
1374 : 3738 : return result;
1375 : : }
1376 : :
1377 : : void
1378 : 0 : SPI_freetuple(HeapTuple tuple)
1379 : : {
1380 : : /* No longer need to worry which context tuple was in... */
1381 : 0 : heap_freetuple(tuple);
1382 : 0 : }
1383 : :
1384 : : void
1385 : 121359 : SPI_freetuptable(SPITupleTable *tuptable)
1386 : : {
1387 : 121359 : bool found = false;
1388 : :
1389 : : /* ignore call if NULL pointer */
1390 [ + + ]: 121359 : if (tuptable == NULL)
1391 : 69556 : return;
1392 : :
1393 : : /*
1394 : : * Search only the topmost SPI context for a matching tuple table.
1395 : : */
1396 [ + - ]: 51803 : if (_SPI_current != NULL)
1397 : : {
1398 : : slist_mutable_iter siter;
1399 : :
1400 : : /* find tuptable in active list, then remove it */
1401 [ + - + - : 51805 : slist_foreach_modify(siter, &_SPI_current->tuptables)
+ - ]
1402 : : {
1403 : : SPITupleTable *tt;
1404 : :
1405 : 51805 : tt = slist_container(SPITupleTable, next, siter.cur);
1406 [ + + ]: 51805 : if (tt == tuptable)
1407 : : {
1408 : 51803 : slist_delete_current(&siter);
1409 : 51803 : found = true;
1410 : 51803 : break;
1411 : : }
1412 : : }
1413 : : }
1414 : :
1415 : : /*
1416 : : * Refuse the deletion if we didn't find it in the topmost SPI context.
1417 : : * This is primarily a guard against double deletion, but might prevent
1418 : : * other errors as well. Since the worst consequence of not deleting a
1419 : : * tuptable would be a transient memory leak, this is just a WARNING.
1420 : : */
1421 [ - + ]: 51803 : if (!found)
1422 : : {
1423 [ # # ]: 0 : elog(WARNING, "attempt to delete invalid SPITupleTable %p", tuptable);
1424 : 0 : return;
1425 : : }
1426 : :
1427 : : /* for safety, reset global variables that might point at tuptable */
1428 [ - + ]: 51803 : if (tuptable == _SPI_current->tuptable)
1429 : 0 : _SPI_current->tuptable = NULL;
1430 [ + + ]: 51803 : if (tuptable == SPI_tuptable)
1431 : 46534 : SPI_tuptable = NULL;
1432 : :
1433 : : /* release all memory belonging to tuptable */
1434 : 51803 : MemoryContextDelete(tuptable->tuptabcxt);
1435 : : }
1436 : :
1437 : :
1438 : : /*
1439 : : * SPI_cursor_open()
1440 : : *
1441 : : * Open a prepared SPI plan as a portal
1442 : : */
1443 : : Portal
1444 : 133 : SPI_cursor_open(const char *name, SPIPlanPtr plan,
1445 : : const Datum *Values, const char *Nulls,
1446 : : bool read_only)
1447 : : {
1448 : : Portal portal;
1449 : : ParamListInfo paramLI;
1450 : :
1451 : : /* build transient ParamListInfo in caller's context */
1452 : 133 : paramLI = _SPI_convert_params(plan->nargs, plan->argtypes,
1453 : : Values, Nulls);
1454 : :
1455 : 133 : portal = SPI_cursor_open_internal(name, plan, paramLI, read_only);
1456 : :
1457 : : /* done with the transient ParamListInfo */
1458 [ + + ]: 133 : if (paramLI)
1459 : 4 : pfree(paramLI);
1460 : :
1461 : 133 : return portal;
1462 : : }
1463 : :
1464 : :
1465 : : /*
1466 : : * SPI_cursor_open_with_args()
1467 : : *
1468 : : * Parse and plan a query and open it as a portal.
1469 : : */
1470 : : Portal
1471 : 0 : SPI_cursor_open_with_args(const char *name,
1472 : : const char *src,
1473 : : int nargs, const Oid *argtypes,
1474 : : const Datum *Values, const char *Nulls,
1475 : : bool read_only, int cursorOptions)
1476 : : {
1477 : : Portal result;
1478 : : _SPI_plan plan;
1479 : : ParamListInfo paramLI;
1480 : :
1481 [ # # # # ]: 0 : if (src == NULL || nargs < 0)
1482 [ # # ]: 0 : elog(ERROR, "SPI_cursor_open_with_args called with invalid arguments");
1483 : :
1484 [ # # # # : 0 : if (nargs > 0 && (argtypes == NULL || Values == NULL))
# # ]
1485 [ # # ]: 0 : elog(ERROR, "SPI_cursor_open_with_args called with missing parameters");
1486 : :
1487 : 0 : SPI_result = _SPI_begin_call(true);
1488 [ # # ]: 0 : if (SPI_result < 0)
1489 [ # # ]: 0 : elog(ERROR, "SPI_cursor_open_with_args called while not connected");
1490 : :
1491 : 0 : memset(&plan, 0, sizeof(_SPI_plan));
1492 : 0 : plan.magic = _SPI_PLAN_MAGIC;
1493 : 0 : plan.parse_mode = RAW_PARSE_DEFAULT;
1494 : 0 : plan.cursor_options = cursorOptions;
1495 : 0 : plan.nargs = nargs;
1496 : 0 : plan.argtypes = argtypes;
1497 : 0 : plan.parserSetup = NULL;
1498 : 0 : plan.parserSetupArg = NULL;
1499 : :
1500 : : /* build transient ParamListInfo in executor context */
1501 : 0 : paramLI = _SPI_convert_params(nargs, argtypes,
1502 : : Values, Nulls);
1503 : :
1504 : 0 : _SPI_prepare_plan(src, &plan);
1505 : :
1506 : : /* We needn't copy the plan; SPI_cursor_open_internal will do so */
1507 : :
1508 : 0 : result = SPI_cursor_open_internal(name, &plan, paramLI, read_only);
1509 : :
1510 : : /* And clean up */
1511 : 0 : _SPI_end_call(true);
1512 : :
1513 : 0 : return result;
1514 : : }
1515 : :
1516 : :
1517 : : /*
1518 : : * SPI_cursor_open_with_paramlist()
1519 : : *
1520 : : * Same as SPI_cursor_open except that parameters (if any) are passed
1521 : : * as a ParamListInfo, which supports dynamic parameter set determination
1522 : : */
1523 : : Portal
1524 : 1784 : SPI_cursor_open_with_paramlist(const char *name, SPIPlanPtr plan,
1525 : : ParamListInfo params, bool read_only)
1526 : : {
1527 : 1784 : return SPI_cursor_open_internal(name, plan, params, read_only);
1528 : : }
1529 : :
1530 : : /* Parse a query and open it as a cursor */
1531 : : Portal
1532 : 6402 : SPI_cursor_parse_open(const char *name,
1533 : : const char *src,
1534 : : const SPIParseOpenOptions *options)
1535 : : {
1536 : : Portal result;
1537 : : _SPI_plan plan;
1538 : :
1539 [ + - - + ]: 6402 : if (src == NULL || options == NULL)
1540 [ # # ]: 0 : elog(ERROR, "SPI_cursor_parse_open called with invalid arguments");
1541 : :
1542 : 6402 : SPI_result = _SPI_begin_call(true);
1543 [ - + ]: 6402 : if (SPI_result < 0)
1544 [ # # ]: 0 : elog(ERROR, "SPI_cursor_parse_open called while not connected");
1545 : :
1546 : 6402 : memset(&plan, 0, sizeof(_SPI_plan));
1547 : 6402 : plan.magic = _SPI_PLAN_MAGIC;
1548 : 6402 : plan.parse_mode = RAW_PARSE_DEFAULT;
1549 : 6402 : plan.cursor_options = options->cursorOptions;
1550 [ + + ]: 6402 : if (options->params)
1551 : : {
1552 : 8 : plan.parserSetup = options->params->parserSetup;
1553 : 8 : plan.parserSetupArg = options->params->parserSetupArg;
1554 : : }
1555 : :
1556 : 6402 : _SPI_prepare_plan(src, &plan);
1557 : :
1558 : : /* We needn't copy the plan; SPI_cursor_open_internal will do so */
1559 : :
1560 : 6402 : result = SPI_cursor_open_internal(name, &plan,
1561 : 6402 : options->params, options->read_only);
1562 : :
1563 : : /* And clean up */
1564 : 6402 : _SPI_end_call(true);
1565 : :
1566 : 6402 : return result;
1567 : : }
1568 : :
1569 : :
1570 : : /*
1571 : : * SPI_cursor_open_internal()
1572 : : *
1573 : : * Common code for SPI_cursor_open variants
1574 : : */
1575 : : static Portal
1576 : 8319 : SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
1577 : : ParamListInfo paramLI, bool read_only)
1578 : : {
1579 : : CachedPlanSource *plansource;
1580 : : CachedPlan *cplan;
1581 : : List *stmt_list;
1582 : : char *query_string;
1583 : : Snapshot snapshot;
1584 : : MemoryContext oldcontext;
1585 : : Portal portal;
1586 : : SPICallbackArg spicallbackarg;
1587 : : ErrorContextCallback spierrcontext;
1588 : :
1589 : : /*
1590 : : * Check that the plan is something the Portal code will special-case as
1591 : : * returning one tupleset.
1592 : : */
1593 [ - + ]: 8319 : if (!SPI_is_cursor_plan(plan))
1594 : : {
1595 : : /* try to give a good error message */
1596 : : const char *cmdtag;
1597 : :
1598 [ # # ]: 0 : if (list_length(plan->plancache_list) != 1)
1599 [ # # ]: 0 : ereport(ERROR,
1600 : : (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1601 : : errmsg("cannot open multi-query plan as cursor")));
1602 : 0 : plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1603 : : /* A SELECT that fails SPI_is_cursor_plan() must be SELECT INTO */
1604 [ # # ]: 0 : if (plansource->commandTag == CMDTAG_SELECT)
1605 : 0 : cmdtag = "SELECT INTO";
1606 : : else
1607 : 0 : cmdtag = GetCommandTagName(plansource->commandTag);
1608 [ # # ]: 0 : ereport(ERROR,
1609 : : (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1610 : : /* translator: %s is name of a SQL command, eg INSERT */
1611 : : errmsg("cannot open %s query as cursor", cmdtag)));
1612 : : }
1613 : :
1614 : : Assert(list_length(plan->plancache_list) == 1);
1615 : 8319 : plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1616 : :
1617 : : /* Push the SPI stack */
1618 [ - + ]: 8319 : if (_SPI_begin_call(true) < 0)
1619 [ # # ]: 0 : elog(ERROR, "SPI_cursor_open called while not connected");
1620 : :
1621 : : /* Reset SPI result (note we deliberately don't touch lastoid) */
1622 : 8319 : SPI_processed = 0;
1623 : 8319 : SPI_tuptable = NULL;
1624 : 8319 : _SPI_current->processed = 0;
1625 : 8319 : _SPI_current->tuptable = NULL;
1626 : :
1627 : : /* Create the portal */
1628 [ + + - + ]: 8319 : if (name == NULL || name[0] == '\0')
1629 : : {
1630 : : /* Use a random nonconflicting name */
1631 : 8287 : portal = CreateNewPortal();
1632 : : }
1633 : : else
1634 : : {
1635 : : /* In this path, error if portal of same name already exists */
1636 : 32 : portal = CreatePortal(name, false, false);
1637 : : }
1638 : :
1639 : : /* Copy the plan's query string into the portal */
1640 : 8319 : query_string = MemoryContextStrdup(portal->portalContext,
1641 : : plansource->query_string);
1642 : :
1643 : : /*
1644 : : * Setup error traceback support for ereport(), in case GetCachedPlan
1645 : : * throws an error.
1646 : : */
1647 : 8319 : spicallbackarg.query = plansource->query_string;
1648 : 8319 : spicallbackarg.mode = plan->parse_mode;
1649 : 8319 : spierrcontext.callback = _SPI_error_callback;
1650 : 8319 : spierrcontext.arg = &spicallbackarg;
1651 : 8319 : spierrcontext.previous = error_context_stack;
1652 : 8319 : error_context_stack = &spierrcontext;
1653 : :
1654 : : /*
1655 : : * Note: for a saved plan, we mustn't have any failure occur between
1656 : : * GetCachedPlan and PortalDefineQuery; that would result in leaking our
1657 : : * plancache refcount.
1658 : : */
1659 : :
1660 : : /* Replan if needed, and increment plan refcount for portal */
1661 : 8319 : cplan = GetCachedPlan(plansource, paramLI, NULL, _SPI_current->queryEnv);
1662 : 8319 : stmt_list = cplan->stmt_list;
1663 : :
1664 [ + + ]: 8319 : if (!plan->saved)
1665 : : {
1666 : : /*
1667 : : * We don't want the portal to depend on an unsaved CachedPlanSource,
1668 : : * so must copy the plan into the portal's context. An error here
1669 : : * will result in leaking our refcount on the plan, but it doesn't
1670 : : * matter because the plan is unsaved and hence transient anyway.
1671 : : */
1672 : 6529 : oldcontext = MemoryContextSwitchTo(portal->portalContext);
1673 : 6529 : stmt_list = copyObject(stmt_list);
1674 : 6529 : MemoryContextSwitchTo(oldcontext);
1675 : 6529 : ReleaseCachedPlan(cplan, NULL);
1676 : 6529 : cplan = NULL; /* portal shouldn't depend on cplan */
1677 : : }
1678 : :
1679 : : /*
1680 : : * Set up the portal.
1681 : : */
1682 : 8319 : PortalDefineQuery(portal,
1683 : : NULL, /* no statement name */
1684 : : query_string,
1685 : : plansource->commandTag,
1686 : : stmt_list,
1687 : : cplan);
1688 : :
1689 : : /*
1690 : : * Set up options for portal. Default SCROLL type is chosen the same way
1691 : : * as PerformCursorOpen does it.
1692 : : */
1693 : 8319 : portal->cursorOptions = plan->cursor_options;
1694 [ + + ]: 8319 : if (!(portal->cursorOptions & (CURSOR_OPT_SCROLL | CURSOR_OPT_NO_SCROLL)))
1695 : : {
1696 [ + - ]: 270 : if (list_length(stmt_list) == 1 &&
1697 [ + - ]: 270 : linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1698 [ + + + + ]: 539 : linitial_node(PlannedStmt, stmt_list)->rowMarks == NIL &&
1699 : 269 : ExecSupportsBackwardScan(linitial_node(PlannedStmt, stmt_list)->planTree))
1700 : 252 : portal->cursorOptions |= CURSOR_OPT_SCROLL;
1701 : : else
1702 : 18 : portal->cursorOptions |= CURSOR_OPT_NO_SCROLL;
1703 : : }
1704 : :
1705 : : /*
1706 : : * Disallow SCROLL with SELECT FOR UPDATE. This is not redundant with the
1707 : : * check in transformDeclareCursorStmt because the cursor options might
1708 : : * not have come through there.
1709 : : */
1710 [ + + ]: 8319 : if (portal->cursorOptions & CURSOR_OPT_SCROLL)
1711 : : {
1712 [ + - ]: 269 : if (list_length(stmt_list) == 1 &&
1713 [ + - ]: 269 : linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1714 [ - + ]: 269 : linitial_node(PlannedStmt, stmt_list)->rowMarks != NIL)
1715 [ # # ]: 0 : ereport(ERROR,
1716 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1717 : : errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1718 : : errdetail("Scrollable cursors must be READ ONLY.")));
1719 : : }
1720 : :
1721 : : /* Make current query environment available to portal at execution time. */
1722 : 8319 : portal->queryEnv = _SPI_current->queryEnv;
1723 : :
1724 : : /*
1725 : : * If told to be read-only, we'd better check for read-only queries. This
1726 : : * can't be done earlier because we need to look at the finished, planned
1727 : : * queries. (In particular, we don't want to do it between GetCachedPlan
1728 : : * and PortalDefineQuery, because throwing an error between those steps
1729 : : * would result in leaking our plancache refcount.)
1730 : : */
1731 [ + + ]: 8319 : if (read_only)
1732 : : {
1733 : : ListCell *lc;
1734 : :
1735 [ + - + + : 208 : foreach(lc, stmt_list)
+ + ]
1736 : : {
1737 : 104 : PlannedStmt *pstmt = lfirst_node(PlannedStmt, lc);
1738 : :
1739 [ - + ]: 104 : if (!CommandIsReadOnly(pstmt))
1740 [ # # ]: 0 : ereport(ERROR,
1741 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1742 : : /* translator: %s is a SQL statement name */
1743 : : errmsg("%s is not allowed in a non-volatile function",
1744 : : CreateCommandName((Node *) pstmt))));
1745 : : }
1746 : : }
1747 : :
1748 : : /* Set up the snapshot to use. */
1749 [ + + ]: 8319 : if (read_only)
1750 : 104 : snapshot = GetActiveSnapshot();
1751 : : else
1752 : : {
1753 : 8215 : CommandCounterIncrement();
1754 : 8215 : snapshot = GetTransactionSnapshot();
1755 : : }
1756 : :
1757 : : /*
1758 : : * If the plan has parameters, copy them into the portal. Note that this
1759 : : * must be done after revalidating the plan, because in dynamic parameter
1760 : : * cases the set of parameters could have changed during re-parsing.
1761 : : */
1762 [ + + ]: 8319 : if (paramLI)
1763 : : {
1764 : 451 : oldcontext = MemoryContextSwitchTo(portal->portalContext);
1765 : 451 : paramLI = copyParamList(paramLI);
1766 : 451 : MemoryContextSwitchTo(oldcontext);
1767 : : }
1768 : :
1769 : : /*
1770 : : * Start portal execution.
1771 : : */
1772 : 8319 : PortalStart(portal, paramLI, 0, snapshot);
1773 : :
1774 : : Assert(portal->strategy != PORTAL_MULTI_QUERY);
1775 : :
1776 : : /* Pop the error context stack */
1777 : 8319 : error_context_stack = spierrcontext.previous;
1778 : :
1779 : : /* Pop the SPI stack */
1780 : 8319 : _SPI_end_call(true);
1781 : :
1782 : : /* Return the created portal */
1783 : 8319 : return portal;
1784 : : }
1785 : :
1786 : :
1787 : : /*
1788 : : * SPI_cursor_find()
1789 : : *
1790 : : * Find the portal of an existing open cursor
1791 : : */
1792 : : Portal
1793 : 362 : SPI_cursor_find(const char *name)
1794 : : {
1795 : 362 : return GetPortalByName(name);
1796 : : }
1797 : :
1798 : :
1799 : : /*
1800 : : * SPI_cursor_fetch()
1801 : : *
1802 : : * Fetch rows in a cursor
1803 : : */
1804 : : void
1805 : 29665 : SPI_cursor_fetch(Portal portal, bool forward, long count)
1806 : : {
1807 : 29665 : _SPI_cursor_operation(portal,
1808 : 29665 : forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1809 : : CreateDestReceiver(DestSPI));
1810 : : /* we know that the DestSPI receiver doesn't need a destroy call */
1811 : 29660 : }
1812 : :
1813 : :
1814 : : /*
1815 : : * SPI_cursor_move()
1816 : : *
1817 : : * Move in a cursor
1818 : : */
1819 : : void
1820 : 0 : SPI_cursor_move(Portal portal, bool forward, long count)
1821 : : {
1822 : 0 : _SPI_cursor_operation(portal,
1823 : 0 : forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1824 : : None_Receiver);
1825 : 0 : }
1826 : :
1827 : :
1828 : : /*
1829 : : * SPI_scroll_cursor_fetch()
1830 : : *
1831 : : * Fetch rows in a scrollable cursor
1832 : : */
1833 : : void
1834 : 201 : SPI_scroll_cursor_fetch(Portal portal, FetchDirection direction, long count)
1835 : : {
1836 : 201 : _SPI_cursor_operation(portal,
1837 : : direction, count,
1838 : : CreateDestReceiver(DestSPI));
1839 : : /* we know that the DestSPI receiver doesn't need a destroy call */
1840 : 197 : }
1841 : :
1842 : :
1843 : : /*
1844 : : * SPI_scroll_cursor_move()
1845 : : *
1846 : : * Move in a scrollable cursor
1847 : : */
1848 : : void
1849 : 28 : SPI_scroll_cursor_move(Portal portal, FetchDirection direction, long count)
1850 : : {
1851 : 28 : _SPI_cursor_operation(portal, direction, count, None_Receiver);
1852 : 28 : }
1853 : :
1854 : :
1855 : : /*
1856 : : * SPI_cursor_close()
1857 : : *
1858 : : * Close a cursor
1859 : : */
1860 : : void
1861 : 8250 : SPI_cursor_close(Portal portal)
1862 : : {
1863 [ - + ]: 8250 : if (!PortalIsValid(portal))
1864 [ # # ]: 0 : elog(ERROR, "invalid portal in SPI cursor operation");
1865 : :
1866 : 8250 : PortalDrop(portal, false);
1867 : 8250 : }
1868 : :
1869 : : /*
1870 : : * Returns the Oid representing the type id for argument at argIndex. First
1871 : : * parameter is at index zero.
1872 : : */
1873 : : Oid
1874 : 0 : SPI_getargtypeid(SPIPlanPtr plan, int argIndex)
1875 : : {
1876 [ # # # # : 0 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
# # ]
1877 [ # # ]: 0 : argIndex < 0 || argIndex >= plan->nargs)
1878 : : {
1879 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1880 : 0 : return InvalidOid;
1881 : : }
1882 : 0 : return plan->argtypes[argIndex];
1883 : : }
1884 : :
1885 : : /*
1886 : : * Returns the number of arguments for the prepared plan.
1887 : : */
1888 : : int
1889 : 0 : SPI_getargcount(SPIPlanPtr plan)
1890 : : {
1891 [ # # # # ]: 0 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1892 : : {
1893 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1894 : 0 : return -1;
1895 : : }
1896 : 0 : return plan->nargs;
1897 : : }
1898 : :
1899 : : /*
1900 : : * Returns true if the plan contains exactly one command
1901 : : * and that command returns tuples to the caller (eg, SELECT or
1902 : : * INSERT ... RETURNING, but not SELECT ... INTO). In essence,
1903 : : * the result indicates if the command can be used with SPI_cursor_open
1904 : : *
1905 : : * Parameters
1906 : : * plan: A plan previously prepared using SPI_prepare
1907 : : */
1908 : : bool
1909 : 8319 : SPI_is_cursor_plan(SPIPlanPtr plan)
1910 : : {
1911 : : CachedPlanSource *plansource;
1912 : :
1913 [ + - - + ]: 8319 : if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1914 : : {
1915 : 0 : SPI_result = SPI_ERROR_ARGUMENT;
1916 : 0 : return false;
1917 : : }
1918 : :
1919 [ - + ]: 8319 : if (list_length(plan->plancache_list) != 1)
1920 : : {
1921 : 0 : SPI_result = 0;
1922 : 0 : return false; /* not exactly 1 pre-rewrite command */
1923 : : }
1924 : 8319 : plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1925 : :
1926 : : /*
1927 : : * We used to force revalidation of the cached plan here, but that seems
1928 : : * unnecessary: invalidation could mean a change in the rowtype of the
1929 : : * tuples returned by a plan, but not whether it returns tuples at all.
1930 : : */
1931 : 8319 : SPI_result = 0;
1932 : :
1933 : : /* Does it return tuples? */
1934 [ + - ]: 8319 : if (plansource->resultDesc)
1935 : 8319 : return true;
1936 : :
1937 : 0 : return false;
1938 : : }
1939 : :
1940 : : /*
1941 : : * SPI_plan_is_valid --- test whether a SPI plan is currently valid
1942 : : * (that is, not marked as being in need of revalidation).
1943 : : *
1944 : : * See notes for CachedPlanIsValid before using this.
1945 : : */
1946 : : bool
1947 : 1459 : SPI_plan_is_valid(SPIPlanPtr plan)
1948 : : {
1949 : : ListCell *lc;
1950 : :
1951 : : Assert(plan->magic == _SPI_PLAN_MAGIC);
1952 : :
1953 [ + - + + : 2776 : foreach(lc, plan->plancache_list)
+ + ]
1954 : : {
1955 : 1459 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
1956 : :
1957 [ + + ]: 1459 : if (!CachedPlanIsValid(plansource))
1958 : 142 : return false;
1959 : : }
1960 : 1317 : return true;
1961 : : }
1962 : :
1963 : : /*
1964 : : * SPI_result_code_string --- convert any SPI return code to a string
1965 : : *
1966 : : * This is often useful in error messages. Most callers will probably
1967 : : * only pass negative (error-case) codes, but for generality we recognize
1968 : : * the success codes too.
1969 : : */
1970 : : const char *
1971 : 60 : SPI_result_code_string(int code)
1972 : : {
1973 : : static char buf[64];
1974 : :
1975 [ - - - - : 60 : switch (code)
- - + - -
- - - - -
- + + - +
- - - - -
- - - - -
- - - ]
1976 : : {
1977 : 0 : case SPI_ERROR_CONNECT:
1978 : 0 : return "SPI_ERROR_CONNECT";
1979 : 0 : case SPI_ERROR_COPY:
1980 : 0 : return "SPI_ERROR_COPY";
1981 : 0 : case SPI_ERROR_OPUNKNOWN:
1982 : 0 : return "SPI_ERROR_OPUNKNOWN";
1983 : 0 : case SPI_ERROR_UNCONNECTED:
1984 : 0 : return "SPI_ERROR_UNCONNECTED";
1985 : 0 : case SPI_ERROR_ARGUMENT:
1986 : 0 : return "SPI_ERROR_ARGUMENT";
1987 : 0 : case SPI_ERROR_PARAM:
1988 : 0 : return "SPI_ERROR_PARAM";
1989 : 3 : case SPI_ERROR_TRANSACTION:
1990 : 3 : return "SPI_ERROR_TRANSACTION";
1991 : 0 : case SPI_ERROR_NOATTRIBUTE:
1992 : 0 : return "SPI_ERROR_NOATTRIBUTE";
1993 : 0 : case SPI_ERROR_NOOUTFUNC:
1994 : 0 : return "SPI_ERROR_NOOUTFUNC";
1995 : 0 : case SPI_ERROR_TYPUNKNOWN:
1996 : 0 : return "SPI_ERROR_TYPUNKNOWN";
1997 : 0 : case SPI_ERROR_REL_DUPLICATE:
1998 : 0 : return "SPI_ERROR_REL_DUPLICATE";
1999 : 0 : case SPI_ERROR_REL_NOT_FOUND:
2000 : 0 : return "SPI_ERROR_REL_NOT_FOUND";
2001 : 0 : case SPI_OK_CONNECT:
2002 : 0 : return "SPI_OK_CONNECT";
2003 : 0 : case SPI_OK_FINISH:
2004 : 0 : return "SPI_OK_FINISH";
2005 : 0 : case SPI_OK_FETCH:
2006 : 0 : return "SPI_OK_FETCH";
2007 : 1 : case SPI_OK_UTILITY:
2008 : 1 : return "SPI_OK_UTILITY";
2009 : 11 : case SPI_OK_SELECT:
2010 : 11 : return "SPI_OK_SELECT";
2011 : 0 : case SPI_OK_SELINTO:
2012 : 0 : return "SPI_OK_SELINTO";
2013 : 45 : case SPI_OK_INSERT:
2014 : 45 : return "SPI_OK_INSERT";
2015 : 0 : case SPI_OK_DELETE:
2016 : 0 : return "SPI_OK_DELETE";
2017 : 0 : case SPI_OK_UPDATE:
2018 : 0 : return "SPI_OK_UPDATE";
2019 : 0 : case SPI_OK_CURSOR:
2020 : 0 : return "SPI_OK_CURSOR";
2021 : 0 : case SPI_OK_INSERT_RETURNING:
2022 : 0 : return "SPI_OK_INSERT_RETURNING";
2023 : 0 : case SPI_OK_DELETE_RETURNING:
2024 : 0 : return "SPI_OK_DELETE_RETURNING";
2025 : 0 : case SPI_OK_UPDATE_RETURNING:
2026 : 0 : return "SPI_OK_UPDATE_RETURNING";
2027 : 0 : case SPI_OK_REWRITTEN:
2028 : 0 : return "SPI_OK_REWRITTEN";
2029 : 0 : case SPI_OK_REL_REGISTER:
2030 : 0 : return "SPI_OK_REL_REGISTER";
2031 : 0 : case SPI_OK_REL_UNREGISTER:
2032 : 0 : return "SPI_OK_REL_UNREGISTER";
2033 : 0 : case SPI_OK_TD_REGISTER:
2034 : 0 : return "SPI_OK_TD_REGISTER";
2035 : 0 : case SPI_OK_MERGE:
2036 : 0 : return "SPI_OK_MERGE";
2037 : 0 : case SPI_OK_MERGE_RETURNING:
2038 : 0 : return "SPI_OK_MERGE_RETURNING";
2039 : : }
2040 : : /* Unrecognized code ... return something useful ... */
2041 : 0 : sprintf(buf, "Unrecognized SPI code %d", code);
2042 : 0 : return buf;
2043 : : }
2044 : :
2045 : : /*
2046 : : * SPI_plan_get_plan_sources --- get a SPI plan's underlying list of
2047 : : * CachedPlanSources.
2048 : : *
2049 : : * CAUTION: there is no check on whether the CachedPlanSources are up-to-date.
2050 : : *
2051 : : * This is exported so that PL/pgSQL can use it (this beats letting PL/pgSQL
2052 : : * look directly into the SPIPlan for itself). It's not documented in
2053 : : * spi.sgml because we'd just as soon not have too many places using this.
2054 : : */
2055 : : List *
2056 : 39589 : SPI_plan_get_plan_sources(SPIPlanPtr plan)
2057 : : {
2058 : : Assert(plan->magic == _SPI_PLAN_MAGIC);
2059 : 39589 : return plan->plancache_list;
2060 : : }
2061 : :
2062 : : /*
2063 : : * SPI_plan_get_cached_plan --- get a SPI plan's generic CachedPlan,
2064 : : * if the SPI plan contains exactly one CachedPlanSource. If not,
2065 : : * return NULL.
2066 : : *
2067 : : * The plan's refcount is incremented (and logged in CurrentResourceOwner,
2068 : : * if it's a saved plan). Caller is responsible for doing ReleaseCachedPlan.
2069 : : *
2070 : : * This is exported so that PL/pgSQL can use it (this beats letting PL/pgSQL
2071 : : * look directly into the SPIPlan for itself). It's not documented in
2072 : : * spi.sgml because we'd just as soon not have too many places using this.
2073 : : */
2074 : : CachedPlan *
2075 : 19747 : SPI_plan_get_cached_plan(SPIPlanPtr plan)
2076 : : {
2077 : : CachedPlanSource *plansource;
2078 : : CachedPlan *cplan;
2079 : : SPICallbackArg spicallbackarg;
2080 : : ErrorContextCallback spierrcontext;
2081 : :
2082 : : Assert(plan->magic == _SPI_PLAN_MAGIC);
2083 : :
2084 : : /* Can't support one-shot plans here */
2085 [ - + ]: 19747 : if (plan->oneshot)
2086 : 0 : return NULL;
2087 : :
2088 : : /* Must have exactly one CachedPlanSource */
2089 [ - + ]: 19747 : if (list_length(plan->plancache_list) != 1)
2090 : 0 : return NULL;
2091 : 19747 : plansource = (CachedPlanSource *) linitial(plan->plancache_list);
2092 : :
2093 : : /* Setup error traceback support for ereport() */
2094 : 19747 : spicallbackarg.query = plansource->query_string;
2095 : 19747 : spicallbackarg.mode = plan->parse_mode;
2096 : 19747 : spierrcontext.callback = _SPI_error_callback;
2097 : 19747 : spierrcontext.arg = &spicallbackarg;
2098 : 19747 : spierrcontext.previous = error_context_stack;
2099 : 19747 : error_context_stack = &spierrcontext;
2100 : :
2101 : : /* Get the generic plan for the query */
2102 : 19747 : cplan = GetCachedPlan(plansource, NULL,
2103 : 19747 : plan->saved ? CurrentResourceOwner : NULL,
2104 [ + + ]: 19747 : _SPI_current->queryEnv);
2105 : : Assert(cplan == plansource->gplan);
2106 : :
2107 : : /* Pop the error context stack */
2108 : 19718 : error_context_stack = spierrcontext.previous;
2109 : :
2110 : 19718 : return cplan;
2111 : : }
2112 : :
2113 : :
2114 : : /* =================== private functions =================== */
2115 : :
2116 : : /*
2117 : : * spi_dest_startup
2118 : : * Initialize to receive tuples from Executor into SPITupleTable
2119 : : * of current SPI procedure
2120 : : */
2121 : : void
2122 : 60657 : spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2123 : : {
2124 : : SPITupleTable *tuptable;
2125 : : MemoryContext oldcxt;
2126 : : MemoryContext tuptabcxt;
2127 : :
2128 [ - + ]: 60657 : if (_SPI_current == NULL)
2129 [ # # ]: 0 : elog(ERROR, "spi_dest_startup called while not connected to SPI");
2130 : :
2131 [ - + ]: 60657 : if (_SPI_current->tuptable != NULL)
2132 [ # # ]: 0 : elog(ERROR, "improper call to spi_dest_startup");
2133 : :
2134 : : /* We create the tuple table context as a child of procCxt */
2135 : :
2136 : 60657 : oldcxt = _SPI_procmem(); /* switch to procedure memory context */
2137 : :
2138 : 60657 : tuptabcxt = AllocSetContextCreate(CurrentMemoryContext,
2139 : : "SPI TupTable",
2140 : : ALLOCSET_DEFAULT_SIZES);
2141 : 60657 : MemoryContextSwitchTo(tuptabcxt);
2142 : :
2143 : 60657 : _SPI_current->tuptable = tuptable = palloc0_object(SPITupleTable);
2144 : 60657 : tuptable->tuptabcxt = tuptabcxt;
2145 : 60657 : tuptable->subid = GetCurrentSubTransactionId();
2146 : :
2147 : : /*
2148 : : * The tuptable is now valid enough to be freed by AtEOSubXact_SPI, so put
2149 : : * it onto the SPI context's tuptables list. This will ensure it's not
2150 : : * leaked even in the unlikely event the following few lines fail.
2151 : : */
2152 : 60657 : slist_push_head(&_SPI_current->tuptables, &tuptable->next);
2153 : :
2154 : : /* set up initial allocations */
2155 : 60657 : tuptable->alloced = 128;
2156 : 60657 : tuptable->vals = palloc_array(HeapTuple, tuptable->alloced);
2157 : 60657 : tuptable->numvals = 0;
2158 : 60657 : tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
2159 : :
2160 : 60657 : MemoryContextSwitchTo(oldcxt);
2161 : 60657 : }
2162 : :
2163 : : /*
2164 : : * spi_printtup
2165 : : * store tuple retrieved by Executor into SPITupleTable
2166 : : * of current SPI procedure
2167 : : */
2168 : : bool
2169 : 73780 : spi_printtup(TupleTableSlot *slot, DestReceiver *self)
2170 : : {
2171 : : SPITupleTable *tuptable;
2172 : : MemoryContext oldcxt;
2173 : :
2174 [ - + ]: 73780 : if (_SPI_current == NULL)
2175 [ # # ]: 0 : elog(ERROR, "spi_printtup called while not connected to SPI");
2176 : :
2177 : 73780 : tuptable = _SPI_current->tuptable;
2178 [ - + ]: 73780 : if (tuptable == NULL)
2179 [ # # ]: 0 : elog(ERROR, "improper call to spi_printtup");
2180 : :
2181 : 73780 : oldcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
2182 : :
2183 [ - + ]: 73780 : if (tuptable->numvals >= tuptable->alloced)
2184 : : {
2185 : : /* Double the size of the pointer array */
2186 : 0 : uint64 newalloced = tuptable->alloced * 2;
2187 : :
2188 : 0 : tuptable->vals = (HeapTuple *) repalloc_huge(tuptable->vals,
2189 : : newalloced * sizeof(HeapTuple));
2190 : 0 : tuptable->alloced = newalloced;
2191 : : }
2192 : :
2193 : 73780 : tuptable->vals[tuptable->numvals] = ExecCopySlotHeapTuple(slot);
2194 : 73780 : (tuptable->numvals)++;
2195 : :
2196 : 73780 : MemoryContextSwitchTo(oldcxt);
2197 : :
2198 : 73780 : return true;
2199 : : }
2200 : :
2201 : : /*
2202 : : * Static functions
2203 : : */
2204 : :
2205 : : /*
2206 : : * Parse and analyze a querystring.
2207 : : *
2208 : : * At entry, plan->argtypes and plan->nargs (or alternatively plan->parserSetup
2209 : : * and plan->parserSetupArg) must be valid, as must plan->parse_mode and
2210 : : * plan->cursor_options.
2211 : : *
2212 : : * Results are stored into *plan (specifically, plan->plancache_list).
2213 : : * Note that the result data is all in CurrentMemoryContext or child contexts
2214 : : * thereof; in practice this means it is in the SPI executor context, and
2215 : : * what we are creating is a "temporary" SPIPlan. Cruft generated during
2216 : : * parsing is also left in CurrentMemoryContext.
2217 : : */
2218 : : static void
2219 : 27116 : _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
2220 : : {
2221 : : List *raw_parsetree_list;
2222 : : List *plancache_list;
2223 : : ListCell *list_item;
2224 : : SPICallbackArg spicallbackarg;
2225 : : ErrorContextCallback spierrcontext;
2226 : :
2227 : : /*
2228 : : * Setup error traceback support for ereport()
2229 : : */
2230 : 27116 : spicallbackarg.query = src;
2231 : 27116 : spicallbackarg.mode = plan->parse_mode;
2232 : 27116 : spierrcontext.callback = _SPI_error_callback;
2233 : 27116 : spierrcontext.arg = &spicallbackarg;
2234 : 27116 : spierrcontext.previous = error_context_stack;
2235 : 27116 : error_context_stack = &spierrcontext;
2236 : :
2237 : : /*
2238 : : * Parse the request string into a list of raw parse trees.
2239 : : */
2240 : 27116 : raw_parsetree_list = raw_parser(src, plan->parse_mode);
2241 : :
2242 : : /*
2243 : : * Do parse analysis and rule rewrite for each raw parsetree, storing the
2244 : : * results into unsaved plancache entries.
2245 : : */
2246 : 27116 : plancache_list = NIL;
2247 : :
2248 [ + - + + : 54170 : foreach(list_item, raw_parsetree_list)
+ + ]
2249 : : {
2250 : 27116 : RawStmt *parsetree = lfirst_node(RawStmt, list_item);
2251 : : List *stmt_list;
2252 : : CachedPlanSource *plansource;
2253 : :
2254 : : /*
2255 : : * Create the CachedPlanSource before we do parse analysis, since it
2256 : : * needs to see the unmodified raw parse tree.
2257 : : */
2258 : 27116 : plansource = CreateCachedPlan(parsetree,
2259 : : src,
2260 : : CreateCommandTag(parsetree->stmt));
2261 : :
2262 : : /*
2263 : : * Parameter datatypes are driven by parserSetup hook if provided,
2264 : : * otherwise we use the fixed parameter list.
2265 : : */
2266 [ + + ]: 27116 : if (plan->parserSetup != NULL)
2267 : : {
2268 : : Assert(plan->nargs == 0);
2269 : 18294 : stmt_list = pg_analyze_and_rewrite_withcb(parsetree,
2270 : : src,
2271 : : plan->parserSetup,
2272 : : plan->parserSetupArg,
2273 : 18294 : _SPI_current->queryEnv);
2274 : : }
2275 : : else
2276 : : {
2277 : 8822 : stmt_list = pg_analyze_and_rewrite_fixedparams(parsetree,
2278 : : src,
2279 : : plan->argtypes,
2280 : : plan->nargs,
2281 : 8822 : _SPI_current->queryEnv);
2282 : : }
2283 : :
2284 : : /* Finish filling in the CachedPlanSource */
2285 : 27054 : CompleteCachedPlan(plansource,
2286 : : stmt_list,
2287 : : NULL,
2288 : : plan->argtypes,
2289 : : plan->nargs,
2290 : : plan->parserSetup,
2291 : : plan->parserSetupArg,
2292 : : plan->cursor_options,
2293 : : false); /* not fixed result */
2294 : :
2295 : 27054 : plancache_list = lappend(plancache_list, plansource);
2296 : : }
2297 : :
2298 : 27054 : plan->plancache_list = plancache_list;
2299 : 27054 : plan->oneshot = false;
2300 : :
2301 : : /*
2302 : : * Pop the error context stack
2303 : : */
2304 : 27054 : error_context_stack = spierrcontext.previous;
2305 : 27054 : }
2306 : :
2307 : : /*
2308 : : * Parse, but don't analyze, a querystring.
2309 : : *
2310 : : * This is a stripped-down version of _SPI_prepare_plan that only does the
2311 : : * initial raw parsing. It creates "one shot" CachedPlanSources
2312 : : * that still require parse analysis before execution is possible.
2313 : : *
2314 : : * The advantage of using the "one shot" form of CachedPlanSource is that
2315 : : * we eliminate data copying and invalidation overhead. Postponing parse
2316 : : * analysis also prevents issues if some of the raw parsetrees are DDL
2317 : : * commands that affect validity of later parsetrees. Both of these
2318 : : * attributes are good things for SPI_execute() and similar cases.
2319 : : *
2320 : : * Results are stored into *plan (specifically, plan->plancache_list).
2321 : : * Note that the result data is all in CurrentMemoryContext or child contexts
2322 : : * thereof; in practice this means it is in the SPI executor context, and
2323 : : * what we are creating is a "temporary" SPIPlan. Cruft generated during
2324 : : * parsing is also left in CurrentMemoryContext.
2325 : : */
2326 : : static void
2327 : 12182 : _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan)
2328 : : {
2329 : : List *raw_parsetree_list;
2330 : : List *plancache_list;
2331 : : ListCell *list_item;
2332 : : SPICallbackArg spicallbackarg;
2333 : : ErrorContextCallback spierrcontext;
2334 : :
2335 : : /*
2336 : : * Setup error traceback support for ereport()
2337 : : */
2338 : 12182 : spicallbackarg.query = src;
2339 : 12182 : spicallbackarg.mode = plan->parse_mode;
2340 : 12182 : spierrcontext.callback = _SPI_error_callback;
2341 : 12182 : spierrcontext.arg = &spicallbackarg;
2342 : 12182 : spierrcontext.previous = error_context_stack;
2343 : 12182 : error_context_stack = &spierrcontext;
2344 : :
2345 : : /*
2346 : : * Parse the request string into a list of raw parse trees.
2347 : : */
2348 : 12182 : raw_parsetree_list = raw_parser(src, plan->parse_mode);
2349 : :
2350 : : /*
2351 : : * Construct plancache entries, but don't do parse analysis yet.
2352 : : */
2353 : 12174 : plancache_list = NIL;
2354 : :
2355 [ + - + + : 24353 : foreach(list_item, raw_parsetree_list)
+ + ]
2356 : : {
2357 : 12179 : RawStmt *parsetree = lfirst_node(RawStmt, list_item);
2358 : : CachedPlanSource *plansource;
2359 : :
2360 : 12179 : plansource = CreateOneShotCachedPlan(parsetree,
2361 : : src,
2362 : : CreateCommandTag(parsetree->stmt));
2363 : :
2364 : 12179 : plancache_list = lappend(plancache_list, plansource);
2365 : : }
2366 : :
2367 : 12174 : plan->plancache_list = plancache_list;
2368 : 12174 : plan->oneshot = true;
2369 : :
2370 : : /*
2371 : : * Pop the error context stack
2372 : : */
2373 : 12174 : error_context_stack = spierrcontext.previous;
2374 : 12174 : }
2375 : :
2376 : : /*
2377 : : * _SPI_execute_plan: execute the given plan with the given options
2378 : : *
2379 : : * options contains options accessible from outside SPI:
2380 : : * params: parameter values to pass to query
2381 : : * read_only: true for read-only execution (no CommandCounterIncrement)
2382 : : * allow_nonatomic: true to allow nonatomic CALL/DO execution
2383 : : * must_return_tuples: throw error if query doesn't return tuples
2384 : : * tcount: execution tuple-count limit, or 0 for none
2385 : : * dest: DestReceiver to receive output, or NULL for normal SPI output
2386 : : * owner: ResourceOwner that will be used to hold refcount on plan;
2387 : : * if NULL, CurrentResourceOwner is used (ignored for non-saved plan)
2388 : : *
2389 : : * Additional, only-internally-accessible options:
2390 : : * snapshot: query snapshot to use, or InvalidSnapshot for the normal
2391 : : * behavior of taking a new snapshot for each query.
2392 : : * crosscheck_snapshot: for RI use, all others pass InvalidSnapshot
2393 : : * fire_triggers: true to fire AFTER triggers at end of query (normal case);
2394 : : * false means any AFTER triggers are postponed to end of outer query
2395 : : */
2396 : : static int
2397 : 68828 : _SPI_execute_plan(SPIPlanPtr plan, const SPIExecuteOptions *options,
2398 : : Snapshot snapshot, Snapshot crosscheck_snapshot,
2399 : : bool fire_triggers)
2400 : : {
2401 : 68828 : int my_res = 0;
2402 : 68828 : uint64 my_processed = 0;
2403 : 68828 : SPITupleTable *my_tuptable = NULL;
2404 : 68828 : int res = 0;
2405 : : bool allow_nonatomic;
2406 : 68828 : bool pushed_active_snap = false;
2407 : 68828 : ResourceOwner plan_owner = options->owner;
2408 : : SPICallbackArg spicallbackarg;
2409 : : ErrorContextCallback spierrcontext;
2410 : 68828 : CachedPlan *cplan = NULL;
2411 : : ListCell *lc1;
2412 : :
2413 : : /*
2414 : : * We allow nonatomic behavior only if options->allow_nonatomic is set
2415 : : * *and* the SPI_OPT_NONATOMIC flag was given when connecting and we are
2416 : : * not inside a subtransaction. The latter two tests match whether
2417 : : * _SPI_commit() would allow a commit; see there for more commentary.
2418 : : */
2419 : 137715 : allow_nonatomic = options->allow_nonatomic &&
2420 [ + + + + : 68828 : !_SPI_current->atomic && !IsSubTransaction();
+ + ]
2421 : :
2422 : : /*
2423 : : * Setup error traceback support for ereport()
2424 : : */
2425 : 68828 : spicallbackarg.query = NULL; /* we'll fill this below */
2426 : 68828 : spicallbackarg.mode = plan->parse_mode;
2427 : 68828 : spierrcontext.callback = _SPI_error_callback;
2428 : 68828 : spierrcontext.arg = &spicallbackarg;
2429 : 68828 : spierrcontext.previous = error_context_stack;
2430 : 68828 : error_context_stack = &spierrcontext;
2431 : :
2432 : : /*
2433 : : * We support four distinct snapshot management behaviors:
2434 : : *
2435 : : * snapshot != InvalidSnapshot, read_only = true: use exactly the given
2436 : : * snapshot.
2437 : : *
2438 : : * snapshot != InvalidSnapshot, read_only = false: use the given snapshot,
2439 : : * modified by advancing its command ID before each querytree.
2440 : : *
2441 : : * snapshot == InvalidSnapshot, read_only = true: do nothing for queries
2442 : : * that require no snapshot. For those that do, ensure that a Portal
2443 : : * snapshot exists; then use that, or use the entry-time ActiveSnapshot if
2444 : : * that exists and is different.
2445 : : *
2446 : : * snapshot == InvalidSnapshot, read_only = false: do nothing for queries
2447 : : * that require no snapshot. For those that do, ensure that a Portal
2448 : : * snapshot exists; then, in atomic execution (!allow_nonatomic) take a
2449 : : * full new snapshot for each user command, and advance its command ID
2450 : : * before each querytree within the command. In allow_nonatomic mode we
2451 : : * just use the Portal snapshot unmodified.
2452 : : *
2453 : : * In the first two cases, we can just push the snap onto the stack once
2454 : : * for the whole plan list.
2455 : : *
2456 : : * Note that snapshot != InvalidSnapshot implies an atomic execution
2457 : : * context.
2458 : : */
2459 [ + + ]: 68828 : if (snapshot != InvalidSnapshot)
2460 : : {
2461 : : /* this intentionally tests the options field not the derived value */
2462 : : Assert(!options->allow_nonatomic);
2463 [ + + ]: 862 : if (options->read_only)
2464 : : {
2465 : 826 : PushActiveSnapshot(snapshot);
2466 : 826 : pushed_active_snap = true;
2467 : : }
2468 : : else
2469 : : {
2470 : : /* Make sure we have a private copy of the snapshot to modify */
2471 : 36 : PushCopiedSnapshot(snapshot);
2472 : 36 : pushed_active_snap = true;
2473 : : }
2474 : : }
2475 : :
2476 : : /*
2477 : : * Ensure that we have a resource owner if plan is saved, and not if it
2478 : : * isn't.
2479 : : */
2480 [ + + ]: 68828 : if (!plan->saved)
2481 : 13074 : plan_owner = NULL;
2482 [ + + ]: 55754 : else if (plan_owner == NULL)
2483 : 55699 : plan_owner = CurrentResourceOwner;
2484 : :
2485 : : /*
2486 : : * We interpret must_return_tuples as "there must be at least one query,
2487 : : * and all of them must return tuples". This is a bit laxer than
2488 : : * SPI_is_cursor_plan's check, but there seems no reason to enforce that
2489 : : * there be only one query.
2490 : : */
2491 [ + + - + ]: 68828 : if (options->must_return_tuples && plan->plancache_list == NIL)
2492 [ # # ]: 0 : ereport(ERROR,
2493 : : (errcode(ERRCODE_SYNTAX_ERROR),
2494 : : errmsg("empty query does not return tuples")));
2495 : :
2496 [ + - + + : 134401 : foreach(lc1, plan->plancache_list)
+ + ]
2497 : : {
2498 : 68832 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
2499 : : List *stmt_list;
2500 : : ListCell *lc2;
2501 : :
2502 : 68832 : spicallbackarg.query = plansource->query_string;
2503 : :
2504 : : /*
2505 : : * If this is a one-shot plan, we still need to do parse analysis.
2506 : : */
2507 [ + + ]: 68832 : if (plan->oneshot)
2508 : : {
2509 : 12178 : RawStmt *parsetree = plansource->raw_parse_tree;
2510 : 12178 : const char *src = plansource->query_string;
2511 : : List *querytree_list;
2512 : :
2513 : : /*
2514 : : * Parameter datatypes are driven by parserSetup hook if provided,
2515 : : * otherwise we use the fixed parameter list.
2516 : : */
2517 [ - + ]: 12178 : if (parsetree == NULL)
2518 : 0 : querytree_list = NIL;
2519 [ + + ]: 12178 : else if (plan->parserSetup != NULL)
2520 : : {
2521 : : Assert(plan->nargs == 0);
2522 : 289 : querytree_list = pg_analyze_and_rewrite_withcb(parsetree,
2523 : : src,
2524 : : plan->parserSetup,
2525 : : plan->parserSetupArg,
2526 : 289 : _SPI_current->queryEnv);
2527 : : }
2528 : : else
2529 : : {
2530 : 11889 : querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree,
2531 : : src,
2532 : : plan->argtypes,
2533 : : plan->nargs,
2534 : 11889 : _SPI_current->queryEnv);
2535 : : }
2536 : :
2537 : : /* Finish filling in the CachedPlanSource */
2538 : 12171 : CompleteCachedPlan(plansource,
2539 : : querytree_list,
2540 : : NULL,
2541 : : plan->argtypes,
2542 : : plan->nargs,
2543 : : plan->parserSetup,
2544 : : plan->parserSetupArg,
2545 : : plan->cursor_options,
2546 : : false); /* not fixed result */
2547 : : }
2548 : :
2549 : : /*
2550 : : * If asked to, complain when query does not return tuples.
2551 : : * (Replanning can't change this, so we can check it before that.
2552 : : * However, we can't check it till after parse analysis, so in the
2553 : : * case of a one-shot plan this is the earliest we could check.)
2554 : : */
2555 [ + + + + ]: 68825 : if (options->must_return_tuples && !plansource->resultDesc)
2556 : : {
2557 : : /* try to give a good error message */
2558 : : const char *cmdtag;
2559 : :
2560 : : /* A SELECT without resultDesc must be SELECT INTO */
2561 [ + - ]: 8 : if (plansource->commandTag == CMDTAG_SELECT)
2562 : 8 : cmdtag = "SELECT INTO";
2563 : : else
2564 : 0 : cmdtag = GetCommandTagName(plansource->commandTag);
2565 [ + - ]: 8 : ereport(ERROR,
2566 : : (errcode(ERRCODE_SYNTAX_ERROR),
2567 : : /* translator: %s is name of a SQL command, eg INSERT */
2568 : : errmsg("%s query does not return tuples", cmdtag)));
2569 : : }
2570 : :
2571 : : /*
2572 : : * Replan if needed, and increment plan refcount. If it's a saved
2573 : : * plan, the refcount must be backed by the plan_owner.
2574 : : */
2575 : 68817 : cplan = GetCachedPlan(plansource, options->params,
2576 : 68817 : plan_owner, _SPI_current->queryEnv);
2577 : :
2578 : 68726 : stmt_list = cplan->stmt_list;
2579 : :
2580 : : /*
2581 : : * If we weren't given a specific snapshot to use, and the statement
2582 : : * list requires a snapshot, set that up.
2583 : : */
2584 [ + + + - ]: 136590 : if (snapshot == InvalidSnapshot &&
2585 [ + - ]: 135728 : (list_length(stmt_list) > 1 ||
2586 [ + + ]: 135728 : (list_length(stmt_list) == 1 &&
2587 : 67864 : PlannedStmtRequiresSnapshot(linitial_node(PlannedStmt,
2588 : : stmt_list)))))
2589 : : {
2590 : : /*
2591 : : * First, ensure there's a Portal-level snapshot. This back-fills
2592 : : * the snapshot stack in case the previous operation was a COMMIT
2593 : : * or ROLLBACK inside a procedure or DO block. (We can't put back
2594 : : * the Portal snapshot any sooner, or we'd break cases like doing
2595 : : * SET or LOCK just after COMMIT.) It's enough to check once per
2596 : : * statement list, since COMMIT/ROLLBACK/CALL/DO can't appear
2597 : : * within a multi-statement list.
2598 : : */
2599 : 59202 : EnsurePortalSnapshotExists();
2600 : :
2601 : : /*
2602 : : * In the default non-read-only case, get a new per-statement-list
2603 : : * snapshot, replacing any that we pushed in a previous cycle.
2604 : : * Skip it when doing non-atomic execution, though (we rely
2605 : : * entirely on the Portal snapshot in that case).
2606 : : */
2607 [ + + + + ]: 59202 : if (!options->read_only && !allow_nonatomic)
2608 : : {
2609 [ + + ]: 56171 : if (pushed_active_snap)
2610 : 4 : PopActiveSnapshot();
2611 : 56171 : PushActiveSnapshot(GetTransactionSnapshot());
2612 : 56171 : pushed_active_snap = true;
2613 : : }
2614 : : }
2615 : :
2616 [ + - + + : 134299 : foreach(lc2, stmt_list)
+ + ]
2617 : : {
2618 : 68726 : PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
2619 : 68726 : bool canSetTag = stmt->canSetTag;
2620 : : DestReceiver *dest;
2621 : :
2622 : : /*
2623 : : * Reset output state. (Note that if a non-SPI receiver is used,
2624 : : * _SPI_current->processed will stay zero, and that's what we'll
2625 : : * report to the caller. It's the receiver's job to count tuples
2626 : : * in that case.)
2627 : : */
2628 : 68726 : _SPI_current->processed = 0;
2629 : 68726 : _SPI_current->tuptable = NULL;
2630 : :
2631 : : /* Check for unsupported cases. */
2632 [ + + ]: 68726 : if (stmt->utilityStmt)
2633 : : {
2634 [ + + ]: 17686 : if (IsA(stmt->utilityStmt, CopyStmt))
2635 : : {
2636 : 9 : CopyStmt *cstmt = (CopyStmt *) stmt->utilityStmt;
2637 : :
2638 [ + + ]: 9 : if (cstmt->filename == NULL)
2639 : : {
2640 : 4 : my_res = SPI_ERROR_COPY;
2641 : 9 : goto fail;
2642 : : }
2643 : : }
2644 [ + + ]: 17677 : else if (IsA(stmt->utilityStmt, TransactionStmt))
2645 : : {
2646 : 5 : my_res = SPI_ERROR_TRANSACTION;
2647 : 5 : goto fail;
2648 : : }
2649 : : }
2650 : :
2651 [ + + - + ]: 68717 : if (options->read_only && !CommandIsReadOnly(stmt))
2652 [ # # ]: 0 : ereport(ERROR,
2653 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2654 : : /* translator: %s is a SQL statement name */
2655 : : errmsg("%s is not allowed in a non-volatile function",
2656 : : CreateCommandName((Node *) stmt))));
2657 : :
2658 : : /*
2659 : : * If not read-only mode, advance the command counter before each
2660 : : * command and update the snapshot. (But skip it if the snapshot
2661 : : * isn't under our control.)
2662 : : */
2663 [ + + + + ]: 68717 : if (!options->read_only && pushed_active_snap)
2664 : : {
2665 : 56203 : CommandCounterIncrement();
2666 : 56203 : UpdateActiveSnapshotCommandId();
2667 : : }
2668 : :
2669 : : /*
2670 : : * Select appropriate tuple receiver. Output from non-canSetTag
2671 : : * subqueries always goes to the bit bucket.
2672 : : */
2673 [ - + ]: 68717 : if (!canSetTag)
2674 : 0 : dest = CreateDestReceiver(DestNone);
2675 [ + + ]: 68717 : else if (options->dest)
2676 : 1849 : dest = options->dest;
2677 : : else
2678 : 66868 : dest = CreateDestReceiver(DestSPI);
2679 : :
2680 [ + + ]: 68717 : if (stmt->utilityStmt == NULL)
2681 : : {
2682 : : QueryDesc *qdesc;
2683 : : Snapshot snap;
2684 : :
2685 [ + - ]: 51040 : if (ActiveSnapshotSet())
2686 : 51040 : snap = GetActiveSnapshot();
2687 : : else
2688 : 0 : snap = InvalidSnapshot;
2689 : :
2690 : 51040 : qdesc = CreateQueryDesc(stmt,
2691 : : plansource->query_string,
2692 : : snap, crosscheck_snapshot,
2693 : : dest,
2694 : 51040 : options->params,
2695 : 51040 : _SPI_current->queryEnv,
2696 : : 0);
2697 [ + - ]: 51040 : res = _SPI_pquery(qdesc, fire_triggers,
2698 : : canSetTag ? options->tcount : 0);
2699 : 47997 : FreeQueryDesc(qdesc);
2700 : : }
2701 : : else
2702 : : {
2703 : : ProcessUtilityContext context;
2704 : : QueryCompletion qc;
2705 : :
2706 : : /*
2707 : : * If we're not allowing nonatomic operations, tell
2708 : : * ProcessUtility this is an atomic execution context.
2709 : : */
2710 [ + + ]: 17677 : if (allow_nonatomic)
2711 : 51 : context = PROCESS_UTILITY_QUERY_NONATOMIC;
2712 : : else
2713 : 17626 : context = PROCESS_UTILITY_QUERY;
2714 : :
2715 : 17677 : InitializeQueryCompletion(&qc);
2716 : 17677 : ProcessUtility(stmt,
2717 : : plansource->query_string,
2718 : : true, /* protect plancache's node tree */
2719 : : context,
2720 : 17677 : options->params,
2721 : 17677 : _SPI_current->queryEnv,
2722 : : dest,
2723 : : &qc);
2724 : :
2725 : : /* Update "processed" if stmt returned tuples */
2726 [ + + ]: 17576 : if (_SPI_current->tuptable)
2727 : 1226 : _SPI_current->processed = _SPI_current->tuptable->numvals;
2728 : :
2729 : 17576 : res = SPI_OK_UTILITY;
2730 : :
2731 : : /*
2732 : : * Some utility statements return a row count, even though the
2733 : : * tuples are not returned to the caller.
2734 : : */
2735 [ + + ]: 17576 : if (IsA(stmt->utilityStmt, CreateTableAsStmt))
2736 : : {
2737 : 33 : CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
2738 : :
2739 [ + + ]: 33 : if (qc.commandTag == CMDTAG_SELECT)
2740 : 29 : _SPI_current->processed = qc.nprocessed;
2741 : : else
2742 : : {
2743 : : /*
2744 : : * Must be an IF NOT EXISTS that did nothing, or a
2745 : : * CREATE ... WITH NO DATA.
2746 : : */
2747 : : Assert(ctastmt->if_not_exists ||
2748 : : ctastmt->into->skipData);
2749 : 4 : _SPI_current->processed = 0;
2750 : : }
2751 : :
2752 : : /*
2753 : : * For historical reasons, if CREATE TABLE AS was spelled
2754 : : * as SELECT INTO, return a special return code.
2755 : : */
2756 [ - + ]: 33 : if (ctastmt->is_select_into)
2757 : 0 : res = SPI_OK_SELINTO;
2758 : : }
2759 [ + + ]: 17543 : else if (IsA(stmt->utilityStmt, CopyStmt))
2760 : : {
2761 : : Assert(qc.commandTag == CMDTAG_COPY);
2762 : 5 : _SPI_current->processed = qc.nprocessed;
2763 : : }
2764 : : }
2765 : :
2766 : : /*
2767 : : * The last canSetTag query sets the status values returned to the
2768 : : * caller. Be careful to free any tuptables not returned, to
2769 : : * avoid intra-transaction memory leak.
2770 : : */
2771 [ + - ]: 65573 : if (canSetTag)
2772 : : {
2773 : 65573 : my_processed = _SPI_current->processed;
2774 : 65573 : SPI_freetuptable(my_tuptable);
2775 : 65573 : my_tuptable = _SPI_current->tuptable;
2776 : 65573 : my_res = res;
2777 : : }
2778 : : else
2779 : : {
2780 : 0 : SPI_freetuptable(_SPI_current->tuptable);
2781 : 0 : _SPI_current->tuptable = NULL;
2782 : : }
2783 : :
2784 : : /*
2785 : : * We don't issue a destroy call to the receiver. The SPI and
2786 : : * None receivers would ignore it anyway, while if the caller
2787 : : * supplied a receiver, it's not our job to destroy it.
2788 : : */
2789 : :
2790 [ - + ]: 65573 : if (res < 0)
2791 : : {
2792 : 0 : my_res = res;
2793 : 0 : goto fail;
2794 : : }
2795 : : }
2796 : :
2797 : : /* Done with this plan, so release refcount */
2798 : 65573 : ReleaseCachedPlan(cplan, plan_owner);
2799 : 65573 : cplan = NULL;
2800 : :
2801 : : /*
2802 : : * If not read-only mode, advance the command counter after the last
2803 : : * command. This ensures that its effects are visible, in case it was
2804 : : * DDL that would affect the next CachedPlanSource.
2805 : : */
2806 [ + + ]: 65573 : if (!options->read_only)
2807 : 61805 : CommandCounterIncrement();
2808 : : }
2809 : :
2810 : 65578 : fail:
2811 : :
2812 : : /* Pop the snapshot off the stack if we pushed one */
2813 [ + + ]: 65578 : if (pushed_active_snap)
2814 : 53948 : PopActiveSnapshot();
2815 : :
2816 : : /* We no longer need the cached plan refcount, if any */
2817 [ + + ]: 65578 : if (cplan)
2818 : 9 : ReleaseCachedPlan(cplan, plan_owner);
2819 : :
2820 : : /*
2821 : : * Pop the error context stack
2822 : : */
2823 : 65578 : error_context_stack = spierrcontext.previous;
2824 : :
2825 : : /* Save results for caller */
2826 : 65578 : SPI_processed = my_processed;
2827 : 65578 : SPI_tuptable = my_tuptable;
2828 : :
2829 : : /* tuptable now is caller's responsibility, not SPI's */
2830 : 65578 : _SPI_current->tuptable = NULL;
2831 : :
2832 : : /*
2833 : : * If none of the queries had canSetTag, return SPI_OK_REWRITTEN. Prior to
2834 : : * 8.4, we used return the last query's result code, but not its auxiliary
2835 : : * results, but that's confusing.
2836 : : */
2837 [ - + ]: 65578 : if (my_res == 0)
2838 : 0 : my_res = SPI_OK_REWRITTEN;
2839 : :
2840 : 65578 : return my_res;
2841 : : }
2842 : :
2843 : : /*
2844 : : * Convert arrays of query parameters to form wanted by planner and executor
2845 : : */
2846 : : static ParamListInfo
2847 : 6095 : _SPI_convert_params(int nargs, const Oid *argtypes,
2848 : : const Datum *Values, const char *Nulls)
2849 : : {
2850 : : ParamListInfo paramLI;
2851 : :
2852 [ + + ]: 6095 : if (nargs > 0)
2853 : : {
2854 : 5053 : paramLI = makeParamList(nargs);
2855 : :
2856 [ + + ]: 13602 : for (int i = 0; i < nargs; i++)
2857 : : {
2858 : 8549 : ParamExternData *prm = ¶mLI->params[i];
2859 : :
2860 : 8549 : prm->value = Values[i];
2861 [ + + - + ]: 8549 : prm->isnull = (Nulls && Nulls[i] == 'n');
2862 : 8549 : prm->pflags = PARAM_FLAG_CONST;
2863 : 8549 : prm->ptype = argtypes[i];
2864 : : }
2865 : : }
2866 : : else
2867 : 1042 : paramLI = NULL;
2868 : 6095 : return paramLI;
2869 : : }
2870 : :
2871 : : static int
2872 : 51040 : _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
2873 : : {
2874 : 51040 : int operation = queryDesc->operation;
2875 : : int eflags;
2876 : : int res;
2877 : :
2878 [ + + + + : 51040 : switch (operation)
+ - ]
2879 : : {
2880 : 30281 : case CMD_SELECT:
2881 [ - + ]: 30281 : if (queryDesc->dest->mydest == DestNone)
2882 : : {
2883 : : /* Don't return SPI_OK_SELECT if we're discarding result */
2884 : 0 : res = SPI_OK_UTILITY;
2885 : : }
2886 : : else
2887 : 30281 : res = SPI_OK_SELECT;
2888 : 30281 : break;
2889 : 13996 : case CMD_INSERT:
2890 [ + + ]: 13996 : if (queryDesc->plannedstmt->hasReturning)
2891 : 1070 : res = SPI_OK_INSERT_RETURNING;
2892 : : else
2893 : 12926 : res = SPI_OK_INSERT;
2894 : 13996 : break;
2895 : 5625 : case CMD_DELETE:
2896 [ - + ]: 5625 : if (queryDesc->plannedstmt->hasReturning)
2897 : 0 : res = SPI_OK_DELETE_RETURNING;
2898 : : else
2899 : 5625 : res = SPI_OK_DELETE;
2900 : 5625 : break;
2901 : 1094 : case CMD_UPDATE:
2902 [ + + ]: 1094 : if (queryDesc->plannedstmt->hasReturning)
2903 : 11 : res = SPI_OK_UPDATE_RETURNING;
2904 : : else
2905 : 1083 : res = SPI_OK_UPDATE;
2906 : 1094 : break;
2907 : 44 : case CMD_MERGE:
2908 [ + + ]: 44 : if (queryDesc->plannedstmt->hasReturning)
2909 : 12 : res = SPI_OK_MERGE_RETURNING;
2910 : : else
2911 : 32 : res = SPI_OK_MERGE;
2912 : 44 : break;
2913 : 0 : default:
2914 : 0 : return SPI_ERROR_OPUNKNOWN;
2915 : : }
2916 : :
2917 : : #ifdef SPI_EXECUTOR_STATS
2918 : : if (ShowExecutorStats)
2919 : : ResetUsage();
2920 : : #endif
2921 : :
2922 : : /* Select execution options */
2923 [ + + ]: 51040 : if (fire_triggers)
2924 : 47725 : eflags = 0; /* default run-to-completion flags */
2925 : : else
2926 : 3315 : eflags = EXEC_FLAG_SKIP_TRIGGERS;
2927 : :
2928 : 51040 : ExecutorStart(queryDesc, eflags);
2929 : :
2930 : 51040 : ExecutorRun(queryDesc, ForwardScanDirection, tcount);
2931 : :
2932 : 48018 : _SPI_current->processed = queryDesc->estate->es_processed;
2933 : :
2934 [ + + + + ]: 48018 : if ((res == SPI_OK_SELECT || queryDesc->plannedstmt->hasReturning) &&
2935 [ + + ]: 28378 : queryDesc->dest->mydest == DestSPI)
2936 : : {
2937 [ - + ]: 26570 : if (_SPI_checktuples())
2938 [ # # ]: 0 : elog(ERROR, "consistency check on SPI tuple count failed");
2939 : : }
2940 : :
2941 : 48018 : ExecutorFinish(queryDesc);
2942 : 47997 : ExecutorEnd(queryDesc);
2943 : : /* FreeQueryDesc is done by the caller */
2944 : :
2945 : : #ifdef SPI_EXECUTOR_STATS
2946 : : if (ShowExecutorStats)
2947 : : ShowUsage("SPI EXECUTOR STATS");
2948 : : #endif
2949 : :
2950 : 47997 : return res;
2951 : : }
2952 : :
2953 : : /*
2954 : : * _SPI_error_callback
2955 : : *
2956 : : * Add context information when a query invoked via SPI fails
2957 : : */
2958 : : static void
2959 : 3801 : _SPI_error_callback(void *arg)
2960 : : {
2961 : 3801 : SPICallbackArg *carg = (SPICallbackArg *) arg;
2962 : 3801 : const char *query = carg->query;
2963 : : int syntaxerrposition;
2964 : :
2965 [ - + ]: 3801 : if (query == NULL) /* in case arg wasn't set yet */
2966 : 0 : return;
2967 : :
2968 : : /*
2969 : : * If there is a syntax error position, convert to internal syntax error;
2970 : : * otherwise treat the query as an item of context stack
2971 : : */
2972 : 3801 : syntaxerrposition = geterrposition();
2973 [ + + ]: 3801 : if (syntaxerrposition > 0)
2974 : : {
2975 : 61 : errposition(0);
2976 : 61 : internalerrposition(syntaxerrposition);
2977 : 61 : internalerrquery(query);
2978 : : }
2979 : : else
2980 : : {
2981 : : /* Use the parse mode to decide how to describe the query */
2982 [ + + + ]: 3740 : switch (carg->mode)
2983 : : {
2984 : 49 : case RAW_PARSE_PLPGSQL_EXPR:
2985 : 49 : errcontext("PL/pgSQL expression \"%s\"", query);
2986 : 49 : break;
2987 : 8 : case RAW_PARSE_PLPGSQL_ASSIGN1:
2988 : : case RAW_PARSE_PLPGSQL_ASSIGN2:
2989 : : case RAW_PARSE_PLPGSQL_ASSIGN3:
2990 : 8 : errcontext("PL/pgSQL assignment \"%s\"", query);
2991 : 8 : break;
2992 : 3683 : default:
2993 : 3683 : errcontext("SQL statement \"%s\"", query);
2994 : 3683 : break;
2995 : : }
2996 : : }
2997 : : }
2998 : :
2999 : : /*
3000 : : * _SPI_cursor_operation()
3001 : : *
3002 : : * Do a FETCH or MOVE in a cursor
3003 : : */
3004 : : static void
3005 : 29894 : _SPI_cursor_operation(Portal portal, FetchDirection direction, long count,
3006 : : DestReceiver *dest)
3007 : : {
3008 : : uint64 nfetched;
3009 : :
3010 : : /* Check that the portal is valid */
3011 [ - + ]: 29894 : if (!PortalIsValid(portal))
3012 [ # # ]: 0 : elog(ERROR, "invalid portal in SPI cursor operation");
3013 : :
3014 : : /* Push the SPI stack */
3015 [ - + ]: 29894 : if (_SPI_begin_call(true) < 0)
3016 [ # # ]: 0 : elog(ERROR, "SPI cursor operation called while not connected");
3017 : :
3018 : : /* Reset the SPI result (note we deliberately don't touch lastoid) */
3019 : 29894 : SPI_processed = 0;
3020 : 29894 : SPI_tuptable = NULL;
3021 : 29894 : _SPI_current->processed = 0;
3022 : 29894 : _SPI_current->tuptable = NULL;
3023 : :
3024 : : /* Run the cursor */
3025 : 29894 : nfetched = PortalRunFetch(portal,
3026 : : direction,
3027 : : count,
3028 : : dest);
3029 : :
3030 : : /*
3031 : : * Think not to combine this store with the preceding function call. If
3032 : : * the portal contains calls to functions that use SPI, then _SPI_stack is
3033 : : * likely to move around while the portal runs. When control returns,
3034 : : * _SPI_current will point to the correct stack entry... but the pointer
3035 : : * may be different than it was beforehand. So we must be sure to re-fetch
3036 : : * the pointer after the function call completes.
3037 : : */
3038 : 29885 : _SPI_current->processed = nfetched;
3039 : :
3040 [ + + - + ]: 29885 : if (dest->mydest == DestSPI && _SPI_checktuples())
3041 [ # # ]: 0 : elog(ERROR, "consistency check on SPI tuple count failed");
3042 : :
3043 : : /* Put the result into place for access by caller */
3044 : 29885 : SPI_processed = _SPI_current->processed;
3045 : 29885 : SPI_tuptable = _SPI_current->tuptable;
3046 : :
3047 : : /* tuptable now is caller's responsibility, not SPI's */
3048 : 29885 : _SPI_current->tuptable = NULL;
3049 : :
3050 : : /* Pop the SPI stack */
3051 : 29885 : _SPI_end_call(true);
3052 : 29885 : }
3053 : :
3054 : :
3055 : : static MemoryContext
3056 : 134165 : _SPI_execmem(void)
3057 : : {
3058 : 134165 : return MemoryContextSwitchTo(_SPI_current->execCxt);
3059 : : }
3060 : :
3061 : : static MemoryContext
3062 : 191493 : _SPI_procmem(void)
3063 : : {
3064 : 191493 : return MemoryContextSwitchTo(_SPI_current->procCxt);
3065 : : }
3066 : :
3067 : : /*
3068 : : * _SPI_begin_call: begin a SPI operation within a connected procedure
3069 : : *
3070 : : * use_exec is true if we intend to make use of the procedure's execCxt
3071 : : * during this SPI operation. We'll switch into that context, and arrange
3072 : : * for it to be cleaned up at _SPI_end_call or if an error occurs.
3073 : : */
3074 : : static int
3075 : 201437 : _SPI_begin_call(bool use_exec)
3076 : : {
3077 [ - + ]: 201437 : if (_SPI_current == NULL)
3078 : 0 : return SPI_ERROR_UNCONNECTED;
3079 : :
3080 [ + + ]: 201437 : if (use_exec)
3081 : : {
3082 : : /* remember when the Executor operation started */
3083 : 134165 : _SPI_current->execSubid = GetCurrentSubTransactionId();
3084 : : /* switch to the Executor memory context */
3085 : 134165 : _SPI_execmem();
3086 : : }
3087 : :
3088 : 201437 : return 0;
3089 : : }
3090 : :
3091 : : /*
3092 : : * _SPI_end_call: end a SPI operation within a connected procedure
3093 : : *
3094 : : * use_exec must be the same as in the previous _SPI_begin_call
3095 : : *
3096 : : * Note: this currently has no failure return cases, so callers don't check
3097 : : */
3098 : : static int
3099 : 131386 : _SPI_end_call(bool use_exec)
3100 : : {
3101 [ + + ]: 131386 : if (use_exec)
3102 : : {
3103 : : /* switch to the procedure memory context */
3104 : 130836 : _SPI_procmem();
3105 : : /* mark Executor context no longer in use */
3106 : 130836 : _SPI_current->execSubid = InvalidSubTransactionId;
3107 : : /* and free Executor memory */
3108 : 130836 : MemoryContextReset(_SPI_current->execCxt);
3109 : : }
3110 : :
3111 : 131386 : return 0;
3112 : : }
3113 : :
3114 : : static bool
3115 : 56427 : _SPI_checktuples(void)
3116 : : {
3117 : 56427 : uint64 processed = _SPI_current->processed;
3118 : 56427 : SPITupleTable *tuptable = _SPI_current->tuptable;
3119 : 56427 : bool failed = false;
3120 : :
3121 [ - + ]: 56427 : if (tuptable == NULL) /* spi_dest_startup was not called */
3122 : 0 : failed = true;
3123 [ - + ]: 56427 : else if (processed != tuptable->numvals)
3124 : 0 : failed = true;
3125 : :
3126 : 56427 : return failed;
3127 : : }
3128 : :
3129 : : /*
3130 : : * Convert a "temporary" SPIPlan into an "unsaved" plan.
3131 : : *
3132 : : * The passed _SPI_plan struct is on the stack, and all its subsidiary data
3133 : : * is in or under the current SPI executor context. Copy the plan into the
3134 : : * SPI procedure context so it will survive _SPI_end_call(). To minimize
3135 : : * data copying, this destructively modifies the input plan, by taking the
3136 : : * plancache entries away from it and reparenting them to the new SPIPlan.
3137 : : */
3138 : : static SPIPlanPtr
3139 : 20652 : _SPI_make_plan_non_temp(SPIPlanPtr plan)
3140 : : {
3141 : : SPIPlanPtr newplan;
3142 : 20652 : MemoryContext parentcxt = _SPI_current->procCxt;
3143 : : MemoryContext plancxt;
3144 : : MemoryContext oldcxt;
3145 : : ListCell *lc;
3146 : :
3147 : : /* Assert the input is a temporary SPIPlan */
3148 : : Assert(plan->magic == _SPI_PLAN_MAGIC);
3149 : : Assert(plan->plancxt == NULL);
3150 : : /* One-shot plans can't be saved */
3151 : : Assert(!plan->oneshot);
3152 : :
3153 : : /*
3154 : : * Create a memory context for the plan, underneath the procedure context.
3155 : : * We don't expect the plan to be very large.
3156 : : */
3157 : 20652 : plancxt = AllocSetContextCreate(parentcxt,
3158 : : "SPI Plan",
3159 : : ALLOCSET_SMALL_SIZES);
3160 : 20652 : oldcxt = MemoryContextSwitchTo(plancxt);
3161 : :
3162 : : /* Copy the _SPI_plan struct and subsidiary data into the new context */
3163 : 20652 : newplan = palloc0_object(_SPI_plan);
3164 : 20652 : newplan->magic = _SPI_PLAN_MAGIC;
3165 : 20652 : newplan->plancxt = plancxt;
3166 : 20652 : newplan->parse_mode = plan->parse_mode;
3167 : 20652 : newplan->cursor_options = plan->cursor_options;
3168 : 20652 : newplan->nargs = plan->nargs;
3169 [ + + ]: 20652 : if (plan->nargs > 0)
3170 : : {
3171 : : Oid *newplan_argtypes;
3172 : :
3173 : 1385 : newplan_argtypes = palloc_array(Oid, plan->nargs);
3174 : 1385 : memcpy(newplan_argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
3175 : 1385 : newplan->argtypes = newplan_argtypes;
3176 : : }
3177 : : else
3178 : 19267 : newplan->argtypes = NULL;
3179 : 20652 : newplan->parserSetup = plan->parserSetup;
3180 : 20652 : newplan->parserSetupArg = plan->parserSetupArg;
3181 : :
3182 : : /*
3183 : : * Reparent all the CachedPlanSources into the procedure context. In
3184 : : * theory this could fail partway through due to the pallocs, but we don't
3185 : : * care too much since both the procedure context and the executor context
3186 : : * would go away on error.
3187 : : */
3188 [ + - + + : 41304 : foreach(lc, plan->plancache_list)
+ + ]
3189 : : {
3190 : 20652 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
3191 : :
3192 : 20652 : CachedPlanSetParentContext(plansource, parentcxt);
3193 : :
3194 : : /* Build new list, with list cells in plancxt */
3195 : 20652 : newplan->plancache_list = lappend(newplan->plancache_list, plansource);
3196 : : }
3197 : :
3198 : 20652 : MemoryContextSwitchTo(oldcxt);
3199 : :
3200 : : /* For safety, unlink the CachedPlanSources from the temporary plan */
3201 : 20652 : plan->plancache_list = NIL;
3202 : :
3203 : 20652 : return newplan;
3204 : : }
3205 : :
3206 : : /*
3207 : : * Make a "saved" copy of the given plan.
3208 : : */
3209 : : static SPIPlanPtr
3210 : 0 : _SPI_save_plan(SPIPlanPtr plan)
3211 : : {
3212 : : SPIPlanPtr newplan;
3213 : : MemoryContext plancxt;
3214 : : MemoryContext oldcxt;
3215 : : ListCell *lc;
3216 : :
3217 : : /* One-shot plans can't be saved */
3218 : : Assert(!plan->oneshot);
3219 : :
3220 : : /*
3221 : : * Create a memory context for the plan. We don't expect the plan to be
3222 : : * very large, so use smaller-than-default alloc parameters. It's a
3223 : : * transient context until we finish copying everything.
3224 : : */
3225 : 0 : plancxt = AllocSetContextCreate(CurrentMemoryContext,
3226 : : "SPI Plan",
3227 : : ALLOCSET_SMALL_SIZES);
3228 : 0 : oldcxt = MemoryContextSwitchTo(plancxt);
3229 : :
3230 : : /* Copy the SPI plan into its own context */
3231 : 0 : newplan = palloc0_object(_SPI_plan);
3232 : 0 : newplan->magic = _SPI_PLAN_MAGIC;
3233 : 0 : newplan->plancxt = plancxt;
3234 : 0 : newplan->parse_mode = plan->parse_mode;
3235 : 0 : newplan->cursor_options = plan->cursor_options;
3236 : 0 : newplan->nargs = plan->nargs;
3237 [ # # ]: 0 : if (plan->nargs > 0)
3238 : : {
3239 : : Oid *newplan_argtypes;
3240 : :
3241 : 0 : newplan_argtypes = palloc_array(Oid, plan->nargs);
3242 : 0 : memcpy(newplan_argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
3243 : 0 : newplan->argtypes = newplan_argtypes;
3244 : : }
3245 : : else
3246 : 0 : newplan->argtypes = NULL;
3247 : 0 : newplan->parserSetup = plan->parserSetup;
3248 : 0 : newplan->parserSetupArg = plan->parserSetupArg;
3249 : :
3250 : : /* Copy all the plancache entries */
3251 [ # # # # : 0 : foreach(lc, plan->plancache_list)
# # ]
3252 : : {
3253 : 0 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
3254 : : CachedPlanSource *newsource;
3255 : :
3256 : 0 : newsource = CopyCachedPlan(plansource);
3257 : 0 : newplan->plancache_list = lappend(newplan->plancache_list, newsource);
3258 : : }
3259 : :
3260 : 0 : MemoryContextSwitchTo(oldcxt);
3261 : :
3262 : : /*
3263 : : * Mark it saved, reparent it under CacheMemoryContext, and mark all the
3264 : : * component CachedPlanSources as saved. This sequence cannot fail
3265 : : * partway through, so there's no risk of long-term memory leakage.
3266 : : */
3267 : 0 : newplan->saved = true;
3268 : 0 : MemoryContextSetParent(newplan->plancxt, CacheMemoryContext);
3269 : :
3270 [ # # # # : 0 : foreach(lc, newplan->plancache_list)
# # ]
3271 : : {
3272 : 0 : CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
3273 : :
3274 : 0 : SaveCachedPlan(plansource);
3275 : : }
3276 : :
3277 : 0 : return newplan;
3278 : : }
3279 : :
3280 : : /*
3281 : : * Internal lookup of ephemeral named relation by name.
3282 : : */
3283 : : static EphemeralNamedRelation
3284 : 550 : _SPI_find_ENR_by_name(const char *name)
3285 : : {
3286 : : /* internal static function; any error is bug in SPI itself */
3287 : : Assert(name != NULL);
3288 : :
3289 : : /* fast exit if no tuplestores have been added */
3290 [ + + ]: 550 : if (_SPI_current->queryEnv == NULL)
3291 : 435 : return NULL;
3292 : :
3293 : 115 : return get_ENR(_SPI_current->queryEnv, name);
3294 : : }
3295 : :
3296 : : /*
3297 : : * Register an ephemeral named relation for use by the planner and executor on
3298 : : * subsequent calls using this SPI connection.
3299 : : */
3300 : : int
3301 : 550 : SPI_register_relation(EphemeralNamedRelation enr)
3302 : : {
3303 : : EphemeralNamedRelation match;
3304 : : int res;
3305 : :
3306 [ + - - + ]: 550 : if (enr == NULL || enr->md.name == NULL)
3307 : 0 : return SPI_ERROR_ARGUMENT;
3308 : :
3309 : 550 : res = _SPI_begin_call(false); /* keep current memory context */
3310 [ - + ]: 550 : if (res < 0)
3311 : 0 : return res;
3312 : :
3313 : 550 : match = _SPI_find_ENR_by_name(enr->md.name);
3314 [ - + ]: 550 : if (match)
3315 : 0 : res = SPI_ERROR_REL_DUPLICATE;
3316 : : else
3317 : : {
3318 [ + + ]: 550 : if (_SPI_current->queryEnv == NULL)
3319 : 435 : _SPI_current->queryEnv = create_queryEnv();
3320 : :
3321 : 550 : register_ENR(_SPI_current->queryEnv, enr);
3322 : 550 : res = SPI_OK_REL_REGISTER;
3323 : : }
3324 : :
3325 : 550 : _SPI_end_call(false);
3326 : :
3327 : 550 : return res;
3328 : : }
3329 : :
3330 : : /*
3331 : : * Unregister an ephemeral named relation by name. This will probably be a
3332 : : * rarely used function, since SPI_finish will clear it automatically.
3333 : : */
3334 : : int
3335 : 0 : SPI_unregister_relation(const char *name)
3336 : : {
3337 : : EphemeralNamedRelation match;
3338 : : int res;
3339 : :
3340 [ # # ]: 0 : if (name == NULL)
3341 : 0 : return SPI_ERROR_ARGUMENT;
3342 : :
3343 : 0 : res = _SPI_begin_call(false); /* keep current memory context */
3344 [ # # ]: 0 : if (res < 0)
3345 : 0 : return res;
3346 : :
3347 : 0 : match = _SPI_find_ENR_by_name(name);
3348 [ # # ]: 0 : if (match)
3349 : : {
3350 : 0 : unregister_ENR(_SPI_current->queryEnv, match->md.name);
3351 : 0 : res = SPI_OK_REL_UNREGISTER;
3352 : : }
3353 : : else
3354 : 0 : res = SPI_ERROR_REL_NOT_FOUND;
3355 : :
3356 : 0 : _SPI_end_call(false);
3357 : :
3358 : 0 : return res;
3359 : : }
3360 : :
3361 : : /*
3362 : : * Register the transient relations from 'tdata' using this SPI connection.
3363 : : * This should be called by PL implementations' trigger handlers after
3364 : : * connecting, in order to make transition tables visible to any queries run
3365 : : * in this connection.
3366 : : */
3367 : : int
3368 : 10788 : SPI_register_trigger_data(TriggerData *tdata)
3369 : : {
3370 [ - + ]: 10788 : if (tdata == NULL)
3371 : 0 : return SPI_ERROR_ARGUMENT;
3372 : :
3373 [ + + ]: 10788 : if (tdata->tg_newtable)
3374 : : {
3375 : : EphemeralNamedRelation enr =
3376 : 319 : palloc_object(EphemeralNamedRelationData);
3377 : : int rc;
3378 : :
3379 : 319 : enr->md.name = tdata->tg_trigger->tgnewtable;
3380 : 319 : enr->md.reliddesc = tdata->tg_relation->rd_id;
3381 : 319 : enr->md.tupdesc = NULL;
3382 : 319 : enr->md.enrtype = ENR_NAMED_TUPLESTORE;
3383 : 319 : enr->md.enrtuples = tuplestore_tuple_count(tdata->tg_newtable);
3384 : 319 : enr->reldata = tdata->tg_newtable;
3385 : 319 : rc = SPI_register_relation(enr);
3386 [ - + ]: 319 : if (rc != SPI_OK_REL_REGISTER)
3387 : 0 : return rc;
3388 : : }
3389 : :
3390 [ + + ]: 10788 : if (tdata->tg_oldtable)
3391 : : {
3392 : : EphemeralNamedRelation enr =
3393 : 231 : palloc_object(EphemeralNamedRelationData);
3394 : : int rc;
3395 : :
3396 : 231 : enr->md.name = tdata->tg_trigger->tgoldtable;
3397 : 231 : enr->md.reliddesc = tdata->tg_relation->rd_id;
3398 : 231 : enr->md.tupdesc = NULL;
3399 : 231 : enr->md.enrtype = ENR_NAMED_TUPLESTORE;
3400 : 231 : enr->md.enrtuples = tuplestore_tuple_count(tdata->tg_oldtable);
3401 : 231 : enr->reldata = tdata->tg_oldtable;
3402 : 231 : rc = SPI_register_relation(enr);
3403 [ - + ]: 231 : if (rc != SPI_OK_REL_REGISTER)
3404 : 0 : return rc;
3405 : : }
3406 : :
3407 : 10788 : return SPI_OK_TD_REGISTER;
3408 : : }
|