PostgreSQL Source Code  git master
pquery.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pquery.c
4  * POSTGRES process query command code
5  *
6  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/tcop/pquery.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include <limits.h>
19 
20 #include "access/xact.h"
21 #include "commands/prepare.h"
23 #include "miscadmin.h"
24 #include "pg_trace.h"
25 #include "tcop/pquery.h"
26 #include "tcop/utility.h"
27 #include "utils/memutils.h"
28 #include "utils/snapmgr.h"
29 
30 
31 /*
32  * ActivePortal is the currently executing Portal (the most closely nested,
33  * if there are several).
34  */
36 
37 
38 static void ProcessQuery(PlannedStmt *plan,
39  const char *sourceText,
40  ParamListInfo params,
41  QueryEnvironment *queryEnv,
43  QueryCompletion *qc);
44 static void FillPortalStore(Portal portal, bool isTopLevel);
45 static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count,
47 static uint64 PortalRunSelect(Portal portal, bool forward, long count,
49 static void PortalRunUtility(Portal portal, PlannedStmt *pstmt,
50  bool isTopLevel, bool setHoldSnapshot,
52 static void PortalRunMulti(Portal portal,
53  bool isTopLevel, bool setHoldSnapshot,
54  DestReceiver *dest, DestReceiver *altdest,
55  QueryCompletion *qc);
56 static uint64 DoPortalRunFetch(Portal portal,
57  FetchDirection fdirection,
58  long count,
60 static void DoPortalRewind(Portal portal);
61 
62 
63 /*
64  * CreateQueryDesc
65  */
66 QueryDesc *
68  const char *sourceText,
69  Snapshot snapshot,
70  Snapshot crosscheck_snapshot,
72  ParamListInfo params,
73  QueryEnvironment *queryEnv,
74  int instrument_options)
75 {
76  QueryDesc *qd = (QueryDesc *) palloc(sizeof(QueryDesc));
77 
78  qd->operation = plannedstmt->commandType; /* operation */
79  qd->plannedstmt = plannedstmt; /* plan */
80  qd->sourceText = sourceText; /* query text */
81  qd->snapshot = RegisterSnapshot(snapshot); /* snapshot */
82  /* RI check snapshot */
83  qd->crosscheck_snapshot = RegisterSnapshot(crosscheck_snapshot);
84  qd->dest = dest; /* output dest */
85  qd->params = params; /* parameter values passed into query */
86  qd->queryEnv = queryEnv;
87  qd->instrument_options = instrument_options; /* instrumentation wanted? */
88 
89  /* null these fields until set by ExecutorStart */
90  qd->tupDesc = NULL;
91  qd->estate = NULL;
92  qd->planstate = NULL;
93  qd->totaltime = NULL;
94 
95  /* not yet executed */
96  qd->already_executed = false;
97 
98  return qd;
99 }
100 
101 /*
102  * FreeQueryDesc
103  */
104 void
106 {
107  /* Can't be a live query */
108  Assert(qdesc->estate == NULL);
109 
110  /* forget our snapshots */
113 
114  /* Only the QueryDesc itself need be freed */
115  pfree(qdesc);
116 }
117 
118 
119 /*
120  * ProcessQuery
121  * Execute a single plannable query within a PORTAL_MULTI_QUERY,
122  * PORTAL_ONE_RETURNING, or PORTAL_ONE_MOD_WITH portal
123  *
124  * plan: the plan tree for the query
125  * sourceText: the source text of the query
126  * params: any parameters needed
127  * dest: where to send results
128  * qc: where to store the command completion status data.
129  *
130  * qc may be NULL if caller doesn't want a status string.
131  *
132  * Must be called in a memory context that will be reset or deleted on
133  * error; otherwise the executor's memory usage will be leaked.
134  */
135 static void
137  const char *sourceText,
138  ParamListInfo params,
139  QueryEnvironment *queryEnv,
141  QueryCompletion *qc)
142 {
143  QueryDesc *queryDesc;
144 
145  /*
146  * Create the QueryDesc object
147  */
148  queryDesc = CreateQueryDesc(plan, sourceText,
150  dest, params, queryEnv, 0);
151 
152  /*
153  * Call ExecutorStart to prepare the plan for execution
154  */
155  ExecutorStart(queryDesc, 0);
156 
157  /*
158  * Run the plan to completion.
159  */
160  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
161 
162  /*
163  * Build command completion status data, if caller wants one.
164  */
165  if (qc)
166  {
167  switch (queryDesc->operation)
168  {
169  case CMD_SELECT:
170  SetQueryCompletion(qc, CMDTAG_SELECT, queryDesc->estate->es_processed);
171  break;
172  case CMD_INSERT:
173  SetQueryCompletion(qc, CMDTAG_INSERT, queryDesc->estate->es_processed);
174  break;
175  case CMD_UPDATE:
176  SetQueryCompletion(qc, CMDTAG_UPDATE, queryDesc->estate->es_processed);
177  break;
178  case CMD_DELETE:
179  SetQueryCompletion(qc, CMDTAG_DELETE, queryDesc->estate->es_processed);
180  break;
181  default:
182  SetQueryCompletion(qc, CMDTAG_UNKNOWN, queryDesc->estate->es_processed);
183  break;
184  }
185  }
186 
187  /*
188  * Now, we close down all the scans and free allocated resources.
189  */
190  ExecutorFinish(queryDesc);
191  ExecutorEnd(queryDesc);
192 
193  FreeQueryDesc(queryDesc);
194 }
195 
196 /*
197  * ChoosePortalStrategy
198  * Select portal execution strategy given the intended statement list.
199  *
200  * The list elements can be Querys or PlannedStmts.
201  * That's more general than portals need, but plancache.c uses this too.
202  *
203  * See the comments in portal.h.
204  */
207 {
208  int nSetTag;
209  ListCell *lc;
210 
211  /*
212  * PORTAL_ONE_SELECT and PORTAL_UTIL_SELECT need only consider the
213  * single-statement case, since there are no rewrite rules that can add
214  * auxiliary queries to a SELECT or a utility command. PORTAL_ONE_MOD_WITH
215  * likewise allows only one top-level statement.
216  */
217  if (list_length(stmts) == 1)
218  {
219  Node *stmt = (Node *) linitial(stmts);
220 
221  if (IsA(stmt, Query))
222  {
223  Query *query = (Query *) stmt;
224 
225  if (query->canSetTag)
226  {
227  if (query->commandType == CMD_SELECT)
228  {
229  if (query->hasModifyingCTE)
230  return PORTAL_ONE_MOD_WITH;
231  else
232  return PORTAL_ONE_SELECT;
233  }
234  if (query->commandType == CMD_UTILITY)
235  {
236  if (UtilityReturnsTuples(query->utilityStmt))
237  return PORTAL_UTIL_SELECT;
238  /* it can't be ONE_RETURNING, so give up */
239  return PORTAL_MULTI_QUERY;
240  }
241  }
242  }
243  else if (IsA(stmt, PlannedStmt))
244  {
245  PlannedStmt *pstmt = (PlannedStmt *) stmt;
246 
247  if (pstmt->canSetTag)
248  {
249  if (pstmt->commandType == CMD_SELECT)
250  {
251  if (pstmt->hasModifyingCTE)
252  return PORTAL_ONE_MOD_WITH;
253  else
254  return PORTAL_ONE_SELECT;
255  }
256  if (pstmt->commandType == CMD_UTILITY)
257  {
258  if (UtilityReturnsTuples(pstmt->utilityStmt))
259  return PORTAL_UTIL_SELECT;
260  /* it can't be ONE_RETURNING, so give up */
261  return PORTAL_MULTI_QUERY;
262  }
263  }
264  }
265  else
266  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
267  }
268 
269  /*
270  * PORTAL_ONE_RETURNING has to allow auxiliary queries added by rewrite.
271  * Choose PORTAL_ONE_RETURNING if there is exactly one canSetTag query and
272  * it has a RETURNING list.
273  */
274  nSetTag = 0;
275  foreach(lc, stmts)
276  {
277  Node *stmt = (Node *) lfirst(lc);
278 
279  if (IsA(stmt, Query))
280  {
281  Query *query = (Query *) stmt;
282 
283  if (query->canSetTag)
284  {
285  if (++nSetTag > 1)
286  return PORTAL_MULTI_QUERY; /* no need to look further */
287  if (query->commandType == CMD_UTILITY ||
288  query->returningList == NIL)
289  return PORTAL_MULTI_QUERY; /* no need to look further */
290  }
291  }
292  else if (IsA(stmt, PlannedStmt))
293  {
294  PlannedStmt *pstmt = (PlannedStmt *) stmt;
295 
296  if (pstmt->canSetTag)
297  {
298  if (++nSetTag > 1)
299  return PORTAL_MULTI_QUERY; /* no need to look further */
300  if (pstmt->commandType == CMD_UTILITY ||
301  !pstmt->hasReturning)
302  return PORTAL_MULTI_QUERY; /* no need to look further */
303  }
304  }
305  else
306  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
307  }
308  if (nSetTag == 1)
309  return PORTAL_ONE_RETURNING;
310 
311  /* Else, it's the general case... */
312  return PORTAL_MULTI_QUERY;
313 }
314 
315 /*
316  * FetchPortalTargetList
317  * Given a portal that returns tuples, extract the query targetlist.
318  * Returns NIL if the portal doesn't have a determinable targetlist.
319  *
320  * Note: do not modify the result.
321  */
322 List *
324 {
325  /* no point in looking if we determined it doesn't return tuples */
326  if (portal->strategy == PORTAL_MULTI_QUERY)
327  return NIL;
328  /* get the primary statement and find out what it returns */
330 }
331 
332 /*
333  * FetchStatementTargetList
334  * Given a statement that returns tuples, extract the query targetlist.
335  * Returns NIL if the statement doesn't have a determinable targetlist.
336  *
337  * This can be applied to a Query or a PlannedStmt.
338  * That's more general than portals need, but plancache.c uses this too.
339  *
340  * Note: do not modify the result.
341  *
342  * XXX be careful to keep this in sync with UtilityReturnsTuples.
343  */
344 List *
346 {
347  if (stmt == NULL)
348  return NIL;
349  if (IsA(stmt, Query))
350  {
351  Query *query = (Query *) stmt;
352 
353  if (query->commandType == CMD_UTILITY)
354  {
355  /* transfer attention to utility statement */
356  stmt = query->utilityStmt;
357  }
358  else
359  {
360  if (query->commandType == CMD_SELECT)
361  return query->targetList;
362  if (query->returningList)
363  return query->returningList;
364  return NIL;
365  }
366  }
367  if (IsA(stmt, PlannedStmt))
368  {
369  PlannedStmt *pstmt = (PlannedStmt *) stmt;
370 
371  if (pstmt->commandType == CMD_UTILITY)
372  {
373  /* transfer attention to utility statement */
374  stmt = pstmt->utilityStmt;
375  }
376  else
377  {
378  if (pstmt->commandType == CMD_SELECT)
379  return pstmt->planTree->targetlist;
380  if (pstmt->hasReturning)
381  return pstmt->planTree->targetlist;
382  return NIL;
383  }
384  }
385  if (IsA(stmt, FetchStmt))
386  {
387  FetchStmt *fstmt = (FetchStmt *) stmt;
388  Portal subportal;
389 
390  Assert(!fstmt->ismove);
391  subportal = GetPortalByName(fstmt->portalname);
392  Assert(PortalIsValid(subportal));
393  return FetchPortalTargetList(subportal);
394  }
395  if (IsA(stmt, ExecuteStmt))
396  {
397  ExecuteStmt *estmt = (ExecuteStmt *) stmt;
398  PreparedStatement *entry;
399 
400  entry = FetchPreparedStatement(estmt->name, true);
401  return FetchPreparedStatementTargetList(entry);
402  }
403  return NIL;
404 }
405 
406 /*
407  * PortalStart
408  * Prepare a portal for execution.
409  *
410  * Caller must already have created the portal, done PortalDefineQuery(),
411  * and adjusted portal options if needed.
412  *
413  * If parameters are needed by the query, they must be passed in "params"
414  * (caller is responsible for giving them appropriate lifetime).
415  *
416  * The caller can also provide an initial set of "eflags" to be passed to
417  * ExecutorStart (but note these can be modified internally, and they are
418  * currently only honored for PORTAL_ONE_SELECT portals). Most callers
419  * should simply pass zero.
420  *
421  * The caller can optionally pass a snapshot to be used; pass InvalidSnapshot
422  * for the normal behavior of setting a new snapshot. This parameter is
423  * presently ignored for non-PORTAL_ONE_SELECT portals (it's only intended
424  * to be used for cursors).
425  *
426  * On return, portal is ready to accept PortalRun() calls, and the result
427  * tupdesc (if any) is known.
428  */
429 void
431  int eflags, Snapshot snapshot)
432 {
433  Portal saveActivePortal;
434  ResourceOwner saveResourceOwner;
435  MemoryContext savePortalContext;
436  MemoryContext oldContext;
437  QueryDesc *queryDesc;
438  int myeflags;
439 
440  AssertArg(PortalIsValid(portal));
441  AssertState(portal->status == PORTAL_DEFINED);
442 
443  /*
444  * Set up global portal context pointers.
445  */
446  saveActivePortal = ActivePortal;
447  saveResourceOwner = CurrentResourceOwner;
448  savePortalContext = PortalContext;
449  PG_TRY();
450  {
451  ActivePortal = portal;
452  if (portal->resowner)
453  CurrentResourceOwner = portal->resowner;
454  PortalContext = portal->portalContext;
455 
456  oldContext = MemoryContextSwitchTo(PortalContext);
457 
458  /* Must remember portal param list, if any */
459  portal->portalParams = params;
460 
461  /*
462  * Determine the portal execution strategy
463  */
464  portal->strategy = ChoosePortalStrategy(portal->stmts);
465 
466  /*
467  * Fire her up according to the strategy
468  */
469  switch (portal->strategy)
470  {
471  case PORTAL_ONE_SELECT:
472 
473  /* Must set snapshot before starting executor. */
474  if (snapshot)
475  PushActiveSnapshot(snapshot);
476  else
478 
479  /*
480  * Create QueryDesc in portal's context; for the moment, set
481  * the destination to DestNone.
482  */
483  queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
484  portal->sourceText,
488  params,
489  portal->queryEnv,
490  0);
491 
492  /*
493  * If it's a scrollable cursor, executor needs to support
494  * REWIND and backwards scan, as well as whatever the caller
495  * might've asked for.
496  */
497  if (portal->cursorOptions & CURSOR_OPT_SCROLL)
498  myeflags = eflags | EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
499  else
500  myeflags = eflags;
501 
502  /*
503  * Call ExecutorStart to prepare the plan for execution
504  */
505  ExecutorStart(queryDesc, myeflags);
506 
507  /*
508  * This tells PortalCleanup to shut down the executor
509  */
510  portal->queryDesc = queryDesc;
511 
512  /*
513  * Remember tuple descriptor (computed by ExecutorStart)
514  */
515  portal->tupDesc = queryDesc->tupDesc;
516 
517  /*
518  * Reset cursor position data to "start of query"
519  */
520  portal->atStart = true;
521  portal->atEnd = false; /* allow fetches */
522  portal->portalPos = 0;
523 
525  break;
526 
528  case PORTAL_ONE_MOD_WITH:
529 
530  /*
531  * We don't start the executor until we are told to run the
532  * portal. We do need to set up the result tupdesc.
533  */
534  {
535  PlannedStmt *pstmt;
536 
537  pstmt = PortalGetPrimaryStmt(portal);
538  portal->tupDesc =
540  }
541 
542  /*
543  * Reset cursor position data to "start of query"
544  */
545  portal->atStart = true;
546  portal->atEnd = false; /* allow fetches */
547  portal->portalPos = 0;
548  break;
549 
550  case PORTAL_UTIL_SELECT:
551 
552  /*
553  * We don't set snapshot here, because PortalRunUtility will
554  * take care of it if needed.
555  */
556  {
557  PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
558 
559  Assert(pstmt->commandType == CMD_UTILITY);
560  portal->tupDesc = UtilityTupleDescriptor(pstmt->utilityStmt);
561  }
562 
563  /*
564  * Reset cursor position data to "start of query"
565  */
566  portal->atStart = true;
567  portal->atEnd = false; /* allow fetches */
568  portal->portalPos = 0;
569  break;
570 
571  case PORTAL_MULTI_QUERY:
572  /* Need do nothing now */
573  portal->tupDesc = NULL;
574  break;
575  }
576  }
577  PG_CATCH();
578  {
579  /* Uncaught error while executing portal: mark it dead */
580  MarkPortalFailed(portal);
581 
582  /* Restore global vars and propagate error */
583  ActivePortal = saveActivePortal;
584  CurrentResourceOwner = saveResourceOwner;
585  PortalContext = savePortalContext;
586 
587  PG_RE_THROW();
588  }
589  PG_END_TRY();
590 
591  MemoryContextSwitchTo(oldContext);
592 
593  ActivePortal = saveActivePortal;
594  CurrentResourceOwner = saveResourceOwner;
595  PortalContext = savePortalContext;
596 
597  portal->status = PORTAL_READY;
598 }
599 
600 /*
601  * PortalSetResultFormat
602  * Select the format codes for a portal's output.
603  *
604  * This must be run after PortalStart for a portal that will be read by
605  * a DestRemote or DestRemoteExecute destination. It is not presently needed
606  * for other destination types.
607  *
608  * formats[] is the client format request, as per Bind message conventions.
609  */
610 void
611 PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
612 {
613  int natts;
614  int i;
615 
616  /* Do nothing if portal won't return tuples */
617  if (portal->tupDesc == NULL)
618  return;
619  natts = portal->tupDesc->natts;
620  portal->formats = (int16 *)
622  natts * sizeof(int16));
623  if (nFormats > 1)
624  {
625  /* format specified for each column */
626  if (nFormats != natts)
627  ereport(ERROR,
628  (errcode(ERRCODE_PROTOCOL_VIOLATION),
629  errmsg("bind message has %d result formats but query has %d columns",
630  nFormats, natts)));
631  memcpy(portal->formats, formats, natts * sizeof(int16));
632  }
633  else if (nFormats > 0)
634  {
635  /* single format specified, use for all columns */
636  int16 format1 = formats[0];
637 
638  for (i = 0; i < natts; i++)
639  portal->formats[i] = format1;
640  }
641  else
642  {
643  /* use default format for all columns */
644  for (i = 0; i < natts; i++)
645  portal->formats[i] = 0;
646  }
647 }
648 
649 /*
650  * PortalRun
651  * Run a portal's query or queries.
652  *
653  * count <= 0 is interpreted as a no-op: the destination gets started up
654  * and shut down, but nothing else happens. Also, count == FETCH_ALL is
655  * interpreted as "all rows". Note that count is ignored in multi-query
656  * situations, where we always run the portal to completion.
657  *
658  * isTopLevel: true if query is being executed at backend "top level"
659  * (that is, directly from a client command message)
660  *
661  * dest: where to send output of primary (canSetTag) query
662  *
663  * altdest: where to send output of non-primary queries
664  *
665  * qc: where to store command completion status data.
666  * May be NULL if caller doesn't want status data.
667  *
668  * Returns true if the portal's execution is complete, false if it was
669  * suspended due to exhaustion of the count parameter.
670  */
671 bool
672 PortalRun(Portal portal, long count, bool isTopLevel, bool run_once,
673  DestReceiver *dest, DestReceiver *altdest,
674  QueryCompletion *qc)
675 {
676  bool result;
677  uint64 nprocessed;
678  ResourceOwner saveTopTransactionResourceOwner;
679  MemoryContext saveTopTransactionContext;
680  Portal saveActivePortal;
681  ResourceOwner saveResourceOwner;
682  MemoryContext savePortalContext;
683  MemoryContext saveMemoryContext;
684 
685  AssertArg(PortalIsValid(portal));
686 
687  TRACE_POSTGRESQL_QUERY_EXECUTE_START();
688 
689  /* Initialize empty completion data */
690  if (qc)
692 
694  {
695  elog(DEBUG3, "PortalRun");
696  /* PORTAL_MULTI_QUERY logs its own stats per query */
697  ResetUsage();
698  }
699 
700  /*
701  * Check for improper portal use, and mark portal active.
702  */
703  MarkPortalActive(portal);
704 
705  /* Set run_once flag. Shouldn't be clear if previously set. */
706  Assert(!portal->run_once || run_once);
707  portal->run_once = run_once;
708 
709  /*
710  * Set up global portal context pointers.
711  *
712  * We have to play a special game here to support utility commands like
713  * VACUUM and CLUSTER, which internally start and commit transactions.
714  * When we are called to execute such a command, CurrentResourceOwner will
715  * be pointing to the TopTransactionResourceOwner --- which will be
716  * destroyed and replaced in the course of the internal commit and
717  * restart. So we need to be prepared to restore it as pointing to the
718  * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
719  * internally starting whole new transactions is not good.)
720  * CurrentMemoryContext has a similar problem, but the other pointers we
721  * save here will be NULL or pointing to longer-lived objects.
722  */
723  saveTopTransactionResourceOwner = TopTransactionResourceOwner;
724  saveTopTransactionContext = TopTransactionContext;
725  saveActivePortal = ActivePortal;
726  saveResourceOwner = CurrentResourceOwner;
727  savePortalContext = PortalContext;
728  saveMemoryContext = CurrentMemoryContext;
729  PG_TRY();
730  {
731  ActivePortal = portal;
732  if (portal->resowner)
733  CurrentResourceOwner = portal->resowner;
734  PortalContext = portal->portalContext;
735 
737 
738  switch (portal->strategy)
739  {
740  case PORTAL_ONE_SELECT:
742  case PORTAL_ONE_MOD_WITH:
743  case PORTAL_UTIL_SELECT:
744 
745  /*
746  * If we have not yet run the command, do so, storing its
747  * results in the portal's tuplestore. But we don't do that
748  * for the PORTAL_ONE_SELECT case.
749  */
750  if (portal->strategy != PORTAL_ONE_SELECT && !portal->holdStore)
751  FillPortalStore(portal, isTopLevel);
752 
753  /*
754  * Now fetch desired portion of results.
755  */
756  nprocessed = PortalRunSelect(portal, true, count, dest);
757 
758  /*
759  * If the portal result contains a command tag and the caller
760  * gave us a pointer to store it, copy it and update the
761  * rowcount.
762  */
763  if (qc && portal->qc.commandTag != CMDTAG_UNKNOWN)
764  {
765  CopyQueryCompletion(qc, &portal->qc);
766  qc->nprocessed = nprocessed;
767  }
768 
769  /* Mark portal not active */
770  portal->status = PORTAL_READY;
771 
772  /*
773  * Since it's a forward fetch, say DONE iff atEnd is now true.
774  */
775  result = portal->atEnd;
776  break;
777 
778  case PORTAL_MULTI_QUERY:
779  PortalRunMulti(portal, isTopLevel, false,
780  dest, altdest, qc);
781 
782  /* Prevent portal's commands from being re-executed */
783  MarkPortalDone(portal);
784 
785  /* Always complete at end of RunMulti */
786  result = true;
787  break;
788 
789  default:
790  elog(ERROR, "unrecognized portal strategy: %d",
791  (int) portal->strategy);
792  result = false; /* keep compiler quiet */
793  break;
794  }
795  }
796  PG_CATCH();
797  {
798  /* Uncaught error while executing portal: mark it dead */
799  MarkPortalFailed(portal);
800 
801  /* Restore global vars and propagate error */
802  if (saveMemoryContext == saveTopTransactionContext)
804  else
805  MemoryContextSwitchTo(saveMemoryContext);
806  ActivePortal = saveActivePortal;
807  if (saveResourceOwner == saveTopTransactionResourceOwner)
809  else
810  CurrentResourceOwner = saveResourceOwner;
811  PortalContext = savePortalContext;
812 
813  PG_RE_THROW();
814  }
815  PG_END_TRY();
816 
817  if (saveMemoryContext == saveTopTransactionContext)
819  else
820  MemoryContextSwitchTo(saveMemoryContext);
821  ActivePortal = saveActivePortal;
822  if (saveResourceOwner == saveTopTransactionResourceOwner)
824  else
825  CurrentResourceOwner = saveResourceOwner;
826  PortalContext = savePortalContext;
827 
829  ShowUsage("EXECUTOR STATISTICS");
830 
831  TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
832 
833  return result;
834 }
835 
836 /*
837  * PortalRunSelect
838  * Execute a portal's query in PORTAL_ONE_SELECT mode, and also
839  * when fetching from a completed holdStore in PORTAL_ONE_RETURNING,
840  * PORTAL_ONE_MOD_WITH, and PORTAL_UTIL_SELECT cases.
841  *
842  * This handles simple N-rows-forward-or-backward cases. For more complex
843  * nonsequential access to a portal, see PortalRunFetch.
844  *
845  * count <= 0 is interpreted as a no-op: the destination gets started up
846  * and shut down, but nothing else happens. Also, count == FETCH_ALL is
847  * interpreted as "all rows". (cf FetchStmt.howMany)
848  *
849  * Caller must already have validated the Portal and done appropriate
850  * setup (cf. PortalRun).
851  *
852  * Returns number of rows processed (suitable for use in result tag)
853  */
854 static uint64
856  bool forward,
857  long count,
859 {
860  QueryDesc *queryDesc;
861  ScanDirection direction;
862  uint64 nprocessed;
863 
864  /*
865  * NB: queryDesc will be NULL if we are fetching from a held cursor or a
866  * completed utility query; can't use it in that path.
867  */
868  queryDesc = portal->queryDesc;
869 
870  /* Caller messed up if we have neither a ready query nor held data. */
871  Assert(queryDesc || portal->holdStore);
872 
873  /*
874  * Force the queryDesc destination to the right thing. This supports
875  * MOVE, for example, which will pass in dest = DestNone. This is okay to
876  * change as long as we do it on every fetch. (The Executor must not
877  * assume that dest never changes.)
878  */
879  if (queryDesc)
880  queryDesc->dest = dest;
881 
882  /*
883  * Determine which direction to go in, and check to see if we're already
884  * at the end of the available tuples in that direction. If so, set the
885  * direction to NoMovement to avoid trying to fetch any tuples. (This
886  * check exists because not all plan node types are robust about being
887  * called again if they've already returned NULL once.) Then call the
888  * executor (we must not skip this, because the destination needs to see a
889  * setup and shutdown even if no tuples are available). Finally, update
890  * the portal position state depending on the number of tuples that were
891  * retrieved.
892  */
893  if (forward)
894  {
895  if (portal->atEnd || count <= 0)
896  {
897  direction = NoMovementScanDirection;
898  count = 0; /* don't pass negative count to executor */
899  }
900  else
901  direction = ForwardScanDirection;
902 
903  /* In the executor, zero count processes all rows */
904  if (count == FETCH_ALL)
905  count = 0;
906 
907  if (portal->holdStore)
908  nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
909  else
910  {
911  PushActiveSnapshot(queryDesc->snapshot);
912  ExecutorRun(queryDesc, direction, (uint64) count,
913  portal->run_once);
914  nprocessed = queryDesc->estate->es_processed;
916  }
917 
918  if (!ScanDirectionIsNoMovement(direction))
919  {
920  if (nprocessed > 0)
921  portal->atStart = false; /* OK to go backward now */
922  if (count == 0 || nprocessed < (uint64) count)
923  portal->atEnd = true; /* we retrieved 'em all */
924  portal->portalPos += nprocessed;
925  }
926  }
927  else
928  {
929  if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
930  ereport(ERROR,
931  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
932  errmsg("cursor can only scan forward"),
933  errhint("Declare it with SCROLL option to enable backward scan.")));
934 
935  if (portal->atStart || count <= 0)
936  {
937  direction = NoMovementScanDirection;
938  count = 0; /* don't pass negative count to executor */
939  }
940  else
941  direction = BackwardScanDirection;
942 
943  /* In the executor, zero count processes all rows */
944  if (count == FETCH_ALL)
945  count = 0;
946 
947  if (portal->holdStore)
948  nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
949  else
950  {
951  PushActiveSnapshot(queryDesc->snapshot);
952  ExecutorRun(queryDesc, direction, (uint64) count,
953  portal->run_once);
954  nprocessed = queryDesc->estate->es_processed;
956  }
957 
958  if (!ScanDirectionIsNoMovement(direction))
959  {
960  if (nprocessed > 0 && portal->atEnd)
961  {
962  portal->atEnd = false; /* OK to go forward now */
963  portal->portalPos++; /* adjust for endpoint case */
964  }
965  if (count == 0 || nprocessed < (uint64) count)
966  {
967  portal->atStart = true; /* we retrieved 'em all */
968  portal->portalPos = 0;
969  }
970  else
971  {
972  portal->portalPos -= nprocessed;
973  }
974  }
975  }
976 
977  return nprocessed;
978 }
979 
980 /*
981  * FillPortalStore
982  * Run the query and load result tuples into the portal's tuple store.
983  *
984  * This is used for PORTAL_ONE_RETURNING, PORTAL_ONE_MOD_WITH, and
985  * PORTAL_UTIL_SELECT cases only.
986  */
987 static void
988 FillPortalStore(Portal portal, bool isTopLevel)
989 {
990  DestReceiver *treceiver;
991  QueryCompletion qc;
992 
994  PortalCreateHoldStore(portal);
995  treceiver = CreateDestReceiver(DestTuplestore);
997  portal->holdStore,
998  portal->holdContext,
999  false,
1000  NULL,
1001  NULL);
1002 
1003  switch (portal->strategy)
1004  {
1005  case PORTAL_ONE_RETURNING:
1006  case PORTAL_ONE_MOD_WITH:
1007 
1008  /*
1009  * Run the portal to completion just as for the default
1010  * PORTAL_MULTI_QUERY case, but send the primary query's output to
1011  * the tuplestore. Auxiliary query outputs are discarded. Set the
1012  * portal's holdSnapshot to the snapshot used (or a copy of it).
1013  */
1014  PortalRunMulti(portal, isTopLevel, true,
1015  treceiver, None_Receiver, &qc);
1016  break;
1017 
1018  case PORTAL_UTIL_SELECT:
1019  PortalRunUtility(portal, linitial_node(PlannedStmt, portal->stmts),
1020  isTopLevel, true, treceiver, &qc);
1021  break;
1022 
1023  default:
1024  elog(ERROR, "unsupported portal strategy: %d",
1025  (int) portal->strategy);
1026  break;
1027  }
1028 
1029  /* Override portal completion data with actual command results */
1030  if (qc.commandTag != CMDTAG_UNKNOWN)
1031  CopyQueryCompletion(&portal->qc, &qc);
1032 
1033  treceiver->rDestroy(treceiver);
1034 }
1035 
1036 /*
1037  * RunFromStore
1038  * Fetch tuples from the portal's tuple store.
1039  *
1040  * Calling conventions are similar to ExecutorRun, except that we
1041  * do not depend on having a queryDesc or estate. Therefore we return the
1042  * number of tuples processed as the result, not in estate->es_processed.
1043  *
1044  * One difference from ExecutorRun is that the destination receiver functions
1045  * are run in the caller's memory context (since we have no estate). Watch
1046  * out for memory leaks.
1047  */
1048 static uint64
1049 RunFromStore(Portal portal, ScanDirection direction, uint64 count,
1050  DestReceiver *dest)
1051 {
1052  uint64 current_tuple_count = 0;
1053  TupleTableSlot *slot;
1054 
1056 
1057  dest->rStartup(dest, CMD_SELECT, portal->tupDesc);
1058 
1059  if (ScanDirectionIsNoMovement(direction))
1060  {
1061  /* do nothing except start/stop the destination */
1062  }
1063  else
1064  {
1065  bool forward = ScanDirectionIsForward(direction);
1066 
1067  for (;;)
1068  {
1069  MemoryContext oldcontext;
1070  bool ok;
1071 
1072  oldcontext = MemoryContextSwitchTo(portal->holdContext);
1073 
1074  ok = tuplestore_gettupleslot(portal->holdStore, forward, false,
1075  slot);
1076 
1077  MemoryContextSwitchTo(oldcontext);
1078 
1079  if (!ok)
1080  break;
1081 
1082  /*
1083  * If we are not able to send the tuple, we assume the destination
1084  * has closed and no more tuples can be sent. If that's the case,
1085  * end the loop.
1086  */
1087  if (!dest->receiveSlot(slot, dest))
1088  break;
1089 
1090  ExecClearTuple(slot);
1091 
1092  /*
1093  * check our tuple count.. if we've processed the proper number
1094  * then quit, else loop again and process more tuples. Zero count
1095  * means no limit.
1096  */
1097  current_tuple_count++;
1098  if (count && count == current_tuple_count)
1099  break;
1100  }
1101  }
1102 
1103  dest->rShutdown(dest);
1104 
1106 
1107  return current_tuple_count;
1108 }
1109 
1110 /*
1111  * PortalRunUtility
1112  * Execute a utility statement inside a portal.
1113  */
1114 static void
1116  bool isTopLevel, bool setHoldSnapshot,
1118 {
1119  Node *utilityStmt = pstmt->utilityStmt;
1120  Snapshot snapshot;
1121 
1122  /*
1123  * Set snapshot if utility stmt needs one. Most reliable way to do this
1124  * seems to be to enumerate those that do not need one; this is a short
1125  * list. Transaction control, LOCK, and SET must *not* set a snapshot
1126  * since they need to be executable at the start of a transaction-snapshot
1127  * mode transaction without freezing a snapshot. By extension we allow
1128  * SHOW not to set a snapshot. The other stmts listed are just efficiency
1129  * hacks. Beware of listing anything that can modify the database --- if,
1130  * say, it has to update an index with expressions that invoke
1131  * user-defined functions, then it had better have a snapshot.
1132  */
1133  if (!(IsA(utilityStmt, TransactionStmt) ||
1134  IsA(utilityStmt, LockStmt) ||
1135  IsA(utilityStmt, VariableSetStmt) ||
1136  IsA(utilityStmt, VariableShowStmt) ||
1137  IsA(utilityStmt, ConstraintsSetStmt) ||
1138  /* efficiency hacks from here down */
1139  IsA(utilityStmt, FetchStmt) ||
1140  IsA(utilityStmt, ListenStmt) ||
1141  IsA(utilityStmt, NotifyStmt) ||
1142  IsA(utilityStmt, UnlistenStmt) ||
1143  IsA(utilityStmt, CheckPointStmt)))
1144  {
1145  snapshot = GetTransactionSnapshot();
1146  /* If told to, register the snapshot we're using and save in portal */
1147  if (setHoldSnapshot)
1148  {
1149  snapshot = RegisterSnapshot(snapshot);
1150  portal->holdSnapshot = snapshot;
1151  }
1152  PushActiveSnapshot(snapshot);
1153  /* PushActiveSnapshot might have copied the snapshot */
1154  snapshot = GetActiveSnapshot();
1155  }
1156  else
1157  snapshot = NULL;
1158 
1159  ProcessUtility(pstmt,
1160  portal->sourceText,
1162  portal->portalParams,
1163  portal->queryEnv,
1164  dest,
1165  qc);
1166 
1167  /* Some utility statements may change context on us */
1169 
1170  /*
1171  * Some utility commands may pop the ActiveSnapshot stack from under us,
1172  * so be careful to only pop the stack if our snapshot is still at the
1173  * top.
1174  */
1175  if (snapshot != NULL && ActiveSnapshotSet() &&
1176  snapshot == GetActiveSnapshot())
1178 }
1179 
1180 /*
1181  * PortalRunMulti
1182  * Execute a portal's queries in the general case (multi queries
1183  * or non-SELECT-like queries)
1184  */
1185 static void
1187  bool isTopLevel, bool setHoldSnapshot,
1188  DestReceiver *dest, DestReceiver *altdest,
1189  QueryCompletion *qc)
1190 {
1191  bool active_snapshot_set = false;
1192  ListCell *stmtlist_item;
1193 
1194  /*
1195  * If the destination is DestRemoteExecute, change to DestNone. The
1196  * reason is that the client won't be expecting any tuples, and indeed has
1197  * no way to know what they are, since there is no provision for Describe
1198  * to send a RowDescription message when this portal execution strategy is
1199  * in effect. This presently will only affect SELECT commands added to
1200  * non-SELECT queries by rewrite rules: such commands will be executed,
1201  * but the results will be discarded unless you use "simple Query"
1202  * protocol.
1203  */
1204  if (dest->mydest == DestRemoteExecute)
1205  dest = None_Receiver;
1206  if (altdest->mydest == DestRemoteExecute)
1207  altdest = None_Receiver;
1208 
1209  /*
1210  * Loop to handle the individual queries generated from a single parsetree
1211  * by analysis and rewrite.
1212  */
1213  foreach(stmtlist_item, portal->stmts)
1214  {
1215  PlannedStmt *pstmt = lfirst_node(PlannedStmt, stmtlist_item);
1216 
1217  /*
1218  * If we got a cancel signal in prior command, quit
1219  */
1221 
1222  if (pstmt->utilityStmt == NULL)
1223  {
1224  /*
1225  * process a plannable query.
1226  */
1227  TRACE_POSTGRESQL_QUERY_EXECUTE_START();
1228 
1229  if (log_executor_stats)
1230  ResetUsage();
1231 
1232  /*
1233  * Must always have a snapshot for plannable queries. First time
1234  * through, take a new snapshot; for subsequent queries in the
1235  * same portal, just update the snapshot's copy of the command
1236  * counter.
1237  */
1238  if (!active_snapshot_set)
1239  {
1240  Snapshot snapshot = GetTransactionSnapshot();
1241 
1242  /* If told to, register the snapshot and save in portal */
1243  if (setHoldSnapshot)
1244  {
1245  snapshot = RegisterSnapshot(snapshot);
1246  portal->holdSnapshot = snapshot;
1247  }
1248 
1249  /*
1250  * We can't have the holdSnapshot also be the active one,
1251  * because UpdateActiveSnapshotCommandId would complain. So
1252  * force an extra snapshot copy. Plain PushActiveSnapshot
1253  * would have copied the transaction snapshot anyway, so this
1254  * only adds a copy step when setHoldSnapshot is true. (It's
1255  * okay for the command ID of the active snapshot to diverge
1256  * from what holdSnapshot has.)
1257  */
1258  PushCopiedSnapshot(snapshot);
1259  active_snapshot_set = true;
1260  }
1261  else
1263 
1264  if (pstmt->canSetTag)
1265  {
1266  /* statement can set tag string */
1267  ProcessQuery(pstmt,
1268  portal->sourceText,
1269  portal->portalParams,
1270  portal->queryEnv,
1271  dest, qc);
1272  }
1273  else
1274  {
1275  /* stmt added by rewrite cannot set tag */
1276  ProcessQuery(pstmt,
1277  portal->sourceText,
1278  portal->portalParams,
1279  portal->queryEnv,
1280  altdest, NULL);
1281  }
1282 
1283  if (log_executor_stats)
1284  ShowUsage("EXECUTOR STATISTICS");
1285 
1286  TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
1287  }
1288  else
1289  {
1290  /*
1291  * process utility functions (create, destroy, etc..)
1292  *
1293  * We must not set a snapshot here for utility commands (if one is
1294  * needed, PortalRunUtility will do it). If a utility command is
1295  * alone in a portal then everything's fine. The only case where
1296  * a utility command can be part of a longer list is that rules
1297  * are allowed to include NotifyStmt. NotifyStmt doesn't care
1298  * whether it has a snapshot or not, so we just leave the current
1299  * snapshot alone if we have one.
1300  */
1301  if (pstmt->canSetTag)
1302  {
1303  Assert(!active_snapshot_set);
1304  /* statement can set tag string */
1305  PortalRunUtility(portal, pstmt, isTopLevel, false,
1306  dest, qc);
1307  }
1308  else
1309  {
1310  Assert(IsA(pstmt->utilityStmt, NotifyStmt));
1311  /* stmt added by rewrite cannot set tag */
1312  PortalRunUtility(portal, pstmt, isTopLevel, false,
1313  altdest, NULL);
1314  }
1315  }
1316 
1317  /*
1318  * Increment command counter between queries, but not after the last
1319  * one.
1320  */
1321  if (lnext(portal->stmts, stmtlist_item) != NULL)
1323 
1324  /*
1325  * Clear subsidiary contexts to recover temporary memory.
1326  */
1328 
1330  }
1331 
1332  /* Pop the snapshot if we pushed one. */
1333  if (active_snapshot_set)
1335 
1336  /*
1337  * If a query completion data was supplied, use it. Otherwise use the
1338  * portal's query completion data.
1339  *
1340  * Exception: Clients expect INSERT/UPDATE/DELETE tags to have counts, so
1341  * fake them with zeros. This can happen with DO INSTEAD rules if there
1342  * is no replacement query of the same type as the original. We print "0
1343  * 0" here because technically there is no query of the matching tag type,
1344  * and printing a non-zero count for a different query type seems wrong,
1345  * e.g. an INSERT that does an UPDATE instead should not print "0 1" if
1346  * one row was updated. See QueryRewrite(), step 3, for details.
1347  */
1348  if (qc && qc->commandTag == CMDTAG_UNKNOWN)
1349  {
1350  if (portal->qc.commandTag != CMDTAG_UNKNOWN)
1351  CopyQueryCompletion(qc, &portal->qc);
1352  /* If the caller supplied a qc, we should have set it by now. */
1353  Assert(qc->commandTag != CMDTAG_UNKNOWN);
1354  }
1355 }
1356 
1357 /*
1358  * PortalRunFetch
1359  * Variant form of PortalRun that supports SQL FETCH directions.
1360  *
1361  * Note: we presently assume that no callers of this want isTopLevel = true.
1362  *
1363  * count <= 0 is interpreted as a no-op: the destination gets started up
1364  * and shut down, but nothing else happens. Also, count == FETCH_ALL is
1365  * interpreted as "all rows". (cf FetchStmt.howMany)
1366  *
1367  * Returns number of rows processed (suitable for use in result tag)
1368  */
1369 uint64
1371  FetchDirection fdirection,
1372  long count,
1373  DestReceiver *dest)
1374 {
1375  uint64 result;
1376  Portal saveActivePortal;
1377  ResourceOwner saveResourceOwner;
1378  MemoryContext savePortalContext;
1379  MemoryContext oldContext;
1380 
1381  AssertArg(PortalIsValid(portal));
1382 
1383  /*
1384  * Check for improper portal use, and mark portal active.
1385  */
1386  MarkPortalActive(portal);
1387 
1388  /* If supporting FETCH, portal can't be run-once. */
1389  Assert(!portal->run_once);
1390 
1391  /*
1392  * Set up global portal context pointers.
1393  */
1394  saveActivePortal = ActivePortal;
1395  saveResourceOwner = CurrentResourceOwner;
1396  savePortalContext = PortalContext;
1397  PG_TRY();
1398  {
1399  ActivePortal = portal;
1400  if (portal->resowner)
1401  CurrentResourceOwner = portal->resowner;
1402  PortalContext = portal->portalContext;
1403 
1404  oldContext = MemoryContextSwitchTo(PortalContext);
1405 
1406  switch (portal->strategy)
1407  {
1408  case PORTAL_ONE_SELECT:
1409  result = DoPortalRunFetch(portal, fdirection, count, dest);
1410  break;
1411 
1412  case PORTAL_ONE_RETURNING:
1413  case PORTAL_ONE_MOD_WITH:
1414  case PORTAL_UTIL_SELECT:
1415 
1416  /*
1417  * If we have not yet run the command, do so, storing its
1418  * results in the portal's tuplestore.
1419  */
1420  if (!portal->holdStore)
1421  FillPortalStore(portal, false /* isTopLevel */ );
1422 
1423  /*
1424  * Now fetch desired portion of results.
1425  */
1426  result = DoPortalRunFetch(portal, fdirection, count, dest);
1427  break;
1428 
1429  default:
1430  elog(ERROR, "unsupported portal strategy");
1431  result = 0; /* keep compiler quiet */
1432  break;
1433  }
1434  }
1435  PG_CATCH();
1436  {
1437  /* Uncaught error while executing portal: mark it dead */
1438  MarkPortalFailed(portal);
1439 
1440  /* Restore global vars and propagate error */
1441  ActivePortal = saveActivePortal;
1442  CurrentResourceOwner = saveResourceOwner;
1443  PortalContext = savePortalContext;
1444 
1445  PG_RE_THROW();
1446  }
1447  PG_END_TRY();
1448 
1449  MemoryContextSwitchTo(oldContext);
1450 
1451  /* Mark portal not active */
1452  portal->status = PORTAL_READY;
1453 
1454  ActivePortal = saveActivePortal;
1455  CurrentResourceOwner = saveResourceOwner;
1456  PortalContext = savePortalContext;
1457 
1458  return result;
1459 }
1460 
1461 /*
1462  * DoPortalRunFetch
1463  * Guts of PortalRunFetch --- the portal context is already set up
1464  *
1465  * count <= 0 is interpreted as a no-op: the destination gets started up
1466  * and shut down, but nothing else happens. Also, count == FETCH_ALL is
1467  * interpreted as "all rows". (cf FetchStmt.howMany)
1468  *
1469  * Returns number of rows processed (suitable for use in result tag)
1470  */
1471 static uint64
1473  FetchDirection fdirection,
1474  long count,
1475  DestReceiver *dest)
1476 {
1477  bool forward;
1478 
1479  Assert(portal->strategy == PORTAL_ONE_SELECT ||
1480  portal->strategy == PORTAL_ONE_RETURNING ||
1481  portal->strategy == PORTAL_ONE_MOD_WITH ||
1482  portal->strategy == PORTAL_UTIL_SELECT);
1483 
1484  switch (fdirection)
1485  {
1486  case FETCH_FORWARD:
1487  if (count < 0)
1488  {
1489  fdirection = FETCH_BACKWARD;
1490  count = -count;
1491  }
1492  /* fall out of switch to share code with FETCH_BACKWARD */
1493  break;
1494  case FETCH_BACKWARD:
1495  if (count < 0)
1496  {
1497  fdirection = FETCH_FORWARD;
1498  count = -count;
1499  }
1500  /* fall out of switch to share code with FETCH_FORWARD */
1501  break;
1502  case FETCH_ABSOLUTE:
1503  if (count > 0)
1504  {
1505  /*
1506  * Definition: Rewind to start, advance count-1 rows, return
1507  * next row (if any).
1508  *
1509  * In practice, if the goal is less than halfway back to the
1510  * start, it's better to scan from where we are.
1511  *
1512  * Also, if current portalPos is outside the range of "long",
1513  * do it the hard way to avoid possible overflow of the count
1514  * argument to PortalRunSelect. We must exclude exactly
1515  * LONG_MAX, as well, lest the count look like FETCH_ALL.
1516  *
1517  * In any case, we arrange to fetch the target row going
1518  * forwards.
1519  */
1520  if ((uint64) (count - 1) <= portal->portalPos / 2 ||
1521  portal->portalPos >= (uint64) LONG_MAX)
1522  {
1523  DoPortalRewind(portal);
1524  if (count > 1)
1525  PortalRunSelect(portal, true, count - 1,
1526  None_Receiver);
1527  }
1528  else
1529  {
1530  long pos = (long) portal->portalPos;
1531 
1532  if (portal->atEnd)
1533  pos++; /* need one extra fetch if off end */
1534  if (count <= pos)
1535  PortalRunSelect(portal, false, pos - count + 1,
1536  None_Receiver);
1537  else if (count > pos + 1)
1538  PortalRunSelect(portal, true, count - pos - 1,
1539  None_Receiver);
1540  }
1541  return PortalRunSelect(portal, true, 1L, dest);
1542  }
1543  else if (count < 0)
1544  {
1545  /*
1546  * Definition: Advance to end, back up abs(count)-1 rows,
1547  * return prior row (if any). We could optimize this if we
1548  * knew in advance where the end was, but typically we won't.
1549  * (Is it worth considering case where count > half of size of
1550  * query? We could rewind once we know the size ...)
1551  */
1552  PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1553  if (count < -1)
1554  PortalRunSelect(portal, false, -count - 1, None_Receiver);
1555  return PortalRunSelect(portal, false, 1L, dest);
1556  }
1557  else
1558  {
1559  /* count == 0 */
1560  /* Rewind to start, return zero rows */
1561  DoPortalRewind(portal);
1562  return PortalRunSelect(portal, true, 0L, dest);
1563  }
1564  break;
1565  case FETCH_RELATIVE:
1566  if (count > 0)
1567  {
1568  /*
1569  * Definition: advance count-1 rows, return next row (if any).
1570  */
1571  if (count > 1)
1572  PortalRunSelect(portal, true, count - 1, None_Receiver);
1573  return PortalRunSelect(portal, true, 1L, dest);
1574  }
1575  else if (count < 0)
1576  {
1577  /*
1578  * Definition: back up abs(count)-1 rows, return prior row (if
1579  * any).
1580  */
1581  if (count < -1)
1582  PortalRunSelect(portal, false, -count - 1, None_Receiver);
1583  return PortalRunSelect(portal, false, 1L, dest);
1584  }
1585  else
1586  {
1587  /* count == 0 */
1588  /* Same as FETCH FORWARD 0, so fall out of switch */
1589  fdirection = FETCH_FORWARD;
1590  }
1591  break;
1592  default:
1593  elog(ERROR, "bogus direction");
1594  break;
1595  }
1596 
1597  /*
1598  * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1599  * >= 0.
1600  */
1601  forward = (fdirection == FETCH_FORWARD);
1602 
1603  /*
1604  * Zero count means to re-fetch the current row, if any (per SQL)
1605  */
1606  if (count == 0)
1607  {
1608  bool on_row;
1609 
1610  /* Are we sitting on a row? */
1611  on_row = (!portal->atStart && !portal->atEnd);
1612 
1613  if (dest->mydest == DestNone)
1614  {
1615  /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1616  return on_row ? 1 : 0;
1617  }
1618  else
1619  {
1620  /*
1621  * If we are sitting on a row, back up one so we can re-fetch it.
1622  * If we are not sitting on a row, we still have to start up and
1623  * shut down the executor so that the destination is initialized
1624  * and shut down correctly; so keep going. To PortalRunSelect,
1625  * count == 0 means we will retrieve no row.
1626  */
1627  if (on_row)
1628  {
1629  PortalRunSelect(portal, false, 1L, None_Receiver);
1630  /* Set up to fetch one row forward */
1631  count = 1;
1632  forward = true;
1633  }
1634  }
1635  }
1636 
1637  /*
1638  * Optimize MOVE BACKWARD ALL into a Rewind.
1639  */
1640  if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1641  {
1642  uint64 result = portal->portalPos;
1643 
1644  if (result > 0 && !portal->atEnd)
1645  result--;
1646  DoPortalRewind(portal);
1647  return result;
1648  }
1649 
1650  return PortalRunSelect(portal, forward, count, dest);
1651 }
1652 
1653 /*
1654  * DoPortalRewind - rewind a Portal to starting point
1655  */
1656 static void
1658 {
1659  QueryDesc *queryDesc;
1660 
1661  /* Rewind holdStore, if we have one */
1662  if (portal->holdStore)
1663  {
1664  MemoryContext oldcontext;
1665 
1666  oldcontext = MemoryContextSwitchTo(portal->holdContext);
1667  tuplestore_rescan(portal->holdStore);
1668  MemoryContextSwitchTo(oldcontext);
1669  }
1670 
1671  /* Rewind executor, if active */
1672  queryDesc = portal->queryDesc;
1673  if (queryDesc)
1674  {
1675  PushActiveSnapshot(queryDesc->snapshot);
1676  ExecutorRewind(queryDesc);
1678  }
1679 
1680  portal->atStart = true;
1681  portal->atEnd = false;
1682  portal->portalPos = 0;
1683 }
void tuplestore_rescan(Tuplestorestate *state)
Definition: tuplestore.c:1233
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:119
signed short int16
Definition: c.h:361
#define NIL
Definition: pg_list.h:65
static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count, DestReceiver *dest)
Definition: pquery.c:1049
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:783
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
int errhint(const char *fmt,...)
Definition: elog.c:1071
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:611
#define AssertState(condition)
Definition: c.h:748
bool atEnd
Definition: portal.h:191
FetchDirection
Definition: parsenodes.h:2740
EState * estate
Definition: execdesc.h:48
MemoryContext TopTransactionContext
Definition: mcxt.c:49
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:430
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define ScanDirectionIsForward(direction)
Definition: sdir.h:55
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
TupleDesc ExecCleanTypeFromTL(List *targetList)
Definition: execTuples.c:1920
#define DEBUG3
Definition: elog.h:23
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:144
void ShowUsage(const char *title)
Definition: postgres.c:4618
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
CommandDest mydest
Definition: dest.h:129
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void SetTuplestoreDestReceiverParams(DestReceiver *self, Tuplestorestate *tStore, MemoryContext tContext, bool detoast, TupleDesc target_tupdesc, const char *map_failure_msg)
void MarkPortalActive(Portal portal)
Definition: portalmem.c:394
uint64 PortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1370
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
Definition: nodes.h:529
int errcode(int sqlerrcode)
Definition: elog.c:610
MemoryContext holdContext
Definition: portal.h:169
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Node * utilityStmt
Definition: parsenodes.h:120
List * stmts
Definition: portal.h:138
#define linitial_node(type, l)
Definition: pg_list.h:198
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
DestReceiver * None_Receiver
Definition: dest.c:96
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
MemoryContext portalContext
Definition: portal.h:120
static uint64 PortalRunSelect(Portal portal, bool forward, long count, DestReceiver *dest)
Definition: pquery.c:855
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2708
static uint64 DoPortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1472
struct Plan * planTree
Definition: plannodes.h:64
List * targetList
Definition: parsenodes.h:140
Snapshot snapshot
Definition: execdesc.h:39
bool run_once
Definition: portal.h:147
int instrument_options
Definition: execdesc.h:44
MemoryContext PortalContext
Definition: mcxt.c:53
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:1115
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:672
void ResetUsage(void)
Definition: postgres.c:4611
QueryEnvironment * queryEnv
Definition: execdesc.h:43
void pfree(void *pointer)
Definition: mcxt.c:1056
ParamListInfo portalParams
Definition: portal.h:141
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition: portalmem.c:151
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
PlanState * planstate
Definition: execdesc.h:49
uint64 nprocessed
Definition: cmdtag.h:31
List * FetchStatementTargetList(Node *stmt)
Definition: pquery.c:345
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:38
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:988
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:122
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:771
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
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void MarkPortalDone(Portal portal)
Definition: portalmem.c:413
Definition: dest.h:89
PortalStrategy
Definition: portal.h:89
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
bool hasReturning
Definition: plannodes.h:50
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
ScanDirection
Definition: sdir.h:22
ParamListInfo params
Definition: execdesc.h:42
Node * utilityStmt
Definition: plannodes.h:92
bool UtilityReturnsTuples(Node *parsetree)
Definition: utility.c:1913
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:853
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
PortalStrategy strategy
Definition: portal.h:145
List * returningList
Definition: parsenodes.h:146
char * portalname
Definition: parsenodes.h:2757
#define EXEC_FLAG_REWIND
Definition: executor.h:57
#define AssertArg(condition)
Definition: c.h:747
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
QueryDesc * queryDesc
Definition: portal.h:156
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:123
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:256
#define PortalIsValid(p)
Definition: portal.h:203
void ExecutorRewind(QueryDesc *queryDesc)
Definition: execMain.c:528
bool canSetTag
Definition: plannodes.h:54
bool ismove
Definition: parsenodes.h:2758
int16 * formats
Definition: portal.h:161
void CommandCounterIncrement(void)
Definition: xact.c:1006
CmdType commandType
Definition: plannodes.h:46
bool already_executed
Definition: execdesc.h:52
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
const char * sourceText
Definition: portal.h:135
TupleDesc tupDesc
Definition: portal.h:159
CommandTag commandTag
Definition: cmdtag.h:30
List * FetchPreparedStatementTargetList(PreparedStatement *stmt)
Definition: prepare.c:524
#define ereport(elevel,...)
Definition: elog.h:144
CmdType commandType
Definition: parsenodes.h:112
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
#define PG_CATCH()
Definition: elog.h:305
struct Instrumentation * totaltime
Definition: execdesc.h:55
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
QueryCompletion qc
Definition: portal.h:137
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
bool hasModifyingCTE
Definition: plannodes.h:52
uint64 es_processed
Definition: execnodes.h:559
bool canSetTag
Definition: parsenodes.h:118
static int list_length(const List *l)
Definition: pg_list.h:169
Snapshot holdSnapshot
Definition: portal.h:179
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:336
void PortalCreateHoldStore(Portal portal)
Definition: portalmem.c:330
QueryEnvironment * queryEnv
Definition: portal.h:142
PortalStrategy ChoosePortalStrategy(List *stmts)
Definition: pquery.c:206
#define nodeTag(nodeptr)
Definition: nodes.h:534
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:125
List * targetlist
Definition: plannodes.h:142
const char * sourceText
Definition: execdesc.h:38
DestReceiver * dest
Definition: execdesc.h:41
ResourceOwner resowner
Definition: portal.h:121
bool atStart
Definition: portal.h:190
void * palloc(Size size)
Definition: mcxt.c:949
Tuplestorestate * holdStore
Definition: portal.h:168
int errmsg(const char *fmt,...)
Definition: elog.c:824
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
#define elog(elevel,...)
Definition: elog.h:214
int i
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2707
bool log_executor_stats
Definition: guc.c:517
char * name
Definition: parsenodes.h:3438
bool hasModifyingCTE
Definition: parsenodes.h:131
static void ProcessQuery(PlannedStmt *plan, const char *sourceText, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:136
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
int cursorOptions
Definition: portal.h:146
PlannedStmt * plannedstmt
Definition: execdesc.h:37
static void DoPortalRewind(Portal portal)
Definition: pquery.c:1657
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:323
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:1186
#define PG_TRY()
Definition: elog.h:295
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:469
Definition: pg_list.h:50
TupleDesc UtilityTupleDescriptor(Node *parsetree)
Definition: utility.c:1969
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:501
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
#define PG_END_TRY()
Definition: elog.h:320
uint64 portalPos
Definition: portal.h:192
#define FETCH_ALL
Definition: parsenodes.h:2750