PostgreSQL Source Code  git master
spi.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * spi.c
4  * Server Programming Interface
5  *
6  * Portions Copyright (c) 1996-2018, 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 "miscadmin.h"
27 #include "tcop/pquery.h"
28 #include "tcop/utility.h"
29 #include "utils/builtins.h"
30 #include "utils/datum.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/rel.h"
34 #include "utils/snapmgr.h"
35 #include "utils/syscache.h"
36 #include "utils/typcache.h"
37 
38 
39 uint64 SPI_processed = 0;
43 
44 static _SPI_connection *_SPI_stack = NULL;
46 static int _SPI_stack_depth = 0; /* allocated size of _SPI_stack */
47 static int _SPI_connected = -1; /* current stack index */
48 
49 static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan,
50  ParamListInfo paramLI, bool read_only);
51 
52 static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan);
53 
54 static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan);
55 
56 static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI,
57  Snapshot snapshot, Snapshot crosscheck_snapshot,
58  bool read_only, bool fire_triggers, uint64 tcount);
59 
60 static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes,
61  Datum *Values, const char *Nulls);
62 
63 static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount);
64 
65 static void _SPI_error_callback(void *arg);
66 
67 static void _SPI_cursor_operation(Portal portal,
68  FetchDirection direction, long count,
70 
73 
74 static int _SPI_begin_call(bool use_exec);
75 static int _SPI_end_call(bool use_exec);
76 static MemoryContext _SPI_execmem(void);
77 static MemoryContext _SPI_procmem(void);
78 static bool _SPI_checktuples(void);
79 
80 
81 /* =================== interface functions =================== */
82 
83 int
85 {
86  return SPI_connect_ext(0);
87 }
88 
89 int
91 {
92  int newdepth;
93 
94  /* Enlarge stack if necessary */
95  if (_SPI_stack == NULL)
96  {
97  if (_SPI_connected != -1 || _SPI_stack_depth != 0)
98  elog(ERROR, "SPI stack corrupted");
99  newdepth = 16;
100  _SPI_stack = (_SPI_connection *)
102  newdepth * sizeof(_SPI_connection));
103  _SPI_stack_depth = newdepth;
104  }
105  else
106  {
108  elog(ERROR, "SPI stack corrupted");
109  if (_SPI_stack_depth == _SPI_connected + 1)
110  {
111  newdepth = _SPI_stack_depth * 2;
112  _SPI_stack = (_SPI_connection *)
113  repalloc(_SPI_stack,
114  newdepth * sizeof(_SPI_connection));
115  _SPI_stack_depth = newdepth;
116  }
117  }
118 
119  /* Enter new stack level */
120  _SPI_connected++;
122 
123  _SPI_current = &(_SPI_stack[_SPI_connected]);
124  _SPI_current->processed = 0;
125  _SPI_current->lastoid = InvalidOid;
126  _SPI_current->tuptable = NULL;
127  _SPI_current->execSubid = InvalidSubTransactionId;
128  slist_init(&_SPI_current->tuptables);
129  _SPI_current->procCxt = NULL; /* in case we fail to create 'em */
130  _SPI_current->execCxt = NULL;
131  _SPI_current->connectSubid = GetCurrentSubTransactionId();
132  _SPI_current->queryEnv = NULL;
133  _SPI_current->atomic = (options & SPI_OPT_NONATOMIC ? false : true);
134  _SPI_current->internal_xact = false;
135 
136  /*
137  * Create memory contexts for this procedure
138  *
139  * In atomic contexts (the normal case), we use TopTransactionContext,
140  * otherwise PortalContext, so that it lives across transaction
141  * boundaries.
142  *
143  * XXX It could be better to use PortalContext as the parent context in
144  * all cases, but we may not be inside a portal (consider deferred-trigger
145  * execution). Perhaps CurTransactionContext could be an option? For now
146  * it doesn't matter because we clean up explicitly in AtEOSubXact_SPI().
147  */
148  _SPI_current->procCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : PortalContext,
149  "SPI Proc",
151  _SPI_current->execCxt = AllocSetContextCreate(_SPI_current->atomic ? TopTransactionContext : _SPI_current->procCxt,
152  "SPI Exec",
154  /* ... and switch to procedure's context */
155  _SPI_current->savedcxt = MemoryContextSwitchTo(_SPI_current->procCxt);
156 
157  return SPI_OK_CONNECT;
158 }
159 
160 int
162 {
163  int res;
164 
165  res = _SPI_begin_call(false); /* just check we're connected */
166  if (res < 0)
167  return res;
168 
169  /* Restore memory context as it was before procedure call */
170  MemoryContextSwitchTo(_SPI_current->savedcxt);
171 
172  /* Release memory used in procedure call (including tuptables) */
173  MemoryContextDelete(_SPI_current->execCxt);
174  _SPI_current->execCxt = NULL;
175  MemoryContextDelete(_SPI_current->procCxt);
176  _SPI_current->procCxt = NULL;
177 
178  /*
179  * Reset result variables, especially SPI_tuptable which is probably
180  * pointing at a just-deleted tuptable
181  */
182  SPI_processed = 0;
184  SPI_tuptable = NULL;
185 
186  /* Exit stack level */
187  _SPI_connected--;
188  if (_SPI_connected < 0)
189  _SPI_current = NULL;
190  else
191  _SPI_current = &(_SPI_stack[_SPI_connected]);
192 
193  return SPI_OK_FINISH;
194 }
195 
196 void
198 {
199  MemoryContext oldcontext = CurrentMemoryContext;
200 
202  MemoryContextSwitchTo(oldcontext);
203 }
204 
205 void
207 {
208  MemoryContext oldcontext = CurrentMemoryContext;
209 
210  if (_SPI_current->atomic)
211  ereport(ERROR,
212  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
213  errmsg("invalid transaction termination")));
214 
215  /*
216  * This restriction is required by PLs implemented on top of SPI. They
217  * use subtransactions to establish exception blocks that are supposed to
218  * be rolled back together if there is an error. Terminating the
219  * top-level transaction in such a block violates that idea. A future PL
220  * implementation might have different ideas about this, in which case
221  * this restriction would have to be refined or the check possibly be
222  * moved out of SPI into the PLs.
223  */
224  if (IsSubTransaction())
225  ereport(ERROR,
226  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
227  errmsg("cannot commit while a subtransaction is active")));
228 
229  _SPI_current->internal_xact = true;
230 
231  if (ActiveSnapshotSet())
234  MemoryContextSwitchTo(oldcontext);
235 
236  _SPI_current->internal_xact = false;
237 }
238 
239 void
241 {
242  MemoryContext oldcontext = CurrentMemoryContext;
243 
244  if (_SPI_current->atomic)
245  ereport(ERROR,
246  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
247  errmsg("invalid transaction termination")));
248 
249  /* see under SPI_commit() */
250  if (IsSubTransaction())
251  ereport(ERROR,
252  (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
253  errmsg("cannot roll back while a subtransaction is active")));
254 
255  _SPI_current->internal_xact = true;
256 
258  MemoryContextSwitchTo(oldcontext);
259 
260  _SPI_current->internal_xact = false;
261 }
262 
263 /*
264  * Clean up SPI state at transaction commit or abort.
265  */
266 void
267 AtEOXact_SPI(bool isCommit)
268 {
269  /*
270  * Do nothing if the transaction end was initiated by SPI.
271  */
272  if (_SPI_current && _SPI_current->internal_xact)
273  return;
274 
275  /*
276  * Note that memory contexts belonging to SPI stack entries will be freed
277  * automatically, so we can ignore them here. We just need to restore our
278  * static variables to initial state.
279  */
280  if (isCommit && _SPI_connected != -1)
282  (errcode(ERRCODE_WARNING),
283  errmsg("transaction left non-empty SPI stack"),
284  errhint("Check for missing \"SPI_finish\" calls.")));
285 
286  _SPI_current = _SPI_stack = NULL;
287  _SPI_stack_depth = 0;
288  _SPI_connected = -1;
289  SPI_processed = 0;
291  SPI_tuptable = NULL;
292 }
293 
294 /*
295  * Clean up SPI state at subtransaction commit or abort.
296  *
297  * During commit, there shouldn't be any unclosed entries remaining from
298  * the current subtransaction; we emit a warning if any are found.
299  */
300 void
301 AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
302 {
303  bool found = false;
304 
305  while (_SPI_connected >= 0)
306  {
307  _SPI_connection *connection = &(_SPI_stack[_SPI_connected]);
308 
309  if (connection->connectSubid != mySubid)
310  break; /* couldn't be any underneath it either */
311 
312  if (connection->internal_xact)
313  break;
314 
315  found = true;
316 
317  /*
318  * Release procedure memory explicitly (see note in SPI_connect)
319  */
320  if (connection->execCxt)
321  {
322  MemoryContextDelete(connection->execCxt);
323  connection->execCxt = NULL;
324  }
325  if (connection->procCxt)
326  {
327  MemoryContextDelete(connection->procCxt);
328  connection->procCxt = NULL;
329  }
330 
331  /*
332  * Pop the stack entry and reset global variables. Unlike
333  * SPI_finish(), we don't risk switching to memory contexts that might
334  * be already gone.
335  */
336  _SPI_connected--;
337  if (_SPI_connected < 0)
338  _SPI_current = NULL;
339  else
340  _SPI_current = &(_SPI_stack[_SPI_connected]);
341  SPI_processed = 0;
343  SPI_tuptable = NULL;
344  }
345 
346  if (found && isCommit)
348  (errcode(ERRCODE_WARNING),
349  errmsg("subtransaction left non-empty SPI stack"),
350  errhint("Check for missing \"SPI_finish\" calls.")));
351 
352  /*
353  * If we are aborting a subtransaction and there is an open SPI context
354  * surrounding the subxact, clean up to prevent memory leakage.
355  */
356  if (_SPI_current && !isCommit)
357  {
358  slist_mutable_iter siter;
359 
360  /*
361  * Throw away executor state if current executor operation was started
362  * within current subxact (essentially, force a _SPI_end_call(true)).
363  */
364  if (_SPI_current->execSubid >= mySubid)
365  {
366  _SPI_current->execSubid = InvalidSubTransactionId;
368  }
369 
370  /* throw away any tuple tables created within current subxact */
371  slist_foreach_modify(siter, &_SPI_current->tuptables)
372  {
373  SPITupleTable *tuptable;
374 
375  tuptable = slist_container(SPITupleTable, next, siter.cur);
376  if (tuptable->subid >= mySubid)
377  {
378  /*
379  * If we used SPI_freetuptable() here, its internal search of
380  * the tuptables list would make this operation O(N^2).
381  * Instead, just free the tuptable manually. This should
382  * match what SPI_freetuptable() does.
383  */
384  slist_delete_current(&siter);
385  if (tuptable == _SPI_current->tuptable)
386  _SPI_current->tuptable = NULL;
387  if (tuptable == SPI_tuptable)
388  SPI_tuptable = NULL;
389  MemoryContextDelete(tuptable->tuptabcxt);
390  }
391  }
392  }
393 }
394 
395 
396 /* Parse, plan, and execute a query string */
397 int
398 SPI_execute(const char *src, bool read_only, long tcount)
399 {
400  _SPI_plan plan;
401  int res;
402 
403  if (src == NULL || tcount < 0)
404  return SPI_ERROR_ARGUMENT;
405 
406  res = _SPI_begin_call(true);
407  if (res < 0)
408  return res;
409 
410  memset(&plan, 0, sizeof(_SPI_plan));
411  plan.magic = _SPI_PLAN_MAGIC;
413 
414  _SPI_prepare_oneshot_plan(src, &plan);
415 
416  res = _SPI_execute_plan(&plan, NULL,
418  read_only, true, tcount);
419 
420  _SPI_end_call(true);
421  return res;
422 }
423 
424 /* Obsolete version of SPI_execute */
425 int
426 SPI_exec(const char *src, long tcount)
427 {
428  return SPI_execute(src, false, tcount);
429 }
430 
431 /* Execute a previously prepared plan */
432 int
433 SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls,
434  bool read_only, long tcount)
435 {
436  int res;
437 
438  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
439  return SPI_ERROR_ARGUMENT;
440 
441  if (plan->nargs > 0 && Values == NULL)
442  return SPI_ERROR_PARAM;
443 
444  res = _SPI_begin_call(true);
445  if (res < 0)
446  return res;
447 
448  res = _SPI_execute_plan(plan,
449  _SPI_convert_params(plan->nargs, plan->argtypes,
450  Values, Nulls),
452  read_only, true, tcount);
453 
454  _SPI_end_call(true);
455  return res;
456 }
457 
458 /* Obsolete version of SPI_execute_plan */
459 int
460 SPI_execp(SPIPlanPtr plan, Datum *Values, const char *Nulls, long tcount)
461 {
462  return SPI_execute_plan(plan, Values, Nulls, false, tcount);
463 }
464 
465 /* Execute a previously prepared plan */
466 int
468  bool read_only, long tcount)
469 {
470  int res;
471 
472  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
473  return SPI_ERROR_ARGUMENT;
474 
475  res = _SPI_begin_call(true);
476  if (res < 0)
477  return res;
478 
479  res = _SPI_execute_plan(plan, params,
481  read_only, true, tcount);
482 
483  _SPI_end_call(true);
484  return res;
485 }
486 
487 /*
488  * SPI_execute_snapshot -- identical to SPI_execute_plan, except that we allow
489  * the caller to specify exactly which snapshots to use, which will be
490  * registered here. Also, the caller may specify that AFTER triggers should be
491  * queued as part of the outer query rather than being fired immediately at the
492  * end of the command.
493  *
494  * This is currently not documented in spi.sgml because it is only intended
495  * for use by RI triggers.
496  *
497  * Passing snapshot == InvalidSnapshot will select the normal behavior of
498  * fetching a new snapshot for each query.
499  */
500 int
502  Datum *Values, const char *Nulls,
503  Snapshot snapshot, Snapshot crosscheck_snapshot,
504  bool read_only, bool fire_triggers, long tcount)
505 {
506  int res;
507 
508  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC || tcount < 0)
509  return SPI_ERROR_ARGUMENT;
510 
511  if (plan->nargs > 0 && Values == NULL)
512  return SPI_ERROR_PARAM;
513 
514  res = _SPI_begin_call(true);
515  if (res < 0)
516  return res;
517 
518  res = _SPI_execute_plan(plan,
519  _SPI_convert_params(plan->nargs, plan->argtypes,
520  Values, Nulls),
521  snapshot, crosscheck_snapshot,
522  read_only, fire_triggers, tcount);
523 
524  _SPI_end_call(true);
525  return res;
526 }
527 
528 /*
529  * SPI_execute_with_args -- plan and execute a query with supplied arguments
530  *
531  * This is functionally equivalent to SPI_prepare followed by
532  * SPI_execute_plan.
533  */
534 int
535 SPI_execute_with_args(const char *src,
536  int nargs, Oid *argtypes,
537  Datum *Values, const char *Nulls,
538  bool read_only, long tcount)
539 {
540  int res;
541  _SPI_plan plan;
542  ParamListInfo paramLI;
543 
544  if (src == NULL || nargs < 0 || tcount < 0)
545  return SPI_ERROR_ARGUMENT;
546 
547  if (nargs > 0 && (argtypes == NULL || Values == NULL))
548  return SPI_ERROR_PARAM;
549 
550  res = _SPI_begin_call(true);
551  if (res < 0)
552  return res;
553 
554  memset(&plan, 0, sizeof(_SPI_plan));
555  plan.magic = _SPI_PLAN_MAGIC;
557  plan.nargs = nargs;
558  plan.argtypes = argtypes;
559  plan.parserSetup = NULL;
560  plan.parserSetupArg = NULL;
561 
562  paramLI = _SPI_convert_params(nargs, argtypes,
563  Values, Nulls);
564 
565  _SPI_prepare_oneshot_plan(src, &plan);
566 
567  res = _SPI_execute_plan(&plan, paramLI,
569  read_only, true, tcount);
570 
571  _SPI_end_call(true);
572  return res;
573 }
574 
576 SPI_prepare(const char *src, int nargs, Oid *argtypes)
577 {
578  return SPI_prepare_cursor(src, nargs, argtypes, 0);
579 }
580 
582 SPI_prepare_cursor(const char *src, int nargs, Oid *argtypes,
583  int cursorOptions)
584 {
585  _SPI_plan plan;
586  SPIPlanPtr result;
587 
588  if (src == NULL || nargs < 0 || (nargs > 0 && argtypes == NULL))
589  {
591  return NULL;
592  }
593 
594  SPI_result = _SPI_begin_call(true);
595  if (SPI_result < 0)
596  return NULL;
597 
598  memset(&plan, 0, sizeof(_SPI_plan));
599  plan.magic = _SPI_PLAN_MAGIC;
600  plan.cursor_options = cursorOptions;
601  plan.nargs = nargs;
602  plan.argtypes = argtypes;
603  plan.parserSetup = NULL;
604  plan.parserSetupArg = NULL;
605 
606  _SPI_prepare_plan(src, &plan);
607 
608  /* copy plan to procedure context */
609  result = _SPI_make_plan_non_temp(&plan);
610 
611  _SPI_end_call(true);
612 
613  return result;
614 }
615 
617 SPI_prepare_params(const char *src,
618  ParserSetupHook parserSetup,
619  void *parserSetupArg,
620  int cursorOptions)
621 {
622  _SPI_plan plan;
623  SPIPlanPtr result;
624 
625  if (src == NULL)
626  {
628  return NULL;
629  }
630 
631  SPI_result = _SPI_begin_call(true);
632  if (SPI_result < 0)
633  return NULL;
634 
635  memset(&plan, 0, sizeof(_SPI_plan));
636  plan.magic = _SPI_PLAN_MAGIC;
637  plan.cursor_options = cursorOptions;
638  plan.nargs = 0;
639  plan.argtypes = NULL;
640  plan.parserSetup = parserSetup;
641  plan.parserSetupArg = parserSetupArg;
642 
643  _SPI_prepare_plan(src, &plan);
644 
645  /* copy plan to procedure context */
646  result = _SPI_make_plan_non_temp(&plan);
647 
648  _SPI_end_call(true);
649 
650  return result;
651 }
652 
653 int
655 {
656  ListCell *lc;
657 
658  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
659  plan->saved || plan->oneshot)
660  return SPI_ERROR_ARGUMENT;
661 
662  /*
663  * Mark it saved, reparent it under CacheMemoryContext, and mark all the
664  * component CachedPlanSources as saved. This sequence cannot fail
665  * partway through, so there's no risk of long-term memory leakage.
666  */
667  plan->saved = true;
669 
670  foreach(lc, plan->plancache_list)
671  {
672  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
673 
674  SaveCachedPlan(plansource);
675  }
676 
677  return 0;
678 }
679 
682 {
683  SPIPlanPtr newplan;
684 
685  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
686  {
688  return NULL;
689  }
690 
691  SPI_result = _SPI_begin_call(false); /* don't change context */
692  if (SPI_result < 0)
693  return NULL;
694 
695  newplan = _SPI_save_plan(plan);
696 
697  SPI_result = _SPI_end_call(false);
698 
699  return newplan;
700 }
701 
702 int
704 {
705  ListCell *lc;
706 
707  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
708  return SPI_ERROR_ARGUMENT;
709 
710  /* Release the plancache entries */
711  foreach(lc, plan->plancache_list)
712  {
713  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
714 
715  DropCachedPlan(plansource);
716  }
717 
718  /* Now get rid of the _SPI_plan and subsidiary data in its plancxt */
720 
721  return 0;
722 }
723 
724 HeapTuple
726 {
727  MemoryContext oldcxt;
728  HeapTuple ctuple;
729 
730  if (tuple == NULL)
731  {
733  return NULL;
734  }
735 
736  if (_SPI_current == NULL)
737  {
739  return NULL;
740  }
741 
742  oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
743 
744  ctuple = heap_copytuple(tuple);
745 
746  MemoryContextSwitchTo(oldcxt);
747 
748  return ctuple;
749 }
750 
753 {
754  MemoryContext oldcxt;
755  HeapTupleHeader dtup;
756 
757  if (tuple == NULL || tupdesc == NULL)
758  {
760  return NULL;
761  }
762 
763  if (_SPI_current == NULL)
764  {
766  return NULL;
767  }
768 
769  /* For RECORD results, make sure a typmod has been assigned */
770  if (tupdesc->tdtypeid == RECORDOID &&
771  tupdesc->tdtypmod < 0)
772  assign_record_type_typmod(tupdesc);
773 
774  oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
775 
776  dtup = DatumGetHeapTupleHeader(heap_copy_tuple_as_datum(tuple, tupdesc));
777 
778  MemoryContextSwitchTo(oldcxt);
779 
780  return dtup;
781 }
782 
783 HeapTuple
784 SPI_modifytuple(Relation rel, HeapTuple tuple, int natts, int *attnum,
785  Datum *Values, const char *Nulls)
786 {
787  MemoryContext oldcxt;
788  HeapTuple mtuple;
789  int numberOfAttributes;
790  Datum *v;
791  bool *n;
792  int i;
793 
794  if (rel == NULL || tuple == NULL || natts < 0 || attnum == NULL || Values == NULL)
795  {
797  return NULL;
798  }
799 
800  if (_SPI_current == NULL)
801  {
803  return NULL;
804  }
805 
806  oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
807 
808  SPI_result = 0;
809 
810  numberOfAttributes = rel->rd_att->natts;
811  v = (Datum *) palloc(numberOfAttributes * sizeof(Datum));
812  n = (bool *) palloc(numberOfAttributes * sizeof(bool));
813 
814  /* fetch old values and nulls */
815  heap_deform_tuple(tuple, rel->rd_att, v, n);
816 
817  /* replace values and nulls */
818  for (i = 0; i < natts; i++)
819  {
820  if (attnum[i] <= 0 || attnum[i] > numberOfAttributes)
821  break;
822  v[attnum[i] - 1] = Values[i];
823  n[attnum[i] - 1] = (Nulls && Nulls[i] == 'n') ? true : false;
824  }
825 
826  if (i == natts) /* no errors in *attnum */
827  {
828  mtuple = heap_form_tuple(rel->rd_att, v, n);
829 
830  /*
831  * copy the identification info of the old tuple: t_ctid, t_self, and
832  * OID (if any)
833  */
834  mtuple->t_data->t_ctid = tuple->t_data->t_ctid;
835  mtuple->t_self = tuple->t_self;
836  mtuple->t_tableOid = tuple->t_tableOid;
837  if (rel->rd_att->tdhasoid)
838  HeapTupleSetOid(mtuple, HeapTupleGetOid(tuple));
839  }
840  else
841  {
842  mtuple = NULL;
844  }
845 
846  pfree(v);
847  pfree(n);
848 
849  MemoryContextSwitchTo(oldcxt);
850 
851  return mtuple;
852 }
853 
854 int
855 SPI_fnumber(TupleDesc tupdesc, const char *fname)
856 {
857  int res;
858  Form_pg_attribute sysatt;
859 
860  for (res = 0; res < tupdesc->natts; res++)
861  {
862  Form_pg_attribute attr = TupleDescAttr(tupdesc, res);
863 
864  if (namestrcmp(&attr->attname, fname) == 0 &&
865  !attr->attisdropped)
866  return res + 1;
867  }
868 
869  sysatt = SystemAttributeByName(fname, true /* "oid" will be accepted */ );
870  if (sysatt != NULL)
871  return sysatt->attnum;
872 
873  /* SPI_ERROR_NOATTRIBUTE is different from all sys column numbers */
874  return SPI_ERROR_NOATTRIBUTE;
875 }
876 
877 char *
878 SPI_fname(TupleDesc tupdesc, int fnumber)
879 {
880  Form_pg_attribute att;
881 
882  SPI_result = 0;
883 
884  if (fnumber > tupdesc->natts || fnumber == 0 ||
886  {
888  return NULL;
889  }
890 
891  if (fnumber > 0)
892  att = TupleDescAttr(tupdesc, fnumber - 1);
893  else
894  att = SystemAttributeDefinition(fnumber, true);
895 
896  return pstrdup(NameStr(att->attname));
897 }
898 
899 char *
900 SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
901 {
902  Datum val;
903  bool isnull;
904  Oid typoid,
905  foutoid;
906  bool typisvarlena;
907 
908  SPI_result = 0;
909 
910  if (fnumber > tupdesc->natts || fnumber == 0 ||
912  {
914  return NULL;
915  }
916 
917  val = heap_getattr(tuple, fnumber, tupdesc, &isnull);
918  if (isnull)
919  return NULL;
920 
921  if (fnumber > 0)
922  typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
923  else
924  typoid = (SystemAttributeDefinition(fnumber, true))->atttypid;
925 
926  getTypeOutputInfo(typoid, &foutoid, &typisvarlena);
927 
928  return OidOutputFunctionCall(foutoid, val);
929 }
930 
931 Datum
932 SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
933 {
934  SPI_result = 0;
935 
936  if (fnumber > tupdesc->natts || fnumber == 0 ||
938  {
940  *isnull = true;
941  return (Datum) NULL;
942  }
943 
944  return heap_getattr(tuple, fnumber, tupdesc, isnull);
945 }
946 
947 char *
948 SPI_gettype(TupleDesc tupdesc, int fnumber)
949 {
950  Oid typoid;
951  HeapTuple typeTuple;
952  char *result;
953 
954  SPI_result = 0;
955 
956  if (fnumber > tupdesc->natts || fnumber == 0 ||
958  {
960  return NULL;
961  }
962 
963  if (fnumber > 0)
964  typoid = TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
965  else
966  typoid = (SystemAttributeDefinition(fnumber, true))->atttypid;
967 
968  typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typoid));
969 
970  if (!HeapTupleIsValid(typeTuple))
971  {
973  return NULL;
974  }
975 
976  result = pstrdup(NameStr(((Form_pg_type) GETSTRUCT(typeTuple))->typname));
977  ReleaseSysCache(typeTuple);
978  return result;
979 }
980 
981 /*
982  * Get the data type OID for a column.
983  *
984  * There's nothing similar for typmod and typcollation. The rare consumers
985  * thereof should inspect the TupleDesc directly.
986  */
987 Oid
988 SPI_gettypeid(TupleDesc tupdesc, int fnumber)
989 {
990  SPI_result = 0;
991 
992  if (fnumber > tupdesc->natts || fnumber == 0 ||
994  {
996  return InvalidOid;
997  }
998 
999  if (fnumber > 0)
1000  return TupleDescAttr(tupdesc, fnumber - 1)->atttypid;
1001  else
1002  return (SystemAttributeDefinition(fnumber, true))->atttypid;
1003 }
1004 
1005 char *
1007 {
1008  return pstrdup(RelationGetRelationName(rel));
1009 }
1010 
1011 char *
1013 {
1015 }
1016 
1017 void *
1019 {
1020  if (_SPI_current == NULL)
1021  elog(ERROR, "SPI_palloc called while not connected to SPI");
1022 
1023  return MemoryContextAlloc(_SPI_current->savedcxt, size);
1024 }
1025 
1026 void *
1027 SPI_repalloc(void *pointer, Size size)
1028 {
1029  /* No longer need to worry which context chunk was in... */
1030  return repalloc(pointer, size);
1031 }
1032 
1033 void
1034 SPI_pfree(void *pointer)
1035 {
1036  /* No longer need to worry which context chunk was in... */
1037  pfree(pointer);
1038 }
1039 
1040 Datum
1041 SPI_datumTransfer(Datum value, bool typByVal, int typLen)
1042 {
1043  MemoryContext oldcxt;
1044  Datum result;
1045 
1046  if (_SPI_current == NULL)
1047  elog(ERROR, "SPI_datumTransfer called while not connected to SPI");
1048 
1049  oldcxt = MemoryContextSwitchTo(_SPI_current->savedcxt);
1050 
1051  result = datumTransfer(value, typByVal, typLen);
1052 
1053  MemoryContextSwitchTo(oldcxt);
1054 
1055  return result;
1056 }
1057 
1058 void
1060 {
1061  /* No longer need to worry which context tuple was in... */
1062  heap_freetuple(tuple);
1063 }
1064 
1065 void
1067 {
1068  bool found = false;
1069 
1070  /* ignore call if NULL pointer */
1071  if (tuptable == NULL)
1072  return;
1073 
1074  /*
1075  * Search only the topmost SPI context for a matching tuple table.
1076  */
1077  if (_SPI_current != NULL)
1078  {
1079  slist_mutable_iter siter;
1080 
1081  /* find tuptable in active list, then remove it */
1082  slist_foreach_modify(siter, &_SPI_current->tuptables)
1083  {
1084  SPITupleTable *tt;
1085 
1086  tt = slist_container(SPITupleTable, next, siter.cur);
1087  if (tt == tuptable)
1088  {
1089  slist_delete_current(&siter);
1090  found = true;
1091  break;
1092  }
1093  }
1094  }
1095 
1096  /*
1097  * Refuse the deletion if we didn't find it in the topmost SPI context.
1098  * This is primarily a guard against double deletion, but might prevent
1099  * other errors as well. Since the worst consequence of not deleting a
1100  * tuptable would be a transient memory leak, this is just a WARNING.
1101  */
1102  if (!found)
1103  {
1104  elog(WARNING, "attempt to delete invalid SPITupleTable %p", tuptable);
1105  return;
1106  }
1107 
1108  /* for safety, reset global variables that might point at tuptable */
1109  if (tuptable == _SPI_current->tuptable)
1110  _SPI_current->tuptable = NULL;
1111  if (tuptable == SPI_tuptable)
1112  SPI_tuptable = NULL;
1113 
1114  /* release all memory belonging to tuptable */
1115  MemoryContextDelete(tuptable->tuptabcxt);
1116 }
1117 
1118 
1119 /*
1120  * SPI_cursor_open()
1121  *
1122  * Open a prepared SPI plan as a portal
1123  */
1124 Portal
1125 SPI_cursor_open(const char *name, SPIPlanPtr plan,
1126  Datum *Values, const char *Nulls,
1127  bool read_only)
1128 {
1129  Portal portal;
1130  ParamListInfo paramLI;
1131 
1132  /* build transient ParamListInfo in caller's context */
1133  paramLI = _SPI_convert_params(plan->nargs, plan->argtypes,
1134  Values, Nulls);
1135 
1136  portal = SPI_cursor_open_internal(name, plan, paramLI, read_only);
1137 
1138  /* done with the transient ParamListInfo */
1139  if (paramLI)
1140  pfree(paramLI);
1141 
1142  return portal;
1143 }
1144 
1145 
1146 /*
1147  * SPI_cursor_open_with_args()
1148  *
1149  * Parse and plan a query and open it as a portal.
1150  */
1151 Portal
1153  const char *src,
1154  int nargs, Oid *argtypes,
1155  Datum *Values, const char *Nulls,
1156  bool read_only, int cursorOptions)
1157 {
1158  Portal result;
1159  _SPI_plan plan;
1160  ParamListInfo paramLI;
1161 
1162  if (src == NULL || nargs < 0)
1163  elog(ERROR, "SPI_cursor_open_with_args called with invalid arguments");
1164 
1165  if (nargs > 0 && (argtypes == NULL || Values == NULL))
1166  elog(ERROR, "SPI_cursor_open_with_args called with missing parameters");
1167 
1168  SPI_result = _SPI_begin_call(true);
1169  if (SPI_result < 0)
1170  elog(ERROR, "SPI_cursor_open_with_args called while not connected");
1171 
1172  memset(&plan, 0, sizeof(_SPI_plan));
1173  plan.magic = _SPI_PLAN_MAGIC;
1174  plan.cursor_options = cursorOptions;
1175  plan.nargs = nargs;
1176  plan.argtypes = argtypes;
1177  plan.parserSetup = NULL;
1178  plan.parserSetupArg = NULL;
1179 
1180  /* build transient ParamListInfo in executor context */
1181  paramLI = _SPI_convert_params(nargs, argtypes,
1182  Values, Nulls);
1183 
1184  _SPI_prepare_plan(src, &plan);
1185 
1186  /* We needn't copy the plan; SPI_cursor_open_internal will do so */
1187 
1188  result = SPI_cursor_open_internal(name, &plan, paramLI, read_only);
1189 
1190  /* And clean up */
1191  _SPI_end_call(true);
1192 
1193  return result;
1194 }
1195 
1196 
1197 /*
1198  * SPI_cursor_open_with_paramlist()
1199  *
1200  * Same as SPI_cursor_open except that parameters (if any) are passed
1201  * as a ParamListInfo, which supports dynamic parameter set determination
1202  */
1203 Portal
1205  ParamListInfo params, bool read_only)
1206 {
1207  return SPI_cursor_open_internal(name, plan, params, read_only);
1208 }
1209 
1210 
1211 /*
1212  * SPI_cursor_open_internal()
1213  *
1214  * Common code for SPI_cursor_open variants
1215  */
1216 static Portal
1218  ParamListInfo paramLI, bool read_only)
1219 {
1220  CachedPlanSource *plansource;
1221  CachedPlan *cplan;
1222  List *stmt_list;
1223  char *query_string;
1224  Snapshot snapshot;
1225  MemoryContext oldcontext;
1226  Portal portal;
1227  ErrorContextCallback spierrcontext;
1228 
1229  /*
1230  * Check that the plan is something the Portal code will special-case as
1231  * returning one tupleset.
1232  */
1233  if (!SPI_is_cursor_plan(plan))
1234  {
1235  /* try to give a good error message */
1236  if (list_length(plan->plancache_list) != 1)
1237  ereport(ERROR,
1238  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1239  errmsg("cannot open multi-query plan as cursor")));
1240  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1241  ereport(ERROR,
1242  (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
1243  /* translator: %s is name of a SQL command, eg INSERT */
1244  errmsg("cannot open %s query as cursor",
1245  plansource->commandTag)));
1246  }
1247 
1248  Assert(list_length(plan->plancache_list) == 1);
1249  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1250 
1251  /* Push the SPI stack */
1252  if (_SPI_begin_call(true) < 0)
1253  elog(ERROR, "SPI_cursor_open called while not connected");
1254 
1255  /* Reset SPI result (note we deliberately don't touch lastoid) */
1256  SPI_processed = 0;
1257  SPI_tuptable = NULL;
1258  _SPI_current->processed = 0;
1259  _SPI_current->tuptable = NULL;
1260 
1261  /* Create the portal */
1262  if (name == NULL || name[0] == '\0')
1263  {
1264  /* Use a random nonconflicting name */
1265  portal = CreateNewPortal();
1266  }
1267  else
1268  {
1269  /* In this path, error if portal of same name already exists */
1270  portal = CreatePortal(name, false, false);
1271  }
1272 
1273  /* Copy the plan's query string into the portal */
1274  query_string = MemoryContextStrdup(portal->portalContext,
1275  plansource->query_string);
1276 
1277  /*
1278  * Setup error traceback support for ereport(), in case GetCachedPlan
1279  * throws an error.
1280  */
1281  spierrcontext.callback = _SPI_error_callback;
1282  spierrcontext.arg = (void *) plansource->query_string;
1283  spierrcontext.previous = error_context_stack;
1284  error_context_stack = &spierrcontext;
1285 
1286  /*
1287  * Note: for a saved plan, we mustn't have any failure occur between
1288  * GetCachedPlan and PortalDefineQuery; that would result in leaking our
1289  * plancache refcount.
1290  */
1291 
1292  /* Replan if needed, and increment plan refcount for portal */
1293  cplan = GetCachedPlan(plansource, paramLI, false, _SPI_current->queryEnv);
1294  stmt_list = cplan->stmt_list;
1295 
1296  if (!plan->saved)
1297  {
1298  /*
1299  * We don't want the portal to depend on an unsaved CachedPlanSource,
1300  * so must copy the plan into the portal's context. An error here
1301  * will result in leaking our refcount on the plan, but it doesn't
1302  * matter because the plan is unsaved and hence transient anyway.
1303  */
1304  oldcontext = MemoryContextSwitchTo(portal->portalContext);
1305  stmt_list = copyObject(stmt_list);
1306  MemoryContextSwitchTo(oldcontext);
1307  ReleaseCachedPlan(cplan, false);
1308  cplan = NULL; /* portal shouldn't depend on cplan */
1309  }
1310 
1311  /*
1312  * Set up the portal.
1313  */
1314  PortalDefineQuery(portal,
1315  NULL, /* no statement name */
1316  query_string,
1317  plansource->commandTag,
1318  stmt_list,
1319  cplan);
1320 
1321  /*
1322  * Set up options for portal. Default SCROLL type is chosen the same way
1323  * as PerformCursorOpen does it.
1324  */
1325  portal->cursorOptions = plan->cursor_options;
1327  {
1328  if (list_length(stmt_list) == 1 &&
1329  linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1330  linitial_node(PlannedStmt, stmt_list)->rowMarks == NIL &&
1331  ExecSupportsBackwardScan(linitial_node(PlannedStmt, stmt_list)->planTree))
1332  portal->cursorOptions |= CURSOR_OPT_SCROLL;
1333  else
1335  }
1336 
1337  /*
1338  * Disallow SCROLL with SELECT FOR UPDATE. This is not redundant with the
1339  * check in transformDeclareCursorStmt because the cursor options might
1340  * not have come through there.
1341  */
1342  if (portal->cursorOptions & CURSOR_OPT_SCROLL)
1343  {
1344  if (list_length(stmt_list) == 1 &&
1345  linitial_node(PlannedStmt, stmt_list)->commandType != CMD_UTILITY &&
1346  linitial_node(PlannedStmt, stmt_list)->rowMarks != NIL)
1347  ereport(ERROR,
1348  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1349  errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
1350  errdetail("Scrollable cursors must be READ ONLY.")));
1351  }
1352 
1353  /* Make current query environment available to portal at execution time. */
1354  portal->queryEnv = _SPI_current->queryEnv;
1355 
1356  /*
1357  * If told to be read-only, or in parallel mode, verify that this query is
1358  * in fact read-only. This can't be done earlier because we need to look
1359  * at the finished, planned queries. (In particular, we don't want to do
1360  * it between GetCachedPlan and PortalDefineQuery, because throwing an
1361  * error between those steps would result in leaking our plancache
1362  * refcount.)
1363  */
1364  if (read_only || IsInParallelMode())
1365  {
1366  ListCell *lc;
1367 
1368  foreach(lc, stmt_list)
1369  {
1370  PlannedStmt *pstmt = lfirst_node(PlannedStmt, lc);
1371 
1372  if (!CommandIsReadOnly(pstmt))
1373  {
1374  if (read_only)
1375  ereport(ERROR,
1376  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1377  /* translator: %s is a SQL statement name */
1378  errmsg("%s is not allowed in a non-volatile function",
1379  CreateCommandTag((Node *) pstmt))));
1380  else
1382  }
1383  }
1384  }
1385 
1386  /* Set up the snapshot to use. */
1387  if (read_only)
1388  snapshot = GetActiveSnapshot();
1389  else
1390  {
1392  snapshot = GetTransactionSnapshot();
1393  }
1394 
1395  /*
1396  * If the plan has parameters, copy them into the portal. Note that this
1397  * must be done after revalidating the plan, because in dynamic parameter
1398  * cases the set of parameters could have changed during re-parsing.
1399  */
1400  if (paramLI)
1401  {
1402  oldcontext = MemoryContextSwitchTo(portal->portalContext);
1403  paramLI = copyParamList(paramLI);
1404  MemoryContextSwitchTo(oldcontext);
1405  }
1406 
1407  /*
1408  * Start portal execution.
1409  */
1410  PortalStart(portal, paramLI, 0, snapshot);
1411 
1412  Assert(portal->strategy != PORTAL_MULTI_QUERY);
1413 
1414  /* Pop the error context stack */
1415  error_context_stack = spierrcontext.previous;
1416 
1417  /* Pop the SPI stack */
1418  _SPI_end_call(true);
1419 
1420  /* Return the created portal */
1421  return portal;
1422 }
1423 
1424 
1425 /*
1426  * SPI_cursor_find()
1427  *
1428  * Find the portal of an existing open cursor
1429  */
1430 Portal
1431 SPI_cursor_find(const char *name)
1432 {
1433  return GetPortalByName(name);
1434 }
1435 
1436 
1437 /*
1438  * SPI_cursor_fetch()
1439  *
1440  * Fetch rows in a cursor
1441  */
1442 void
1443 SPI_cursor_fetch(Portal portal, bool forward, long count)
1444 {
1445  _SPI_cursor_operation(portal,
1446  forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1448  /* we know that the DestSPI receiver doesn't need a destroy call */
1449 }
1450 
1451 
1452 /*
1453  * SPI_cursor_move()
1454  *
1455  * Move in a cursor
1456  */
1457 void
1458 SPI_cursor_move(Portal portal, bool forward, long count)
1459 {
1460  _SPI_cursor_operation(portal,
1461  forward ? FETCH_FORWARD : FETCH_BACKWARD, count,
1462  None_Receiver);
1463 }
1464 
1465 
1466 /*
1467  * SPI_scroll_cursor_fetch()
1468  *
1469  * Fetch rows in a scrollable cursor
1470  */
1471 void
1472 SPI_scroll_cursor_fetch(Portal portal, FetchDirection direction, long count)
1473 {
1474  _SPI_cursor_operation(portal,
1475  direction, count,
1477  /* we know that the DestSPI receiver doesn't need a destroy call */
1478 }
1479 
1480 
1481 /*
1482  * SPI_scroll_cursor_move()
1483  *
1484  * Move in a scrollable cursor
1485  */
1486 void
1487 SPI_scroll_cursor_move(Portal portal, FetchDirection direction, long count)
1488 {
1489  _SPI_cursor_operation(portal, direction, count, None_Receiver);
1490 }
1491 
1492 
1493 /*
1494  * SPI_cursor_close()
1495  *
1496  * Close a cursor
1497  */
1498 void
1500 {
1501  if (!PortalIsValid(portal))
1502  elog(ERROR, "invalid portal in SPI cursor operation");
1503 
1504  PortalDrop(portal, false);
1505 }
1506 
1507 /*
1508  * Returns the Oid representing the type id for argument at argIndex. First
1509  * parameter is at index zero.
1510  */
1511 Oid
1512 SPI_getargtypeid(SPIPlanPtr plan, int argIndex)
1513 {
1514  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC ||
1515  argIndex < 0 || argIndex >= plan->nargs)
1516  {
1518  return InvalidOid;
1519  }
1520  return plan->argtypes[argIndex];
1521 }
1522 
1523 /*
1524  * Returns the number of arguments for the prepared plan.
1525  */
1526 int
1528 {
1529  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1530  {
1532  return -1;
1533  }
1534  return plan->nargs;
1535 }
1536 
1537 /*
1538  * Returns true if the plan contains exactly one command
1539  * and that command returns tuples to the caller (eg, SELECT or
1540  * INSERT ... RETURNING, but not SELECT ... INTO). In essence,
1541  * the result indicates if the command can be used with SPI_cursor_open
1542  *
1543  * Parameters
1544  * plan: A plan previously prepared using SPI_prepare
1545  */
1546 bool
1548 {
1549  CachedPlanSource *plansource;
1550 
1551  if (plan == NULL || plan->magic != _SPI_PLAN_MAGIC)
1552  {
1554  return false;
1555  }
1556 
1557  if (list_length(plan->plancache_list) != 1)
1558  {
1559  SPI_result = 0;
1560  return false; /* not exactly 1 pre-rewrite command */
1561  }
1562  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1563 
1564  /*
1565  * We used to force revalidation of the cached plan here, but that seems
1566  * unnecessary: invalidation could mean a change in the rowtype of the
1567  * tuples returned by a plan, but not whether it returns tuples at all.
1568  */
1569  SPI_result = 0;
1570 
1571  /* Does it return tuples? */
1572  if (plansource->resultDesc)
1573  return true;
1574 
1575  return false;
1576 }
1577 
1578 /*
1579  * SPI_plan_is_valid --- test whether a SPI plan is currently valid
1580  * (that is, not marked as being in need of revalidation).
1581  *
1582  * See notes for CachedPlanIsValid before using this.
1583  */
1584 bool
1586 {
1587  ListCell *lc;
1588 
1589  Assert(plan->magic == _SPI_PLAN_MAGIC);
1590 
1591  foreach(lc, plan->plancache_list)
1592  {
1593  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
1594 
1595  if (!CachedPlanIsValid(plansource))
1596  return false;
1597  }
1598  return true;
1599 }
1600 
1601 /*
1602  * SPI_result_code_string --- convert any SPI return code to a string
1603  *
1604  * This is often useful in error messages. Most callers will probably
1605  * only pass negative (error-case) codes, but for generality we recognize
1606  * the success codes too.
1607  */
1608 const char *
1610 {
1611  static char buf[64];
1612 
1613  switch (code)
1614  {
1615  case SPI_ERROR_CONNECT:
1616  return "SPI_ERROR_CONNECT";
1617  case SPI_ERROR_COPY:
1618  return "SPI_ERROR_COPY";
1619  case SPI_ERROR_OPUNKNOWN:
1620  return "SPI_ERROR_OPUNKNOWN";
1621  case SPI_ERROR_UNCONNECTED:
1622  return "SPI_ERROR_UNCONNECTED";
1623  case SPI_ERROR_ARGUMENT:
1624  return "SPI_ERROR_ARGUMENT";
1625  case SPI_ERROR_PARAM:
1626  return "SPI_ERROR_PARAM";
1627  case SPI_ERROR_TRANSACTION:
1628  return "SPI_ERROR_TRANSACTION";
1629  case SPI_ERROR_NOATTRIBUTE:
1630  return "SPI_ERROR_NOATTRIBUTE";
1631  case SPI_ERROR_NOOUTFUNC:
1632  return "SPI_ERROR_NOOUTFUNC";
1633  case SPI_ERROR_TYPUNKNOWN:
1634  return "SPI_ERROR_TYPUNKNOWN";
1636  return "SPI_ERROR_REL_DUPLICATE";
1638  return "SPI_ERROR_REL_NOT_FOUND";
1639  case SPI_OK_CONNECT:
1640  return "SPI_OK_CONNECT";
1641  case SPI_OK_FINISH:
1642  return "SPI_OK_FINISH";
1643  case SPI_OK_FETCH:
1644  return "SPI_OK_FETCH";
1645  case SPI_OK_UTILITY:
1646  return "SPI_OK_UTILITY";
1647  case SPI_OK_SELECT:
1648  return "SPI_OK_SELECT";
1649  case SPI_OK_SELINTO:
1650  return "SPI_OK_SELINTO";
1651  case SPI_OK_INSERT:
1652  return "SPI_OK_INSERT";
1653  case SPI_OK_DELETE:
1654  return "SPI_OK_DELETE";
1655  case SPI_OK_UPDATE:
1656  return "SPI_OK_UPDATE";
1657  case SPI_OK_CURSOR:
1658  return "SPI_OK_CURSOR";
1660  return "SPI_OK_INSERT_RETURNING";
1662  return "SPI_OK_DELETE_RETURNING";
1664  return "SPI_OK_UPDATE_RETURNING";
1665  case SPI_OK_REWRITTEN:
1666  return "SPI_OK_REWRITTEN";
1667  case SPI_OK_REL_REGISTER:
1668  return "SPI_OK_REL_REGISTER";
1669  case SPI_OK_REL_UNREGISTER:
1670  return "SPI_OK_REL_UNREGISTER";
1671  }
1672  /* Unrecognized code ... return something useful ... */
1673  sprintf(buf, "Unrecognized SPI code %d", code);
1674  return buf;
1675 }
1676 
1677 /*
1678  * SPI_plan_get_plan_sources --- get a SPI plan's underlying list of
1679  * CachedPlanSources.
1680  *
1681  * This is exported so that PL/pgSQL can use it (this beats letting PL/pgSQL
1682  * look directly into the SPIPlan for itself). It's not documented in
1683  * spi.sgml because we'd just as soon not have too many places using this.
1684  */
1685 List *
1687 {
1688  Assert(plan->magic == _SPI_PLAN_MAGIC);
1689  return plan->plancache_list;
1690 }
1691 
1692 /*
1693  * SPI_plan_get_cached_plan --- get a SPI plan's generic CachedPlan,
1694  * if the SPI plan contains exactly one CachedPlanSource. If not,
1695  * return NULL. Caller is responsible for doing ReleaseCachedPlan().
1696  *
1697  * This is exported so that PL/pgSQL can use it (this beats letting PL/pgSQL
1698  * look directly into the SPIPlan for itself). It's not documented in
1699  * spi.sgml because we'd just as soon not have too many places using this.
1700  */
1701 CachedPlan *
1703 {
1704  CachedPlanSource *plansource;
1705  CachedPlan *cplan;
1706  ErrorContextCallback spierrcontext;
1707 
1708  Assert(plan->magic == _SPI_PLAN_MAGIC);
1709 
1710  /* Can't support one-shot plans here */
1711  if (plan->oneshot)
1712  return NULL;
1713 
1714  /* Must have exactly one CachedPlanSource */
1715  if (list_length(plan->plancache_list) != 1)
1716  return NULL;
1717  plansource = (CachedPlanSource *) linitial(plan->plancache_list);
1718 
1719  /* Setup error traceback support for ereport() */
1720  spierrcontext.callback = _SPI_error_callback;
1721  spierrcontext.arg = (void *) plansource->query_string;
1722  spierrcontext.previous = error_context_stack;
1723  error_context_stack = &spierrcontext;
1724 
1725  /* Get the generic plan for the query */
1726  cplan = GetCachedPlan(plansource, NULL, plan->saved,
1727  _SPI_current->queryEnv);
1728  Assert(cplan == plansource->gplan);
1729 
1730  /* Pop the error context stack */
1731  error_context_stack = spierrcontext.previous;
1732 
1733  return cplan;
1734 }
1735 
1736 
1737 /* =================== private functions =================== */
1738 
1739 /*
1740  * spi_dest_startup
1741  * Initialize to receive tuples from Executor into SPITupleTable
1742  * of current SPI procedure
1743  */
1744 void
1745 spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1746 {
1747  SPITupleTable *tuptable;
1748  MemoryContext oldcxt;
1749  MemoryContext tuptabcxt;
1750 
1751  if (_SPI_current == NULL)
1752  elog(ERROR, "spi_dest_startup called while not connected to SPI");
1753 
1754  if (_SPI_current->tuptable != NULL)
1755  elog(ERROR, "improper call to spi_dest_startup");
1756 
1757  /* We create the tuple table context as a child of procCxt */
1758 
1759  oldcxt = _SPI_procmem(); /* switch to procedure memory context */
1760 
1762  "SPI TupTable",
1764  MemoryContextSwitchTo(tuptabcxt);
1765 
1766  _SPI_current->tuptable = tuptable = (SPITupleTable *)
1767  palloc0(sizeof(SPITupleTable));
1768  tuptable->tuptabcxt = tuptabcxt;
1769  tuptable->subid = GetCurrentSubTransactionId();
1770 
1771  /*
1772  * The tuptable is now valid enough to be freed by AtEOSubXact_SPI, so put
1773  * it onto the SPI context's tuptables list. This will ensure it's not
1774  * leaked even in the unlikely event the following few lines fail.
1775  */
1776  slist_push_head(&_SPI_current->tuptables, &tuptable->next);
1777 
1778  /* set up initial allocations */
1779  tuptable->alloced = tuptable->free = 128;
1780  tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple));
1781  tuptable->tupdesc = CreateTupleDescCopy(typeinfo);
1782 
1783  MemoryContextSwitchTo(oldcxt);
1784 }
1785 
1786 /*
1787  * spi_printtup
1788  * store tuple retrieved by Executor into SPITupleTable
1789  * of current SPI procedure
1790  */
1791 bool
1793 {
1794  SPITupleTable *tuptable;
1795  MemoryContext oldcxt;
1796 
1797  if (_SPI_current == NULL)
1798  elog(ERROR, "spi_printtup called while not connected to SPI");
1799 
1800  tuptable = _SPI_current->tuptable;
1801  if (tuptable == NULL)
1802  elog(ERROR, "improper call to spi_printtup");
1803 
1804  oldcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
1805 
1806  if (tuptable->free == 0)
1807  {
1808  /* Double the size of the pointer array */
1809  tuptable->free = tuptable->alloced;
1810  tuptable->alloced += tuptable->free;
1811  tuptable->vals = (HeapTuple *) repalloc_huge(tuptable->vals,
1812  tuptable->alloced * sizeof(HeapTuple));
1813  }
1814 
1815  tuptable->vals[tuptable->alloced - tuptable->free] =
1816  ExecCopySlotTuple(slot);
1817  (tuptable->free)--;
1818 
1819  MemoryContextSwitchTo(oldcxt);
1820 
1821  return true;
1822 }
1823 
1824 /*
1825  * Static functions
1826  */
1827 
1828 /*
1829  * Parse and analyze a querystring.
1830  *
1831  * At entry, plan->argtypes and plan->nargs (or alternatively plan->parserSetup
1832  * and plan->parserSetupArg) must be valid, as must plan->cursor_options.
1833  *
1834  * Results are stored into *plan (specifically, plan->plancache_list).
1835  * Note that the result data is all in CurrentMemoryContext or child contexts
1836  * thereof; in practice this means it is in the SPI executor context, and
1837  * what we are creating is a "temporary" SPIPlan. Cruft generated during
1838  * parsing is also left in CurrentMemoryContext.
1839  */
1840 static void
1841 _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
1842 {
1843  List *raw_parsetree_list;
1844  List *plancache_list;
1845  ListCell *list_item;
1846  ErrorContextCallback spierrcontext;
1847 
1848  /*
1849  * Setup error traceback support for ereport()
1850  */
1851  spierrcontext.callback = _SPI_error_callback;
1852  spierrcontext.arg = (void *) src;
1853  spierrcontext.previous = error_context_stack;
1854  error_context_stack = &spierrcontext;
1855 
1856  /*
1857  * Parse the request string into a list of raw parse trees.
1858  */
1859  raw_parsetree_list = pg_parse_query(src);
1860 
1861  /*
1862  * Do parse analysis and rule rewrite for each raw parsetree, storing the
1863  * results into unsaved plancache entries.
1864  */
1865  plancache_list = NIL;
1866 
1867  foreach(list_item, raw_parsetree_list)
1868  {
1869  RawStmt *parsetree = lfirst_node(RawStmt, list_item);
1870  List *stmt_list;
1871  CachedPlanSource *plansource;
1872 
1873  /*
1874  * Create the CachedPlanSource before we do parse analysis, since it
1875  * needs to see the unmodified raw parse tree.
1876  */
1877  plansource = CreateCachedPlan(parsetree,
1878  src,
1879  CreateCommandTag(parsetree->stmt));
1880 
1881  /*
1882  * Parameter datatypes are driven by parserSetup hook if provided,
1883  * otherwise we use the fixed parameter list.
1884  */
1885  if (plan->parserSetup != NULL)
1886  {
1887  Assert(plan->nargs == 0);
1888  stmt_list = pg_analyze_and_rewrite_params(parsetree,
1889  src,
1890  plan->parserSetup,
1891  plan->parserSetupArg,
1892  _SPI_current->queryEnv);
1893  }
1894  else
1895  {
1896  stmt_list = pg_analyze_and_rewrite(parsetree,
1897  src,
1898  plan->argtypes,
1899  plan->nargs,
1900  _SPI_current->queryEnv);
1901  }
1902 
1903  /* Finish filling in the CachedPlanSource */
1904  CompleteCachedPlan(plansource,
1905  stmt_list,
1906  NULL,
1907  plan->argtypes,
1908  plan->nargs,
1909  plan->parserSetup,
1910  plan->parserSetupArg,
1911  plan->cursor_options,
1912  false); /* not fixed result */
1913 
1914  plancache_list = lappend(plancache_list, plansource);
1915  }
1916 
1917  plan->plancache_list = plancache_list;
1918  plan->oneshot = false;
1919 
1920  /*
1921  * Pop the error context stack
1922  */
1923  error_context_stack = spierrcontext.previous;
1924 }
1925 
1926 /*
1927  * Parse, but don't analyze, a querystring.
1928  *
1929  * This is a stripped-down version of _SPI_prepare_plan that only does the
1930  * initial raw parsing. It creates "one shot" CachedPlanSources
1931  * that still require parse analysis before execution is possible.
1932  *
1933  * The advantage of using the "one shot" form of CachedPlanSource is that
1934  * we eliminate data copying and invalidation overhead. Postponing parse
1935  * analysis also prevents issues if some of the raw parsetrees are DDL
1936  * commands that affect validity of later parsetrees. Both of these
1937  * attributes are good things for SPI_execute() and similar cases.
1938  *
1939  * Results are stored into *plan (specifically, plan->plancache_list).
1940  * Note that the result data is all in CurrentMemoryContext or child contexts
1941  * thereof; in practice this means it is in the SPI executor context, and
1942  * what we are creating is a "temporary" SPIPlan. Cruft generated during
1943  * parsing is also left in CurrentMemoryContext.
1944  */
1945 static void
1947 {
1948  List *raw_parsetree_list;
1949  List *plancache_list;
1950  ListCell *list_item;
1951  ErrorContextCallback spierrcontext;
1952 
1953  /*
1954  * Setup error traceback support for ereport()
1955  */
1956  spierrcontext.callback = _SPI_error_callback;
1957  spierrcontext.arg = (void *) src;
1958  spierrcontext.previous = error_context_stack;
1959  error_context_stack = &spierrcontext;
1960 
1961  /*
1962  * Parse the request string into a list of raw parse trees.
1963  */
1964  raw_parsetree_list = pg_parse_query(src);
1965 
1966  /*
1967  * Construct plancache entries, but don't do parse analysis yet.
1968  */
1969  plancache_list = NIL;
1970 
1971  foreach(list_item, raw_parsetree_list)
1972  {
1973  RawStmt *parsetree = lfirst_node(RawStmt, list_item);
1974  CachedPlanSource *plansource;
1975 
1976  plansource = CreateOneShotCachedPlan(parsetree,
1977  src,
1978  CreateCommandTag(parsetree->stmt));
1979 
1980  plancache_list = lappend(plancache_list, plansource);
1981  }
1982 
1983  plan->plancache_list = plancache_list;
1984  plan->oneshot = true;
1985 
1986  /*
1987  * Pop the error context stack
1988  */
1989  error_context_stack = spierrcontext.previous;
1990 }
1991 
1992 /*
1993  * Execute the given plan with the given parameter values
1994  *
1995  * snapshot: query snapshot to use, or InvalidSnapshot for the normal
1996  * behavior of taking a new snapshot for each query.
1997  * crosscheck_snapshot: for RI use, all others pass InvalidSnapshot
1998  * read_only: true for read-only execution (no CommandCounterIncrement)
1999  * fire_triggers: true to fire AFTER triggers at end of query (normal case);
2000  * false means any AFTER triggers are postponed to end of outer query
2001  * tcount: execution tuple-count limit, or 0 for none
2002  */
2003 static int
2005  Snapshot snapshot, Snapshot crosscheck_snapshot,
2006  bool read_only, bool fire_triggers, uint64 tcount)
2007 {
2008  int my_res = 0;
2009  uint64 my_processed = 0;
2010  Oid my_lastoid = InvalidOid;
2011  SPITupleTable *my_tuptable = NULL;
2012  int res = 0;
2013  bool pushed_active_snap = false;
2014  ErrorContextCallback spierrcontext;
2015  CachedPlan *cplan = NULL;
2016  ListCell *lc1;
2017 
2018  /*
2019  * Setup error traceback support for ereport()
2020  */
2021  spierrcontext.callback = _SPI_error_callback;
2022  spierrcontext.arg = NULL; /* we'll fill this below */
2023  spierrcontext.previous = error_context_stack;
2024  error_context_stack = &spierrcontext;
2025 
2026  /*
2027  * We support four distinct snapshot management behaviors:
2028  *
2029  * snapshot != InvalidSnapshot, read_only = true: use exactly the given
2030  * snapshot.
2031  *
2032  * snapshot != InvalidSnapshot, read_only = false: use the given snapshot,
2033  * modified by advancing its command ID before each querytree.
2034  *
2035  * snapshot == InvalidSnapshot, read_only = true: use the entry-time
2036  * ActiveSnapshot, if any (if there isn't one, we run with no snapshot).
2037  *
2038  * snapshot == InvalidSnapshot, read_only = false: take a full new
2039  * snapshot for each user command, and advance its command ID before each
2040  * querytree within the command.
2041  *
2042  * In the first two cases, we can just push the snap onto the stack once
2043  * for the whole plan list.
2044  *
2045  * But if the plan has no_snapshots set to true, then don't manage
2046  * snapshots at all. The caller should then take care of that.
2047  */
2048  if (snapshot != InvalidSnapshot && !plan->no_snapshots)
2049  {
2050  if (read_only)
2051  {
2052  PushActiveSnapshot(snapshot);
2053  pushed_active_snap = true;
2054  }
2055  else
2056  {
2057  /* Make sure we have a private copy of the snapshot to modify */
2058  PushCopiedSnapshot(snapshot);
2059  pushed_active_snap = true;
2060  }
2061  }
2062 
2063  foreach(lc1, plan->plancache_list)
2064  {
2065  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc1);
2066  List *stmt_list;
2067  ListCell *lc2;
2068 
2069  spierrcontext.arg = (void *) plansource->query_string;
2070 
2071  /*
2072  * If this is a one-shot plan, we still need to do parse analysis.
2073  */
2074  if (plan->oneshot)
2075  {
2076  RawStmt *parsetree = plansource->raw_parse_tree;
2077  const char *src = plansource->query_string;
2078  List *stmt_list;
2079 
2080  /*
2081  * Parameter datatypes are driven by parserSetup hook if provided,
2082  * otherwise we use the fixed parameter list.
2083  */
2084  if (parsetree == NULL)
2085  stmt_list = NIL;
2086  else if (plan->parserSetup != NULL)
2087  {
2088  Assert(plan->nargs == 0);
2089  stmt_list = pg_analyze_and_rewrite_params(parsetree,
2090  src,
2091  plan->parserSetup,
2092  plan->parserSetupArg,
2093  _SPI_current->queryEnv);
2094  }
2095  else
2096  {
2097  stmt_list = pg_analyze_and_rewrite(parsetree,
2098  src,
2099  plan->argtypes,
2100  plan->nargs,
2101  _SPI_current->queryEnv);
2102  }
2103 
2104  /* Finish filling in the CachedPlanSource */
2105  CompleteCachedPlan(plansource,
2106  stmt_list,
2107  NULL,
2108  plan->argtypes,
2109  plan->nargs,
2110  plan->parserSetup,
2111  plan->parserSetupArg,
2112  plan->cursor_options,
2113  false); /* not fixed result */
2114  }
2115 
2116  /*
2117  * Replan if needed, and increment plan refcount. If it's a saved
2118  * plan, the refcount must be backed by the CurrentResourceOwner.
2119  */
2120  cplan = GetCachedPlan(plansource, paramLI, plan->saved, _SPI_current->queryEnv);
2121  stmt_list = cplan->stmt_list;
2122 
2123  /*
2124  * In the default non-read-only case, get a new snapshot, replacing
2125  * any that we pushed in a previous cycle.
2126  */
2127  if (snapshot == InvalidSnapshot && !read_only && !plan->no_snapshots)
2128  {
2129  if (pushed_active_snap)
2132  pushed_active_snap = true;
2133  }
2134 
2135  foreach(lc2, stmt_list)
2136  {
2137  PlannedStmt *stmt = lfirst_node(PlannedStmt, lc2);
2138  bool canSetTag = stmt->canSetTag;
2139  DestReceiver *dest;
2140 
2141  _SPI_current->processed = 0;
2142  _SPI_current->lastoid = InvalidOid;
2143  _SPI_current->tuptable = NULL;
2144 
2145  if (stmt->utilityStmt)
2146  {
2147  if (IsA(stmt->utilityStmt, CopyStmt))
2148  {
2149  CopyStmt *cstmt = (CopyStmt *) stmt->utilityStmt;
2150 
2151  if (cstmt->filename == NULL)
2152  {
2153  my_res = SPI_ERROR_COPY;
2154  goto fail;
2155  }
2156  }
2157  else if (IsA(stmt->utilityStmt, TransactionStmt))
2158  {
2159  my_res = SPI_ERROR_TRANSACTION;
2160  goto fail;
2161  }
2162  }
2163 
2164  if (read_only && !CommandIsReadOnly(stmt))
2165  ereport(ERROR,
2166  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2167  /* translator: %s is a SQL statement name */
2168  errmsg("%s is not allowed in a non-volatile function",
2169  CreateCommandTag((Node *) stmt))));
2170 
2171  if (IsInParallelMode() && !CommandIsReadOnly(stmt))
2173 
2174  /*
2175  * If not read-only mode, advance the command counter before each
2176  * command and update the snapshot.
2177  */
2178  if (!read_only && !plan->no_snapshots)
2179  {
2182  }
2183 
2184  dest = CreateDestReceiver(canSetTag ? DestSPI : DestNone);
2185 
2186  if (stmt->utilityStmt == NULL)
2187  {
2188  QueryDesc *qdesc;
2189  Snapshot snap;
2190 
2191  if (ActiveSnapshotSet())
2192  snap = GetActiveSnapshot();
2193  else
2194  snap = InvalidSnapshot;
2195 
2196  qdesc = CreateQueryDesc(stmt,
2197  plansource->query_string,
2198  snap, crosscheck_snapshot,
2199  dest,
2200  paramLI, _SPI_current->queryEnv,
2201  0);
2202  res = _SPI_pquery(qdesc, fire_triggers,
2203  canSetTag ? tcount : 0);
2204  FreeQueryDesc(qdesc);
2205  }
2206  else
2207  {
2208  char completionTag[COMPLETION_TAG_BUFSIZE];
2209  ProcessUtilityContext context;
2210 
2211  /*
2212  * If the SPI context is atomic, or we are asked to manage
2213  * snapshots, then we are in an atomic execution context.
2214  * Conversely, to propagate a nonatomic execution context, the
2215  * caller must be in a nonatomic SPI context and manage
2216  * snapshots itself.
2217  */
2218  if (_SPI_current->atomic || !plan->no_snapshots)
2219  context = PROCESS_UTILITY_QUERY;
2220  else
2222 
2223  ProcessUtility(stmt,
2224  plansource->query_string,
2225  context,
2226  paramLI,
2227  _SPI_current->queryEnv,
2228  dest,
2229  completionTag);
2230 
2231  /* Update "processed" if stmt returned tuples */
2232  if (_SPI_current->tuptable)
2233  _SPI_current->processed = _SPI_current->tuptable->alloced -
2234  _SPI_current->tuptable->free;
2235 
2236  res = SPI_OK_UTILITY;
2237 
2238  /*
2239  * Some utility statements return a row count, even though the
2240  * tuples are not returned to the caller.
2241  */
2242  if (IsA(stmt->utilityStmt, CreateTableAsStmt))
2243  {
2244  CreateTableAsStmt *ctastmt = (CreateTableAsStmt *) stmt->utilityStmt;
2245 
2246  if (strncmp(completionTag, "SELECT ", 7) == 0)
2247  _SPI_current->processed =
2248  pg_strtouint64(completionTag + 7, NULL, 10);
2249  else
2250  {
2251  /*
2252  * Must be an IF NOT EXISTS that did nothing, or a
2253  * CREATE ... WITH NO DATA.
2254  */
2255  Assert(ctastmt->if_not_exists ||
2256  ctastmt->into->skipData);
2257  _SPI_current->processed = 0;
2258  }
2259 
2260  /*
2261  * For historical reasons, if CREATE TABLE AS was spelled
2262  * as SELECT INTO, return a special return code.
2263  */
2264  if (ctastmt->is_select_into)
2265  res = SPI_OK_SELINTO;
2266  }
2267  else if (IsA(stmt->utilityStmt, CopyStmt))
2268  {
2269  Assert(strncmp(completionTag, "COPY ", 5) == 0);
2270  _SPI_current->processed = pg_strtouint64(completionTag + 5,
2271  NULL, 10);
2272  }
2273  }
2274 
2275  /*
2276  * The last canSetTag query sets the status values returned to the
2277  * caller. Be careful to free any tuptables not returned, to
2278  * avoid intratransaction memory leak.
2279  */
2280  if (canSetTag)
2281  {
2282  my_processed = _SPI_current->processed;
2283  my_lastoid = _SPI_current->lastoid;
2284  SPI_freetuptable(my_tuptable);
2285  my_tuptable = _SPI_current->tuptable;
2286  my_res = res;
2287  }
2288  else
2289  {
2290  SPI_freetuptable(_SPI_current->tuptable);
2291  _SPI_current->tuptable = NULL;
2292  }
2293  /* we know that the receiver doesn't need a destroy call */
2294  if (res < 0)
2295  {
2296  my_res = res;
2297  goto fail;
2298  }
2299  }
2300 
2301  /* Done with this plan, so release refcount */
2302  ReleaseCachedPlan(cplan, plan->saved);
2303  cplan = NULL;
2304 
2305  /*
2306  * If not read-only mode, advance the command counter after the last
2307  * command. This ensures that its effects are visible, in case it was
2308  * DDL that would affect the next CachedPlanSource.
2309  */
2310  if (!read_only)
2312  }
2313 
2314 fail:
2315 
2316  /* Pop the snapshot off the stack if we pushed one */
2317  if (pushed_active_snap)
2319 
2320  /* We no longer need the cached plan refcount, if any */
2321  if (cplan)
2322  ReleaseCachedPlan(cplan, plan->saved);
2323 
2324  /*
2325  * Pop the error context stack
2326  */
2327  error_context_stack = spierrcontext.previous;
2328 
2329  /* Save results for caller */
2330  SPI_processed = my_processed;
2331  SPI_lastoid = my_lastoid;
2332  SPI_tuptable = my_tuptable;
2333 
2334  /* tuptable now is caller's responsibility, not SPI's */
2335  _SPI_current->tuptable = NULL;
2336 
2337  /*
2338  * If none of the queries had canSetTag, return SPI_OK_REWRITTEN. Prior to
2339  * 8.4, we used return the last query's result code, but not its auxiliary
2340  * results, but that's confusing.
2341  */
2342  if (my_res == 0)
2343  my_res = SPI_OK_REWRITTEN;
2344 
2345  return my_res;
2346 }
2347 
2348 /*
2349  * Convert arrays of query parameters to form wanted by planner and executor
2350  */
2351 static ParamListInfo
2352 _SPI_convert_params(int nargs, Oid *argtypes,
2353  Datum *Values, const char *Nulls)
2354 {
2355  ParamListInfo paramLI;
2356 
2357  if (nargs > 0)
2358  {
2359  int i;
2360 
2361  paramLI = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
2362  nargs * sizeof(ParamExternData));
2363  /* we have static list of params, so no hooks needed */
2364  paramLI->paramFetch = NULL;
2365  paramLI->paramFetchArg = NULL;
2366  paramLI->paramCompile = NULL;
2367  paramLI->paramCompileArg = NULL;
2368  paramLI->parserSetup = NULL;
2369  paramLI->parserSetupArg = NULL;
2370  paramLI->numParams = nargs;
2371 
2372  for (i = 0; i < nargs; i++)
2373  {
2374  ParamExternData *prm = &paramLI->params[i];
2375 
2376  prm->value = Values[i];
2377  prm->isnull = (Nulls && Nulls[i] == 'n');
2378  prm->pflags = PARAM_FLAG_CONST;
2379  prm->ptype = argtypes[i];
2380  }
2381  }
2382  else
2383  paramLI = NULL;
2384  return paramLI;
2385 }
2386 
2387 static int
2388 _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
2389 {
2390  int operation = queryDesc->operation;
2391  int eflags;
2392  int res;
2393 
2394  switch (operation)
2395  {
2396  case CMD_SELECT:
2397  if (queryDesc->dest->mydest != DestSPI)
2398  {
2399  /* Don't return SPI_OK_SELECT if we're discarding result */
2400  res = SPI_OK_UTILITY;
2401  }
2402  else
2403  res = SPI_OK_SELECT;
2404  break;
2405  case CMD_INSERT:
2406  if (queryDesc->plannedstmt->hasReturning)
2408  else
2409  res = SPI_OK_INSERT;
2410  break;
2411  case CMD_DELETE:
2412  if (queryDesc->plannedstmt->hasReturning)
2414  else
2415  res = SPI_OK_DELETE;
2416  break;
2417  case CMD_UPDATE:
2418  if (queryDesc->plannedstmt->hasReturning)
2420  else
2421  res = SPI_OK_UPDATE;
2422  break;
2423  default:
2424  return SPI_ERROR_OPUNKNOWN;
2425  }
2426 
2427 #ifdef SPI_EXECUTOR_STATS
2428  if (ShowExecutorStats)
2429  ResetUsage();
2430 #endif
2431 
2432  /* Select execution options */
2433  if (fire_triggers)
2434  eflags = 0; /* default run-to-completion flags */
2435  else
2436  eflags = EXEC_FLAG_SKIP_TRIGGERS;
2437 
2438  ExecutorStart(queryDesc, eflags);
2439 
2440  ExecutorRun(queryDesc, ForwardScanDirection, tcount, true);
2441 
2442  _SPI_current->processed = queryDesc->estate->es_processed;
2443  _SPI_current->lastoid = queryDesc->estate->es_lastoid;
2444 
2445  if ((res == SPI_OK_SELECT || queryDesc->plannedstmt->hasReturning) &&
2446  queryDesc->dest->mydest == DestSPI)
2447  {
2448  if (_SPI_checktuples())
2449  elog(ERROR, "consistency check on SPI tuple count failed");
2450  }
2451 
2452  ExecutorFinish(queryDesc);
2453  ExecutorEnd(queryDesc);
2454  /* FreeQueryDesc is done by the caller */
2455 
2456 #ifdef SPI_EXECUTOR_STATS
2457  if (ShowExecutorStats)
2458  ShowUsage("SPI EXECUTOR STATS");
2459 #endif
2460 
2461  return res;
2462 }
2463 
2464 /*
2465  * _SPI_error_callback
2466  *
2467  * Add context information when a query invoked via SPI fails
2468  */
2469 static void
2471 {
2472  const char *query = (const char *) arg;
2473  int syntaxerrposition;
2474 
2475  if (query == NULL) /* in case arg wasn't set yet */
2476  return;
2477 
2478  /*
2479  * If there is a syntax error position, convert to internal syntax error;
2480  * otherwise treat the query as an item of context stack
2481  */
2482  syntaxerrposition = geterrposition();
2483  if (syntaxerrposition > 0)
2484  {
2485  errposition(0);
2486  internalerrposition(syntaxerrposition);
2487  internalerrquery(query);
2488  }
2489  else
2490  errcontext("SQL statement \"%s\"", query);
2491 }
2492 
2493 /*
2494  * _SPI_cursor_operation()
2495  *
2496  * Do a FETCH or MOVE in a cursor
2497  */
2498 static void
2499 _SPI_cursor_operation(Portal portal, FetchDirection direction, long count,
2500  DestReceiver *dest)
2501 {
2502  uint64 nfetched;
2503 
2504  /* Check that the portal is valid */
2505  if (!PortalIsValid(portal))
2506  elog(ERROR, "invalid portal in SPI cursor operation");
2507 
2508  /* Push the SPI stack */
2509  if (_SPI_begin_call(true) < 0)
2510  elog(ERROR, "SPI cursor operation called while not connected");
2511 
2512  /* Reset the SPI result (note we deliberately don't touch lastoid) */
2513  SPI_processed = 0;
2514  SPI_tuptable = NULL;
2515  _SPI_current->processed = 0;
2516  _SPI_current->tuptable = NULL;
2517 
2518  /* Run the cursor */
2519  nfetched = PortalRunFetch(portal,
2520  direction,
2521  count,
2522  dest);
2523 
2524  /*
2525  * Think not to combine this store with the preceding function call. If
2526  * the portal contains calls to functions that use SPI, then SPI_stack is
2527  * likely to move around while the portal runs. When control returns,
2528  * _SPI_current will point to the correct stack entry... but the pointer
2529  * may be different than it was beforehand. So we must be sure to re-fetch
2530  * the pointer after the function call completes.
2531  */
2532  _SPI_current->processed = nfetched;
2533 
2534  if (dest->mydest == DestSPI && _SPI_checktuples())
2535  elog(ERROR, "consistency check on SPI tuple count failed");
2536 
2537  /* Put the result into place for access by caller */
2538  SPI_processed = _SPI_current->processed;
2539  SPI_tuptable = _SPI_current->tuptable;
2540 
2541  /* tuptable now is caller's responsibility, not SPI's */
2542  _SPI_current->tuptable = NULL;
2543 
2544  /* Pop the SPI stack */
2545  _SPI_end_call(true);
2546 }
2547 
2548 
2549 static MemoryContext
2551 {
2552  return MemoryContextSwitchTo(_SPI_current->execCxt);
2553 }
2554 
2555 static MemoryContext
2557 {
2558  return MemoryContextSwitchTo(_SPI_current->procCxt);
2559 }
2560 
2561 /*
2562  * _SPI_begin_call: begin a SPI operation within a connected procedure
2563  *
2564  * use_exec is true if we intend to make use of the procedure's execCxt
2565  * during this SPI operation. We'll switch into that context, and arrange
2566  * for it to be cleaned up at _SPI_end_call or if an error occurs.
2567  */
2568 static int
2569 _SPI_begin_call(bool use_exec)
2570 {
2571  if (_SPI_current == NULL)
2572  return SPI_ERROR_UNCONNECTED;
2573 
2574  if (use_exec)
2575  {
2576  /* remember when the Executor operation started */
2577  _SPI_current->execSubid = GetCurrentSubTransactionId();
2578  /* switch to the Executor memory context */
2579  _SPI_execmem();
2580  }
2581 
2582  return 0;
2583 }
2584 
2585 /*
2586  * _SPI_end_call: end a SPI operation within a connected procedure
2587  *
2588  * use_exec must be the same as in the previous _SPI_begin_call
2589  *
2590  * Note: this currently has no failure return cases, so callers don't check
2591  */
2592 static int
2593 _SPI_end_call(bool use_exec)
2594 {
2595  if (use_exec)
2596  {
2597  /* switch to the procedure memory context */
2598  _SPI_procmem();
2599  /* mark Executor context no longer in use */
2600  _SPI_current->execSubid = InvalidSubTransactionId;
2601  /* and free Executor memory */
2603  }
2604 
2605  return 0;
2606 }
2607 
2608 static bool
2610 {
2611  uint64 processed = _SPI_current->processed;
2612  SPITupleTable *tuptable = _SPI_current->tuptable;
2613  bool failed = false;
2614 
2615  if (tuptable == NULL) /* spi_dest_startup was not called */
2616  failed = true;
2617  else if (processed != (tuptable->alloced - tuptable->free))
2618  failed = true;
2619 
2620  return failed;
2621 }
2622 
2623 /*
2624  * Convert a "temporary" SPIPlan into an "unsaved" plan.
2625  *
2626  * The passed _SPI_plan struct is on the stack, and all its subsidiary data
2627  * is in or under the current SPI executor context. Copy the plan into the
2628  * SPI procedure context so it will survive _SPI_end_call(). To minimize
2629  * data copying, this destructively modifies the input plan, by taking the
2630  * plancache entries away from it and reparenting them to the new SPIPlan.
2631  */
2632 static SPIPlanPtr
2634 {
2635  SPIPlanPtr newplan;
2636  MemoryContext parentcxt = _SPI_current->procCxt;
2637  MemoryContext plancxt;
2638  MemoryContext oldcxt;
2639  ListCell *lc;
2640 
2641  /* Assert the input is a temporary SPIPlan */
2642  Assert(plan->magic == _SPI_PLAN_MAGIC);
2643  Assert(plan->plancxt == NULL);
2644  /* One-shot plans can't be saved */
2645  Assert(!plan->oneshot);
2646 
2647  /*
2648  * Create a memory context for the plan, underneath the procedure context.
2649  * We don't expect the plan to be very large.
2650  */
2651  plancxt = AllocSetContextCreate(parentcxt,
2652  "SPI Plan",
2654  oldcxt = MemoryContextSwitchTo(plancxt);
2655 
2656  /* Copy the SPI_plan struct and subsidiary data into the new context */
2657  newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
2658  newplan->magic = _SPI_PLAN_MAGIC;
2659  newplan->plancxt = plancxt;
2660  newplan->cursor_options = plan->cursor_options;
2661  newplan->nargs = plan->nargs;
2662  if (plan->nargs > 0)
2663  {
2664  newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
2665  memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
2666  }
2667  else
2668  newplan->argtypes = NULL;
2669  newplan->parserSetup = plan->parserSetup;
2670  newplan->parserSetupArg = plan->parserSetupArg;
2671 
2672  /*
2673  * Reparent all the CachedPlanSources into the procedure context. In
2674  * theory this could fail partway through due to the pallocs, but we don't
2675  * care too much since both the procedure context and the executor context
2676  * would go away on error.
2677  */
2678  foreach(lc, plan->plancache_list)
2679  {
2680  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
2681 
2682  CachedPlanSetParentContext(plansource, parentcxt);
2683 
2684  /* Build new list, with list cells in plancxt */
2685  newplan->plancache_list = lappend(newplan->plancache_list, plansource);
2686  }
2687 
2688  MemoryContextSwitchTo(oldcxt);
2689 
2690  /* For safety, unlink the CachedPlanSources from the temporary plan */
2691  plan->plancache_list = NIL;
2692 
2693  return newplan;
2694 }
2695 
2696 /*
2697  * Make a "saved" copy of the given plan.
2698  */
2699 static SPIPlanPtr
2701 {
2702  SPIPlanPtr newplan;
2703  MemoryContext plancxt;
2704  MemoryContext oldcxt;
2705  ListCell *lc;
2706 
2707  /* One-shot plans can't be saved */
2708  Assert(!plan->oneshot);
2709 
2710  /*
2711  * Create a memory context for the plan. We don't expect the plan to be
2712  * very large, so use smaller-than-default alloc parameters. It's a
2713  * transient context until we finish copying everything.
2714  */
2716  "SPI Plan",
2718  oldcxt = MemoryContextSwitchTo(plancxt);
2719 
2720  /* Copy the SPI plan into its own context */
2721  newplan = (SPIPlanPtr) palloc0(sizeof(_SPI_plan));
2722  newplan->magic = _SPI_PLAN_MAGIC;
2723  newplan->plancxt = plancxt;
2724  newplan->cursor_options = plan->cursor_options;
2725  newplan->nargs = plan->nargs;
2726  if (plan->nargs > 0)
2727  {
2728  newplan->argtypes = (Oid *) palloc(plan->nargs * sizeof(Oid));
2729  memcpy(newplan->argtypes, plan->argtypes, plan->nargs * sizeof(Oid));
2730  }
2731  else
2732  newplan->argtypes = NULL;
2733  newplan->parserSetup = plan->parserSetup;
2734  newplan->parserSetupArg = plan->parserSetupArg;
2735 
2736  /* Copy all the plancache entries */
2737  foreach(lc, plan->plancache_list)
2738  {
2739  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
2740  CachedPlanSource *newsource;
2741 
2742  newsource = CopyCachedPlan(plansource);
2743  newplan->plancache_list = lappend(newplan->plancache_list, newsource);
2744  }
2745 
2746  MemoryContextSwitchTo(oldcxt);
2747 
2748  /*
2749  * Mark it saved, reparent it under CacheMemoryContext, and mark all the
2750  * component CachedPlanSources as saved. This sequence cannot fail
2751  * partway through, so there's no risk of long-term memory leakage.
2752  */
2753  newplan->saved = true;
2755 
2756  foreach(lc, newplan->plancache_list)
2757  {
2758  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(lc);
2759 
2760  SaveCachedPlan(plansource);
2761  }
2762 
2763  return newplan;
2764 }
2765 
2766 /*
2767  * Internal lookup of ephemeral named relation by name.
2768  */
2771 {
2772  /* internal static function; any error is bug in SPI itself */
2773  Assert(name != NULL);
2774 
2775  /* fast exit if no tuplestores have been added */
2776  if (_SPI_current->queryEnv == NULL)
2777  return NULL;
2778 
2779  return get_ENR(_SPI_current->queryEnv, name);
2780 }
2781 
2782 /*
2783  * Register an ephemeral named relation for use by the planner and executor on
2784  * subsequent calls using this SPI connection.
2785  */
2786 int
2788 {
2789  EphemeralNamedRelation match;
2790  int res;
2791 
2792  if (enr == NULL || enr->md.name == NULL)
2793  return SPI_ERROR_ARGUMENT;
2794 
2795  res = _SPI_begin_call(false); /* keep current memory context */
2796  if (res < 0)
2797  return res;
2798 
2799  match = _SPI_find_ENR_by_name(enr->md.name);
2800  if (match)
2802  else
2803  {
2804  if (_SPI_current->queryEnv == NULL)
2805  _SPI_current->queryEnv = create_queryEnv();
2806 
2807  register_ENR(_SPI_current->queryEnv, enr);
2808  res = SPI_OK_REL_REGISTER;
2809  }
2810 
2811  _SPI_end_call(false);
2812 
2813  return res;
2814 }
2815 
2816 /*
2817  * Unregister an ephemeral named relation by name. This will probably be a
2818  * rarely used function, since SPI_finish will clear it automatically.
2819  */
2820 int
2822 {
2823  EphemeralNamedRelation match;
2824  int res;
2825 
2826  if (name == NULL)
2827  return SPI_ERROR_ARGUMENT;
2828 
2829  res = _SPI_begin_call(false); /* keep current memory context */
2830  if (res < 0)
2831  return res;
2832 
2833  match = _SPI_find_ENR_by_name(name);
2834  if (match)
2835  {
2836  unregister_ENR(_SPI_current->queryEnv, match->md.name);
2837  res = SPI_OK_REL_UNREGISTER;
2838  }
2839  else
2841 
2842  _SPI_end_call(false);
2843 
2844  return res;
2845 }
2846 
2847 /*
2848  * Register the transient relations from 'tdata' using this SPI connection.
2849  * This should be called by PL implementations' trigger handlers after
2850  * connecting, in order to make transition tables visible to any queries run
2851  * in this connection.
2852  */
2853 int
2855 {
2856  if (tdata == NULL)
2857  return SPI_ERROR_ARGUMENT;
2858 
2859  if (tdata->tg_newtable)
2860  {
2863  int rc;
2864 
2865  enr->md.name = tdata->tg_trigger->tgnewtable;
2866  enr->md.reliddesc = tdata->tg_relation->rd_id;
2867  enr->md.tupdesc = NULL;
2870  enr->reldata = tdata->tg_newtable;
2871  rc = SPI_register_relation(enr);
2872  if (rc != SPI_OK_REL_REGISTER)
2873  return rc;
2874  }
2875 
2876  if (tdata->tg_oldtable)
2877  {
2880  int rc;
2881 
2882  enr->md.name = tdata->tg_trigger->tgoldtable;
2883  enr->md.reliddesc = tdata->tg_relation->rd_id;
2884  enr->md.tupdesc = NULL;
2887  enr->reldata = tdata->tg_oldtable;
2888  rc = SPI_register_relation(enr);
2889  if (rc != SPI_OK_REL_REGISTER)
2890  return rc;
2891  }
2892 
2893  return SPI_OK_TD_REGISTER;
2894 }
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:855
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:722
static void _SPI_prepare_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1841
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:124
ParamListInfo copyParamList(ParamListInfo from)
Definition: params.c:36
#define NIL
Definition: pg_list.h:69
Oid * argtypes
Definition: spi_priv.h:94
EphemeralNamedRelationMetadataData md
Datum value
Definition: params.h:92
#define SPI_OK_CONNECT
Definition: spi.h:50
bool CommandIsReadOnly(PlannedStmt *pstmt)
Definition: utility.c:99
void AbortCurrentTransaction(void)
Definition: xact.c:2984
Oid SPI_gettypeid(TupleDesc tupdesc, int fnumber)
Definition: spi.c:988
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:175
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:112
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:781
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
#define SPI_ERROR_PARAM
Definition: spi.h:42
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
List * plancache_list
Definition: spi_priv.h:90
Oid tdtypeid
Definition: tupdesc.h:83
#define SPI_ERROR_REL_NOT_FOUND
Definition: spi.h:48
int errhint(const char *fmt,...)
Definition: elog.c:987
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2650
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner, QueryEnvironment *queryEnv)
Definition: plancache.c:1137
#define GETSTRUCT(TUP)
Definition: htup_details.h:673
void * parserSetupArg
Definition: params.h:117
#define SPI_ERROR_REL_DUPLICATE
Definition: spi.h:47
Portal CreateNewPortal(void)
Definition: portalmem.c:234
FetchDirection
Definition: parsenodes.h:2678
static int32 next
Definition: blutils.c:211
EState * estate
Definition: execdesc.h:48
MemoryContext TopTransactionContext
Definition: mcxt.c:49
HeapTupleHeader SPI_returntuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: spi.c:752
bool tdhasoid
Definition: tupdesc.h:85
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:445
void SPI_freetuple(HeapTuple tuple)
Definition: spi.c:1059
#define SPI_ERROR_UNCONNECTED
Definition: spi.h:39
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:256
CachedPlanSource * CreateOneShotCachedPlan(RawStmt *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:236
int SPI_connect_ext(int options)
Definition: spi.c:90
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:281
Oid es_lastoid
Definition: execnodes.h:530
bool SPI_is_cursor_plan(SPIPlanPtr plan)
Definition: spi.c:1547
int SPI_connect(void)
Definition: spi.c:84
#define _SPI_PLAN_MAGIC
Definition: spi_priv.h:20
#define SPI_OK_DELETE_RETURNING
Definition: spi.h:61
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
const char * commandTag
Definition: plancache.h:85
static int _SPI_stack_depth
Definition: spi.c:46
void SPI_scroll_cursor_fetch(Portal portal, FetchDirection direction, long count)
Definition: spi.c:1472
bool internal_xact
Definition: spi_priv.h:42
Definition: dest.h:93
void ShowUsage(const char *title)
Definition: postgres.c:4453
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:354
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
int magic
Definition: spi_priv.h:86
#define SPI_OK_DELETE
Definition: spi.h:57
CommandDest mydest
Definition: dest.h:128
char * pstrdup(const char *in)
Definition: mcxt.c:1161
void CommitTransactionCommand(void)
Definition: xact.c:2744
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:576
Portal SPI_cursor_open_with_paramlist(const char *name, SPIPlanPtr plan, ParamListInfo params, bool read_only)
Definition: spi.c:1204
static EphemeralNamedRelation _SPI_find_ENR_by_name(const char *name)
Definition: spi.c:2770
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:202
slist_node * cur
Definition: ilist.h:241
int SPI_finish(void)
Definition: spi.c:161
uint64 PortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1395
void SPI_scroll_cursor_move(Portal portal, FetchDirection direction, long count)
Definition: spi.c:1487
SPIPlanPtr SPI_saveplan(SPIPlanPtr plan)
Definition: spi.c:681
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:141
#define SPI_ERROR_COPY
Definition: spi.h:37
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:839
Form_pg_attribute SystemAttributeByName(const char *attname, bool relhasoids)
Definition: heap.c:217
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:574
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:301
SPITupleTable * SPI_tuptable
Definition: spi.c:41
Definition: nodes.h:517
slist_node next
Definition: spi.h:29
#define SPI_ERROR_OPUNKNOWN
Definition: spi.h:38
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag)
Definition: utility.c:337
int errcode(int sqlerrcode)
Definition: elog.c:575
static void _SPI_prepare_oneshot_plan(const char *src, SPIPlanPtr plan)
Definition: spi.c:1946
ProcessUtilityContext
Definition: utility.h:19
int namestrcmp(Name name, const char *str)
Definition: name.c:247
static int _SPI_connected
Definition: spi.c:47
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
SubTransactionId execSubid
Definition: spi_priv.h:30
static _SPI_connection * _SPI_current
Definition: spi.c:45
HeapTuple SPI_copytuple(HeapTuple tuple)
Definition: spi.c:725
#define false
Definition: c.h:283
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
Portal SPI_cursor_open(const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
Definition: spi.c:1125
uint32 SubTransactionId
Definition: c.h:478
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1074
ParserSetupHook parserSetup
Definition: params.h:116
bool skipData
Definition: primnodes.h:116
struct ParamListInfoData * ParamListInfo
Definition: params.h:98
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
unsigned int Oid
Definition: postgres_ext.h:31
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:650
HeapTuple * vals
Definition: spi.h:28
#define linitial_node(type, l)
Definition: pg_list.h:114
void SPI_rollback(void)
Definition: spi.c:240
DestReceiver * None_Receiver
Definition: dest.c:91
#define SPI_OK_REL_REGISTER
Definition: spi.h:64
void(* callback)(void *arg)
Definition: elog.h:239
struct ErrorContextCallback * previous
Definition: elog.h:238
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:264
#define SPI_ERROR_CONNECT
Definition: spi.h:36
int natts
Definition: tupdesc.h:82
#define SPI_OK_CURSOR
Definition: spi.h:59
MemoryContext portalContext
Definition: portal.h:119
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2646
uint64 SPI_processed
Definition: spi.c:39
int32 tdtypmod
Definition: tupdesc.h:84
struct CachedPlan * gplan
Definition: plancache.h:105
char * SPI_gettype(TupleDesc tupdesc, int fnumber)
Definition: spi.c:948
static int _SPI_begin_call(bool use_exec)
Definition: spi.c:2569
static bool _SPI_checktuples(void)
Definition: spi.c:2609
void assign_record_type_typmod(TupleDesc tupDesc)
Definition: typcache.c:1761
MemoryContext PortalContext
Definition: mcxt.c:53
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
TupleDesc resultDesc
Definition: plancache.h:92
char * SPI_fname(TupleDesc tupdesc, int fnumber)
Definition: spi.c:878
Portal SPI_cursor_find(const char *name)
Definition: spi.c:1431
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:715
ErrorContextCallback * error_context_stack
Definition: elog.c:88
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:900
CachedPlan * SPI_plan_get_cached_plan(SPIPlanPtr plan)
Definition: spi.c:1702
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
int SPI_result
Definition: spi.c:42
static int _SPI_execute_plan(SPIPlanPtr plan, ParamListInfo paramLI, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, uint64 tcount)
Definition: spi.c:2004
void ResetUsage(void)
Definition: postgres.c:4446
void * paramFetchArg
Definition: params.h:113
#define SPI_ERROR_NOOUTFUNC
Definition: spi.h:45
SubTransactionId connectSubid
Definition: spi_priv.h:37
ParamCompileHook paramCompile
Definition: params.h:114
#define SPI_ERROR_ARGUMENT
Definition: spi.h:41
static void _SPI_error_callback(void *arg)
Definition: spi.c:2470
ParamFetchHook paramFetch
Definition: params.h:112
void pfree(void *pointer)
Definition: mcxt.c:1031
static void slist_init(slist_head *head)
Definition: ilist.h:554
bool IsInParallelMode(void)
Definition: xact.c:905
#define linitial(l)
Definition: pg_list.h:111
#define SPI_OK_TD_REGISTER
Definition: spi.h:66
#define ObjectIdGetDatum(X)
Definition: postgres.h:490
#define ERROR
Definition: elog.h:43
bool no_snapshots
Definition: spi_priv.h:89
QueryEnvironment * queryEnv
Definition: spi_priv.h:38
int SPI_execute_plan_with_paramlist(SPIPlanPtr plan, ParamListInfo params, bool read_only, long tcount)
Definition: spi.c:467
int SPI_execute_with_args(const char *src, int nargs, Oid *argtypes, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:535
int SPI_exec(const char *src, long tcount)
Definition: spi.c:426
Datum SPI_datumTransfer(Datum value, bool typByVal, int typLen)
Definition: spi.c:1041
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:299
#define SPI_OPT_NONATOMIC
Definition: spi.h:68
#define SPI_OK_INSERT_RETURNING
Definition: spi.h:60
static SPIPlanPtr _SPI_save_plan(SPIPlanPtr plan)
Definition: spi.c:2700
SPITupleTable * tuptable
Definition: spi_priv.h:27
List * pg_parse_query(const char *query_string)
Definition: postgres.c:608
ItemPointerData t_ctid
Definition: htup_details.h:157
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:769
ItemPointerData t_self
Definition: htup.h:65
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:433
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
Definition: spi.c:932
CachedPlanSource * CopyCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:1324
const char * SPI_result_code_string(int code)
Definition: spi.c:1609
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define lfirst_node(type, lc)
Definition: pg_list.h:109
void unregister_ENR(QueryEnvironment *queryEnv, const char *name)
static int _SPI_pquery(QueryDesc *queryDesc, bool fire_triggers, uint64 tcount)
Definition: spi.c:2388
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
int SPI_unregister_relation(const char *name)
Definition: spi.c:2821
Definition: dest.h:88
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3051
Node * stmt
Definition: parsenodes.h:1450
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:654
static char * buf
Definition: pg_test_fsync.c:67
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
bool hasReturning
Definition: plannodes.h:49
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
static MemoryContext _SPI_execmem(void)
Definition: spi.c:2550
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define SPI_OK_UTILITY
Definition: spi.h:53
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:152
Node * utilityStmt
Definition: plannodes.h:96
#define SPI_OK_UPDATE_RETURNING
Definition: spi.h:62
void spi_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: spi.c:1745
int geterrposition(void)
Definition: elog.c:1257
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1258
static _SPI_connection * _SPI_stack
Definition: spi.c:44
#define RelationGetRelationName(relation)
Definition: rel.h:441
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
Oid t_tableOid
Definition: htup.h:66
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:851
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define SPI_OK_REWRITTEN
Definition: spi.h:63
static SPIPlanPtr _SPI_make_plan_non_temp(SPIPlanPtr plan)
Definition: spi.c:2633
PortalStrategy strategy
Definition: portal.h:143
int SPI_getargcount(SPIPlanPtr plan)
Definition: spi.c:1527
void CachedPlanSetParentContext(CachedPlanSource *plansource, MemoryContext newcontext)
Definition: plancache.c:1286
HeapTuple SPI_modifytuple(Relation rel, HeapTuple tuple, int natts, int *attnum, Datum *Values, const char *Nulls)
Definition: spi.c:784
Oid atttypid
Definition: pg_attribute.h:49
#define ereport(elevel, rest)
Definition: elog.h:122
int SPI_register_trigger_data(TriggerData *tdata)
Definition: spi.c:2854
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2056
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Oid rd_id
Definition: rel.h:86
MemoryContext savedcxt
Definition: spi_priv.h:36
Datum heap_copy_tuple_as_datum(HeapTuple tuple, TupleDesc tupleDesc)
Definition: heaptuple.c:1038
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
MemoryContext plancxt
Definition: spi_priv.h:91
#define SPI_ERROR_TRANSACTION
Definition: spi.h:43
int SPI_execute_snapshot(SPIPlanPtr plan, Datum *Values, const char *Nulls, Snapshot snapshot, Snapshot crosscheck_snapshot, bool read_only, bool fire_triggers, long tcount)
Definition: spi.c:501
struct ParamExternData ParamExternData
List * lappend(List *list, void *datum)
Definition: list.c:128
void * SPI_palloc(Size size)
Definition: spi.c:1018
#define SPI_OK_SELINTO
Definition: spi.h:55
static int _SPI_end_call(bool use_exec)
Definition: spi.c:2593
void SPI_commit(void)
Definition: spi.c:206
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
#define WARNING
Definition: elog.h:40
HeapTuple ExecCopySlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:581
void register_ENR(QueryEnvironment *queryEnv, EphemeralNamedRelation enr)
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:786
CmdType operation
Definition: execdesc.h:36
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1066
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
#define InvalidSnapshot
Definition: snapshot.h:25
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define PortalIsValid(p)
Definition: portal.h:201
#define SPI_OK_FETCH
Definition: spi.h:52
uint64 pg_strtouint64(const char *str, char **endptr, int base)
Definition: numutils.c:405
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
bool canSetTag
Definition: plannodes.h:53
void * palloc0(Size size)
Definition: mcxt.c:955
MemoryContext procCxt
Definition: spi_priv.h:34
uintptr_t Datum
Definition: postgres.h:365
Oid SPI_lastoid
Definition: spi.c:40
void CommandCounterIncrement(void)
Definition: xact.c:914
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
bool ExecSupportsBackwardScan(Plan *node)
Definition: execAmi.c:462
char * tgnewtable
Definition: reltrigger.h:43
MemoryContext execCxt
Definition: spi_priv.h:35
TupleDesc tupdesc
Definition: spi.h:27
static struct @131 value
Trigger * tg_trigger
Definition: trigger.h:37
bool saved
Definition: spi_priv.h:87
TupleDesc rd_att
Definition: rel.h:85
static void _SPI_cursor_operation(Portal portal, FetchDirection direction, long count, DestReceiver *dest)
Definition: spi.c:2499
#define SPI_OK_SELECT
Definition: spi.h:54
int nargs
Definition: spi_priv.h:93
Form_pg_attribute SystemAttributeDefinition(AttrNumber attno, bool relhasoids)
Definition: heap.c:203
char * SPI_getrelname(Relation rel)
Definition: spi.c:1006
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:442
int internalerrquery(const char *query)
Definition: elog.c:1161
IntoClause * into
Definition: parsenodes.h:3197
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:190
int64 tuplestore_tuple_count(Tuplestorestate *state)
Definition: tuplestore.c:546
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
uint64 processed
Definition: spi_priv.h:25
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
ParserSetupHook parserSetup
Definition: spi_priv.h:95
Portal SPI_cursor_open_with_args(const char *name, const char *src, int nargs, Oid *argtypes, Datum *Values, const char *Nulls, bool read_only, int cursorOptions)
Definition: spi.c:1152
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:641
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:326
bool oneshot
Definition: spi_priv.h:88
void StartTransactionCommand(void)
Definition: xact.c:2673
uint64 es_processed
Definition: execnodes.h:529
SPIPlanPtr SPI_prepare_cursor(const char *src, int nargs, Oid *argtypes, int cursorOptions)
Definition: spi.c:582
char * SPI_getnspname(Relation rel)
Definition: spi.c:1012
uint16 pflags
Definition: params.h:94
const char * query_string
Definition: plancache.h:84
size_t Size
Definition: c.h:433
void AtEOXact_SPI(bool isCommit)
Definition: spi.c:267
FormData_pg_type * Form_pg_type
Definition: pg_type.h:247
QueryEnvironment * create_queryEnv()
static int list_length(const List *l)
Definition: pg_list.h:89
void * parserSetupArg
Definition: spi_priv.h:96
#define SPI_OK_FINISH
Definition: spi.h:51
#define SPI_ERROR_TYPUNKNOWN
Definition: spi.h:46
void SPI_cursor_move(Portal portal, bool forward, long count)
Definition: spi.c:1458
#define InvalidSubTransactionId
Definition: c.h:480
List * pg_analyze_and_rewrite_params(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:687
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
struct RawStmt * raw_parse_tree
Definition: plancache.h:83
#define EXEC_FLAG_SKIP_TRIGGERS
Definition: executor.h:62
const char * name
Definition: encode.c:521
QueryEnvironment * queryEnv
Definition: portal.h:140
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
void * paramCompileArg
Definition: params.h:115
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1315
bool IsSubTransaction(void)
Definition: xact.c:4495
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:703
void SPI_cursor_close(Portal portal)
Definition: spi.c:1499
DestReceiver * dest
Definition: execdesc.h:41
uint64 free
Definition: spi.h:26
static Portal SPI_cursor_open_internal(const char *name, SPIPlanPtr plan, ParamListInfo paramLI, bool read_only)
Definition: spi.c:1217
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2653
bool SPI_plan_is_valid(SPIPlanPtr plan)
Definition: spi.c:1585
int SPI_register_relation(EphemeralNamedRelation enr)
Definition: spi.c:2787
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1832
void * repalloc_huge(void *pointer, Size size)
Definition: mcxt.c:1114
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:465
#define SPI_OK_UPDATE
Definition: spi.h:58
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2645
int SPI_execp(SPIPlanPtr plan, Datum *Values, const char *Nulls, long tcount)
Definition: spi.c:460
uint64 alloced
Definition: spi.h:25
Oid SPI_getargtypeid(SPIPlanPtr plan, int argIndex)
Definition: spi.c:1512
#define errcontext
Definition: elog.h:164
#define NameStr(name)
Definition: c.h:576
Tuplestorestate * tg_newtable
Definition: trigger.h:41
List * SPI_plan_get_plan_sources(SPIPlanPtr plan)
Definition: spi.c:1686
void * arg
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Definition: spi.c:1443
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:487
bool CachedPlanIsValid(CachedPlanSource *plansource)
Definition: plancache.c:1415
EphemeralNameRelationType enrtype
char * filename
Definition: parsenodes.h:1960
void SPI_start_transaction(void)
Definition: spi.c:197
#define SPI_OK_INSERT
Definition: spi.h:56
struct _SPI_plan * SPIPlanPtr
Definition: spi.h:34
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:652
List * stmt_list
Definition: plancache.h:133
void * SPI_repalloc(void *pointer, Size size)
Definition: spi.c:1027
int cursor_options
Definition: spi_priv.h:92
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:712
int cursorOptions
Definition: portal.h:144
PlannedStmt * plannedstmt
Definition: execdesc.h:37
#define copyObject(obj)
Definition: nodes.h:630
static MemoryContext _SPI_procmem(void)
Definition: spi.c:2556
SubTransactionId subid
Definition: spi.h:30
char * tgoldtable
Definition: reltrigger.h:42
static ParamListInfo _SPI_convert_params(int nargs, Oid *argtypes, Datum *Values, const char *Nulls)
Definition: spi.c:2352
Definition: pg_list.h:45
bool isnull
Definition: params.h:93
long val
Definition: informix.c:689
void SPI_pfree(void *pointer)
Definition: spi.c:1034
#define offsetof(type, field)
Definition: c.h:622
int errposition(int cursorpos)
Definition: elog.c:1125
#define PARAM_FLAG_CONST
Definition: params.h:88
slist_head tuptables
Definition: spi_priv.h:33
bool spi_printtup(TupleTableSlot *slot, DestReceiver *self)
Definition: spi.c:1792
SPIPlanPtr SPI_prepare_params(const char *src, ParserSetupHook parserSetup, void *parserSetupArg, int cursorOptions)
Definition: spi.c:617
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:398
MemoryContext tuptabcxt
Definition: spi.h:24
#define SPI_OK_REL_UNREGISTER
Definition: spi.h:65
MemoryContext CacheMemoryContext
Definition: mcxt.c:47
static bool Nulls[MAXATTR]
Definition: bootstrap.c:165
Relation tg_relation
Definition: trigger.h:34
EphemeralNamedRelation get_ENR(QueryEnvironment *queryEnv, const char *name)
int internalerrposition(int cursorpos)
Definition: elog.c:1141
#define RelationGetNamespace(relation)
Definition: rel.h:448