PostgreSQL Source Code  git master
pquery.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/xact.h"
#include "commands/prepare.h"
#include "executor/tstoreReceiver.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
Include dependency graph for pquery.c:

Go to the source code of this file.

Functions

static void ProcessQuery (PlannedStmt *plan, const char *sourceText, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
 
static void FillPortalStore (Portal portal, bool isTopLevel)
 
static uint64 RunFromStore (Portal portal, ScanDirection direction, uint64 count, DestReceiver *dest)
 
static uint64 PortalRunSelect (Portal portal, bool forward, long count, DestReceiver *dest)
 
static void PortalRunUtility (Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
 
static void PortalRunMulti (Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
 
static uint64 DoPortalRunFetch (Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
 
static void DoPortalRewind (Portal portal)
 
QueryDescCreateQueryDesc (PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
 
void FreeQueryDesc (QueryDesc *qdesc)
 
PortalStrategy ChoosePortalStrategy (List *stmts)
 
ListFetchPortalTargetList (Portal portal)
 
ListFetchStatementTargetList (Node *stmt)
 
void PortalStart (Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
 
void PortalSetResultFormat (Portal portal, int nFormats, int16 *formats)
 
bool PortalRun (Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
 
uint64 PortalRunFetch (Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
 

Variables

Portal ActivePortal = NULL
 

Function Documentation

◆ ChoosePortalStrategy()

PortalStrategy ChoosePortalStrategy ( List stmts)

Definition at line 206 of file pquery.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_SELECT, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, elog, ERROR, PlannedStmt::hasModifyingCTE, Query::hasModifyingCTE, PlannedStmt::hasReturning, IsA, lfirst, linitial, list_length(), NIL, nodeTag, PORTAL_MULTI_QUERY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_UTIL_SELECT, Query::returningList, UtilityReturnsTuples(), PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by PlanCacheComputeResultDesc(), and PortalStart().

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 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Definition: nodes.h:529
Node * utilityStmt
Definition: parsenodes.h:120
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
bool hasReturning
Definition: plannodes.h:50
Node * utilityStmt
Definition: plannodes.h:92
bool UtilityReturnsTuples(Node *parsetree)
Definition: utility.c:1913
List * returningList
Definition: parsenodes.h:146
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:112
#define lfirst(lc)
Definition: pg_list.h:190
bool hasModifyingCTE
Definition: plannodes.h:52
bool canSetTag
Definition: parsenodes.h:118
static int list_length(const List *l)
Definition: pg_list.h:169
#define nodeTag(nodeptr)
Definition: nodes.h:534
#define elog(elevel,...)
Definition: elog.h:214
bool hasModifyingCTE
Definition: parsenodes.h:131

◆ CreateQueryDesc()

QueryDesc* CreateQueryDesc ( PlannedStmt plannedstmt,
const char *  sourceText,
Snapshot  snapshot,
Snapshot  crosscheck_snapshot,
DestReceiver dest,
ParamListInfo  params,
QueryEnvironment queryEnv,
int  instrument_options 
)

Definition at line 67 of file pquery.c.

References QueryDesc::already_executed, PlannedStmt::commandType, QueryDesc::crosscheck_snapshot, QueryDesc::dest, generate_unaccent_rules::dest, QueryDesc::estate, QueryDesc::instrument_options, QueryDesc::operation, palloc(), QueryDesc::params, QueryDesc::plannedstmt, QueryDesc::planstate, QueryDesc::queryEnv, RegisterSnapshot(), QueryDesc::snapshot, QueryDesc::sourceText, QueryDesc::totaltime, and QueryDesc::tupDesc.

Referenced by _SPI_execute_plan(), BeginCopy(), ExecCreateTableAs(), ExecParallelGetQueryDesc(), execute_sql_string(), ExplainOnePlan(), PortalStart(), postquel_start(), ProcessQuery(), and refresh_matview_datafill().

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 }
EState * estate
Definition: execdesc.h:48
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
Snapshot snapshot
Definition: execdesc.h:39
int instrument_options
Definition: execdesc.h:44
QueryEnvironment * queryEnv
Definition: execdesc.h:43
PlanState * planstate
Definition: execdesc.h:49
ParamListInfo params
Definition: execdesc.h:42
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
CmdType commandType
Definition: plannodes.h:46
bool already_executed
Definition: execdesc.h:52
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
struct Instrumentation * totaltime
Definition: execdesc.h:55
const char * sourceText
Definition: execdesc.h:38
DestReceiver * dest
Definition: execdesc.h:41
void * palloc(Size size)
Definition: mcxt.c:949
PlannedStmt * plannedstmt
Definition: execdesc.h:37

◆ DoPortalRewind()

static void DoPortalRewind ( Portal  portal)
static

Definition at line 1655 of file pquery.c.

References PortalData::atEnd, PortalData::atStart, ExecutorRewind(), PortalData::holdContext, PortalData::holdStore, MemoryContextSwitchTo(), PopActiveSnapshot(), PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, QueryDesc::snapshot, and tuplestore_rescan().

Referenced by DoPortalRunFetch().

1656 {
1657  QueryDesc *queryDesc;
1658 
1659  /* Rewind holdStore, if we have one */
1660  if (portal->holdStore)
1661  {
1662  MemoryContext oldcontext;
1663 
1664  oldcontext = MemoryContextSwitchTo(portal->holdContext);
1665  tuplestore_rescan(portal->holdStore);
1666  MemoryContextSwitchTo(oldcontext);
1667  }
1668 
1669  /* Rewind executor, if active */
1670  queryDesc = portal->queryDesc;
1671  if (queryDesc)
1672  {
1673  PushActiveSnapshot(queryDesc->snapshot);
1674  ExecutorRewind(queryDesc);
1676  }
1677 
1678  portal->atStart = true;
1679  portal->atEnd = false;
1680  portal->portalPos = 0;
1681 }
void tuplestore_rescan(Tuplestorestate *state)
Definition: tuplestore.c:1233
bool atEnd
Definition: portal.h:191
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext holdContext
Definition: portal.h:169
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Snapshot snapshot
Definition: execdesc.h:39
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
QueryDesc * queryDesc
Definition: portal.h:156
void ExecutorRewind(QueryDesc *queryDesc)
Definition: execMain.c:528
bool atStart
Definition: portal.h:190
Tuplestorestate * holdStore
Definition: portal.h:168
uint64 portalPos
Definition: portal.h:192

◆ DoPortalRunFetch()

static uint64 DoPortalRunFetch ( Portal  portal,
FetchDirection  fdirection,
long  count,
DestReceiver dest 
)
static

Definition at line 1470 of file pquery.c.

References Assert, PortalData::atEnd, PortalData::atStart, DestNone, DoPortalRewind(), elog, ERROR, FETCH_ABSOLUTE, FETCH_ALL, FETCH_BACKWARD, FETCH_FORWARD, FETCH_RELATIVE, _DestReceiver::mydest, None_Receiver, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_UTIL_SELECT, PortalData::portalPos, PortalRunSelect(), and PortalData::strategy.

Referenced by PortalRunFetch().

1474 {
1475  bool forward;
1476 
1477  Assert(portal->strategy == PORTAL_ONE_SELECT ||
1478  portal->strategy == PORTAL_ONE_RETURNING ||
1479  portal->strategy == PORTAL_ONE_MOD_WITH ||
1480  portal->strategy == PORTAL_UTIL_SELECT);
1481 
1482  switch (fdirection)
1483  {
1484  case FETCH_FORWARD:
1485  if (count < 0)
1486  {
1487  fdirection = FETCH_BACKWARD;
1488  count = -count;
1489  }
1490  /* fall out of switch to share code with FETCH_BACKWARD */
1491  break;
1492  case FETCH_BACKWARD:
1493  if (count < 0)
1494  {
1495  fdirection = FETCH_FORWARD;
1496  count = -count;
1497  }
1498  /* fall out of switch to share code with FETCH_FORWARD */
1499  break;
1500  case FETCH_ABSOLUTE:
1501  if (count > 0)
1502  {
1503  /*
1504  * Definition: Rewind to start, advance count-1 rows, return
1505  * next row (if any).
1506  *
1507  * In practice, if the goal is less than halfway back to the
1508  * start, it's better to scan from where we are.
1509  *
1510  * Also, if current portalPos is outside the range of "long",
1511  * do it the hard way to avoid possible overflow of the count
1512  * argument to PortalRunSelect. We must exclude exactly
1513  * LONG_MAX, as well, lest the count look like FETCH_ALL.
1514  *
1515  * In any case, we arrange to fetch the target row going
1516  * forwards.
1517  */
1518  if ((uint64) (count - 1) <= portal->portalPos / 2 ||
1519  portal->portalPos >= (uint64) LONG_MAX)
1520  {
1521  DoPortalRewind(portal);
1522  if (count > 1)
1523  PortalRunSelect(portal, true, count - 1,
1524  None_Receiver);
1525  }
1526  else
1527  {
1528  long pos = (long) portal->portalPos;
1529 
1530  if (portal->atEnd)
1531  pos++; /* need one extra fetch if off end */
1532  if (count <= pos)
1533  PortalRunSelect(portal, false, pos - count + 1,
1534  None_Receiver);
1535  else if (count > pos + 1)
1536  PortalRunSelect(portal, true, count - pos - 1,
1537  None_Receiver);
1538  }
1539  return PortalRunSelect(portal, true, 1L, dest);
1540  }
1541  else if (count < 0)
1542  {
1543  /*
1544  * Definition: Advance to end, back up abs(count)-1 rows,
1545  * return prior row (if any). We could optimize this if we
1546  * knew in advance where the end was, but typically we won't.
1547  * (Is it worth considering case where count > half of size of
1548  * query? We could rewind once we know the size ...)
1549  */
1550  PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1551  if (count < -1)
1552  PortalRunSelect(portal, false, -count - 1, None_Receiver);
1553  return PortalRunSelect(portal, false, 1L, dest);
1554  }
1555  else
1556  {
1557  /* count == 0 */
1558  /* Rewind to start, return zero rows */
1559  DoPortalRewind(portal);
1560  return PortalRunSelect(portal, true, 0L, dest);
1561  }
1562  break;
1563  case FETCH_RELATIVE:
1564  if (count > 0)
1565  {
1566  /*
1567  * Definition: advance count-1 rows, return next row (if any).
1568  */
1569  if (count > 1)
1570  PortalRunSelect(portal, true, count - 1, None_Receiver);
1571  return PortalRunSelect(portal, true, 1L, dest);
1572  }
1573  else if (count < 0)
1574  {
1575  /*
1576  * Definition: back up abs(count)-1 rows, return prior row (if
1577  * any).
1578  */
1579  if (count < -1)
1580  PortalRunSelect(portal, false, -count - 1, None_Receiver);
1581  return PortalRunSelect(portal, false, 1L, dest);
1582  }
1583  else
1584  {
1585  /* count == 0 */
1586  /* Same as FETCH FORWARD 0, so fall out of switch */
1587  fdirection = FETCH_FORWARD;
1588  }
1589  break;
1590  default:
1591  elog(ERROR, "bogus direction");
1592  break;
1593  }
1594 
1595  /*
1596  * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1597  * >= 0.
1598  */
1599  forward = (fdirection == FETCH_FORWARD);
1600 
1601  /*
1602  * Zero count means to re-fetch the current row, if any (per SQL)
1603  */
1604  if (count == 0)
1605  {
1606  bool on_row;
1607 
1608  /* Are we sitting on a row? */
1609  on_row = (!portal->atStart && !portal->atEnd);
1610 
1611  if (dest->mydest == DestNone)
1612  {
1613  /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1614  return on_row ? 1 : 0;
1615  }
1616  else
1617  {
1618  /*
1619  * If we are sitting on a row, back up one so we can re-fetch it.
1620  * If we are not sitting on a row, we still have to start up and
1621  * shut down the executor so that the destination is initialized
1622  * and shut down correctly; so keep going. To PortalRunSelect,
1623  * count == 0 means we will retrieve no row.
1624  */
1625  if (on_row)
1626  {
1627  PortalRunSelect(portal, false, 1L, None_Receiver);
1628  /* Set up to fetch one row forward */
1629  count = 1;
1630  forward = true;
1631  }
1632  }
1633  }
1634 
1635  /*
1636  * Optimize MOVE BACKWARD ALL into a Rewind.
1637  */
1638  if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1639  {
1640  uint64 result = portal->portalPos;
1641 
1642  if (result > 0 && !portal->atEnd)
1643  result--;
1644  DoPortalRewind(portal);
1645  return result;
1646  }
1647 
1648  return PortalRunSelect(portal, forward, count, dest);
1649 }
bool atEnd
Definition: portal.h:191
CommandDest mydest
Definition: dest.h:129
DestReceiver * None_Receiver
Definition: dest.c:96
static uint64 PortalRunSelect(Portal portal, bool forward, long count, DestReceiver *dest)
Definition: pquery.c:855
#define ERROR
Definition: elog.h:43
Definition: dest.h:89
PortalStrategy strategy
Definition: portal.h:145
#define Assert(condition)
Definition: c.h:738
bool atStart
Definition: portal.h:190
#define elog(elevel,...)
Definition: elog.h:214
static void DoPortalRewind(Portal portal)
Definition: pquery.c:1655
uint64 portalPos
Definition: portal.h:192
#define FETCH_ALL
Definition: parsenodes.h:2750

◆ FetchPortalTargetList()

List* FetchPortalTargetList ( Portal  portal)

Definition at line 323 of file pquery.c.

References FetchStatementTargetList(), NIL, PORTAL_MULTI_QUERY, PortalGetPrimaryStmt(), and PortalData::strategy.

Referenced by exec_describe_portal_message(), FetchStatementTargetList(), and printtup_startup().

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 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:529
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition: portalmem.c:151
List * FetchStatementTargetList(Node *stmt)
Definition: pquery.c:345
PortalStrategy strategy
Definition: portal.h:145

◆ FetchStatementTargetList()

List* FetchStatementTargetList ( Node stmt)

Definition at line 345 of file pquery.c.

References Assert, CMD_SELECT, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, FetchPortalTargetList(), FetchPreparedStatement(), FetchPreparedStatementTargetList(), GetPortalByName(), PlannedStmt::hasReturning, IsA, FetchStmt::ismove, ExecuteStmt::name, NIL, PlannedStmt::planTree, PortalIsValid, FetchStmt::portalname, Query::returningList, Query::targetList, Plan::targetlist, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by CachedPlanGetTargetList(), and FetchPortalTargetList().

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 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
Node * utilityStmt
Definition: parsenodes.h:120
struct Plan * planTree
Definition: plannodes.h:64
List * targetList
Definition: parsenodes.h:140
bool hasReturning
Definition: plannodes.h:50
Node * utilityStmt
Definition: plannodes.h:92
List * returningList
Definition: parsenodes.h:146
char * portalname
Definition: parsenodes.h:2757
#define PortalIsValid(p)
Definition: portal.h:203
bool ismove
Definition: parsenodes.h:2758
CmdType commandType
Definition: plannodes.h:46
List * FetchPreparedStatementTargetList(PreparedStatement *stmt)
Definition: prepare.c:524
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:738
List * targetlist
Definition: plannodes.h:142
char * name
Definition: parsenodes.h:3438
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:323
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:469

◆ FillPortalStore()

static void FillPortalStore ( Portal  portal,
bool  isTopLevel 
)
static

Definition at line 988 of file pquery.c.

References QueryCompletion::commandTag, CopyQueryCompletion(), CreateDestReceiver(), DestTuplestore, elog, ERROR, PortalData::holdContext, PortalData::holdStore, InitializeQueryCompletion(), linitial_node, None_Receiver, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_UTIL_SELECT, PortalCreateHoldStore(), PortalRunMulti(), PortalRunUtility(), PortalData::qc, _DestReceiver::rDestroy, SetTuplestoreDestReceiverParams(), PortalData::stmts, and PortalData::strategy.

Referenced by PortalRun(), and PortalRunFetch().

989 {
990  DestReceiver *treceiver;
991  QueryCompletion qc;
992 
994  PortalCreateHoldStore(portal);
995  treceiver = CreateDestReceiver(DestTuplestore);
997  portal->holdStore,
998  portal->holdContext,
999  false);
1000 
1001  switch (portal->strategy)
1002  {
1003  case PORTAL_ONE_RETURNING:
1004  case PORTAL_ONE_MOD_WITH:
1005 
1006  /*
1007  * Run the portal to completion just as for the default
1008  * PORTAL_MULTI_QUERY case, but send the primary query's output to
1009  * the tuplestore. Auxiliary query outputs are discarded. Set the
1010  * portal's holdSnapshot to the snapshot used (or a copy of it).
1011  */
1012  PortalRunMulti(portal, isTopLevel, true,
1013  treceiver, None_Receiver, &qc);
1014  break;
1015 
1016  case PORTAL_UTIL_SELECT:
1017  PortalRunUtility(portal, linitial_node(PlannedStmt, portal->stmts),
1018  isTopLevel, true, treceiver, &qc);
1019  break;
1020 
1021  default:
1022  elog(ERROR, "unsupported portal strategy: %d",
1023  (int) portal->strategy);
1024  break;
1025  }
1026 
1027  /* Override portal completion data with actual command results */
1028  if (qc.commandTag != CMDTAG_UNKNOWN)
1029  CopyQueryCompletion(&portal->qc, &qc);
1030 
1031  treceiver->rDestroy(treceiver);
1032 }
void SetTuplestoreDestReceiverParams(DestReceiver *self, Tuplestorestate *tStore, MemoryContext tContext, bool detoast)
MemoryContext holdContext
Definition: portal.h:169
List * stmts
Definition: portal.h:138
#define linitial_node(type, l)
Definition: pg_list.h:198
DestReceiver * None_Receiver
Definition: dest.c:96
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:1113
#define ERROR
Definition: elog.h:43
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:38
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
PortalStrategy strategy
Definition: portal.h:145
CommandTag commandTag
Definition: cmdtag.h:30
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
QueryCompletion qc
Definition: portal.h:137
void PortalCreateHoldStore(Portal portal)
Definition: portalmem.c:330
Tuplestorestate * holdStore
Definition: portal.h:168
#define elog(elevel,...)
Definition: elog.h:214
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:1184

◆ FreeQueryDesc()

void FreeQueryDesc ( QueryDesc qdesc)

Definition at line 105 of file pquery.c.

References Assert, QueryDesc::crosscheck_snapshot, QueryDesc::estate, pfree(), QueryDesc::snapshot, and UnregisterSnapshot().

Referenced by _SPI_execute_plan(), EndCopyTo(), ExecCreateTableAs(), execute_sql_string(), ExplainOnePlan(), ParallelQueryMain(), PersistHoldablePortal(), PortalCleanup(), postquel_end(), ProcessQuery(), and refresh_matview_datafill().

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 }
EState * estate
Definition: execdesc.h:48
Snapshot snapshot
Definition: execdesc.h:39
void pfree(void *pointer)
Definition: mcxt.c:1056
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
#define Assert(condition)
Definition: c.h:738

◆ PortalRun()

bool PortalRun ( Portal  portal,
long  count,
bool  isTopLevel,
bool  run_once,
DestReceiver dest,
DestReceiver altdest,
QueryCompletion qc 
)

Definition at line 672 of file pquery.c.

References ActivePortal, Assert, AssertArg, PortalData::atEnd, QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, CurrentResourceOwner, DEBUG3, elog, ERROR, FillPortalStore(), PortalData::holdStore, InitializeQueryCompletion(), log_executor_stats, MarkPortalActive(), MarkPortalDone(), MarkPortalFailed(), MemoryContextSwitchTo(), QueryCompletion::nprocessed, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PORTAL_MULTI_QUERY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_READY, PORTAL_UTIL_SELECT, PortalContext, PortalData::portalContext, PortalIsValid, PortalRunMulti(), PortalRunSelect(), PortalData::qc, ResetUsage(), PortalData::resowner, PortalData::run_once, ShowUsage(), PortalData::status, PortalData::strategy, TopTransactionContext, and TopTransactionResourceOwner.

Referenced by exec_execute_message(), exec_simple_query(), and ExecuteQuery().

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 }
bool atEnd
Definition: portal.h:191
MemoryContext TopTransactionContext
Definition: mcxt.c:49
#define DEBUG3
Definition: elog.h:23
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:144
void ShowUsage(const char *title)
Definition: postgres.c:4618
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void MarkPortalActive(Portal portal)
Definition: portalmem.c:394
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext portalContext
Definition: portal.h:120
static uint64 PortalRunSelect(Portal portal, bool forward, long count, DestReceiver *dest)
Definition: pquery.c:855
bool run_once
Definition: portal.h:147
MemoryContext PortalContext
Definition: mcxt.c:53
void ResetUsage(void)
Definition: postgres.c:4611
#define ERROR
Definition: elog.h:43
uint64 nprocessed
Definition: cmdtag.h:31
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:38
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:988
void MarkPortalDone(Portal portal)
Definition: portalmem.c:413
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
PortalStrategy strategy
Definition: portal.h:145
#define AssertArg(condition)
Definition: c.h:740
#define PortalIsValid(p)
Definition: portal.h:203
CommandTag commandTag
Definition: cmdtag.h:30
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
#define PG_CATCH()
Definition: elog.h:305
QueryCompletion qc
Definition: portal.h:137
#define Assert(condition)
Definition: c.h:738
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:336
ResourceOwner resowner
Definition: portal.h:121
Tuplestorestate * holdStore
Definition: portal.h:168
#define elog(elevel,...)
Definition: elog.h:214
bool log_executor_stats
Definition: guc.c:526
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:1184
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320

◆ PortalRunFetch()

uint64 PortalRunFetch ( Portal  portal,
FetchDirection  fdirection,
long  count,
DestReceiver dest 
)

Definition at line 1368 of file pquery.c.

References ActivePortal, Assert, AssertArg, CurrentResourceOwner, DoPortalRunFetch(), elog, ERROR, FillPortalStore(), PortalData::holdStore, MarkPortalActive(), MarkPortalFailed(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_READY, PORTAL_UTIL_SELECT, PortalContext, PortalData::portalContext, PortalIsValid, PortalData::resowner, PortalData::run_once, PortalData::status, and PortalData::strategy.

Referenced by _SPI_cursor_operation(), and PerformPortalFetch().

1372 {
1373  uint64 result;
1374  Portal saveActivePortal;
1375  ResourceOwner saveResourceOwner;
1376  MemoryContext savePortalContext;
1377  MemoryContext oldContext;
1378 
1379  AssertArg(PortalIsValid(portal));
1380 
1381  /*
1382  * Check for improper portal use, and mark portal active.
1383  */
1384  MarkPortalActive(portal);
1385 
1386  /* If supporting FETCH, portal can't be run-once. */
1387  Assert(!portal->run_once);
1388 
1389  /*
1390  * Set up global portal context pointers.
1391  */
1392  saveActivePortal = ActivePortal;
1393  saveResourceOwner = CurrentResourceOwner;
1394  savePortalContext = PortalContext;
1395  PG_TRY();
1396  {
1397  ActivePortal = portal;
1398  if (portal->resowner)
1399  CurrentResourceOwner = portal->resowner;
1400  PortalContext = portal->portalContext;
1401 
1402  oldContext = MemoryContextSwitchTo(PortalContext);
1403 
1404  switch (portal->strategy)
1405  {
1406  case PORTAL_ONE_SELECT:
1407  result = DoPortalRunFetch(portal, fdirection, count, dest);
1408  break;
1409 
1410  case PORTAL_ONE_RETURNING:
1411  case PORTAL_ONE_MOD_WITH:
1412  case PORTAL_UTIL_SELECT:
1413 
1414  /*
1415  * If we have not yet run the command, do so, storing its
1416  * results in the portal's tuplestore.
1417  */
1418  if (!portal->holdStore)
1419  FillPortalStore(portal, false /* isTopLevel */ );
1420 
1421  /*
1422  * Now fetch desired portion of results.
1423  */
1424  result = DoPortalRunFetch(portal, fdirection, count, dest);
1425  break;
1426 
1427  default:
1428  elog(ERROR, "unsupported portal strategy");
1429  result = 0; /* keep compiler quiet */
1430  break;
1431  }
1432  }
1433  PG_CATCH();
1434  {
1435  /* Uncaught error while executing portal: mark it dead */
1436  MarkPortalFailed(portal);
1437 
1438  /* Restore global vars and propagate error */
1439  ActivePortal = saveActivePortal;
1440  CurrentResourceOwner = saveResourceOwner;
1441  PortalContext = savePortalContext;
1442 
1443  PG_RE_THROW();
1444  }
1445  PG_END_TRY();
1446 
1447  MemoryContextSwitchTo(oldContext);
1448 
1449  /* Mark portal not active */
1450  portal->status = PORTAL_READY;
1451 
1452  ActivePortal = saveActivePortal;
1453  CurrentResourceOwner = saveResourceOwner;
1454  PortalContext = savePortalContext;
1455 
1456  return result;
1457 }
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void MarkPortalActive(Portal portal)
Definition: portalmem.c:394
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext portalContext
Definition: portal.h:120
static uint64 DoPortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1470
bool run_once
Definition: portal.h:147
MemoryContext PortalContext
Definition: mcxt.c:53
#define ERROR
Definition: elog.h:43
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:988
PortalStrategy strategy
Definition: portal.h:145
#define AssertArg(condition)
Definition: c.h:740
#define PortalIsValid(p)
Definition: portal.h:203
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:738
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:336
ResourceOwner resowner
Definition: portal.h:121
Tuplestorestate * holdStore
Definition: portal.h:168
#define elog(elevel,...)
Definition: elog.h:214
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320

◆ PortalRunMulti()

static void PortalRunMulti ( Portal  portal,
bool  isTopLevel,
bool  setHoldSnapshot,
DestReceiver dest,
DestReceiver altdest,
QueryCompletion qc 
)
static

Definition at line 1184 of file pquery.c.

References Assert, PlannedStmt::canSetTag, CHECK_FOR_INTERRUPTS, CommandCounterIncrement(), QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, DestRemoteExecute, GetTransactionSnapshot(), PortalData::holdSnapshot, IsA, lfirst_node, lnext(), log_executor_stats, MemoryContextDeleteChildren(), _DestReceiver::mydest, None_Receiver, PopActiveSnapshot(), PortalData::portalContext, PortalData::portalParams, PortalRunUtility(), ProcessQuery(), PushCopiedSnapshot(), PortalData::qc, PortalData::queryEnv, RegisterSnapshot(), ResetUsage(), ShowUsage(), PortalData::sourceText, PortalData::stmts, UpdateActiveSnapshotCommandId(), and PlannedStmt::utilityStmt.

Referenced by FillPortalStore(), and PortalRun().

1188 {
1189  bool active_snapshot_set = false;
1190  ListCell *stmtlist_item;
1191 
1192  /*
1193  * If the destination is DestRemoteExecute, change to DestNone. The
1194  * reason is that the client won't be expecting any tuples, and indeed has
1195  * no way to know what they are, since there is no provision for Describe
1196  * to send a RowDescription message when this portal execution strategy is
1197  * in effect. This presently will only affect SELECT commands added to
1198  * non-SELECT queries by rewrite rules: such commands will be executed,
1199  * but the results will be discarded unless you use "simple Query"
1200  * protocol.
1201  */
1202  if (dest->mydest == DestRemoteExecute)
1203  dest = None_Receiver;
1204  if (altdest->mydest == DestRemoteExecute)
1205  altdest = None_Receiver;
1206 
1207  /*
1208  * Loop to handle the individual queries generated from a single parsetree
1209  * by analysis and rewrite.
1210  */
1211  foreach(stmtlist_item, portal->stmts)
1212  {
1213  PlannedStmt *pstmt = lfirst_node(PlannedStmt, stmtlist_item);
1214 
1215  /*
1216  * If we got a cancel signal in prior command, quit
1217  */
1219 
1220  if (pstmt->utilityStmt == NULL)
1221  {
1222  /*
1223  * process a plannable query.
1224  */
1225  TRACE_POSTGRESQL_QUERY_EXECUTE_START();
1226 
1227  if (log_executor_stats)
1228  ResetUsage();
1229 
1230  /*
1231  * Must always have a snapshot for plannable queries. First time
1232  * through, take a new snapshot; for subsequent queries in the
1233  * same portal, just update the snapshot's copy of the command
1234  * counter.
1235  */
1236  if (!active_snapshot_set)
1237  {
1238  Snapshot snapshot = GetTransactionSnapshot();
1239 
1240  /* If told to, register the snapshot and save in portal */
1241  if (setHoldSnapshot)
1242  {
1243  snapshot = RegisterSnapshot(snapshot);
1244  portal->holdSnapshot = snapshot;
1245  }
1246 
1247  /*
1248  * We can't have the holdSnapshot also be the active one,
1249  * because UpdateActiveSnapshotCommandId would complain. So
1250  * force an extra snapshot copy. Plain PushActiveSnapshot
1251  * would have copied the transaction snapshot anyway, so this
1252  * only adds a copy step when setHoldSnapshot is true. (It's
1253  * okay for the command ID of the active snapshot to diverge
1254  * from what holdSnapshot has.)
1255  */
1256  PushCopiedSnapshot(snapshot);
1257  active_snapshot_set = true;
1258  }
1259  else
1261 
1262  if (pstmt->canSetTag)
1263  {
1264  /* statement can set tag string */
1265  ProcessQuery(pstmt,
1266  portal->sourceText,
1267  portal->portalParams,
1268  portal->queryEnv,
1269  dest, qc);
1270  }
1271  else
1272  {
1273  /* stmt added by rewrite cannot set tag */
1274  ProcessQuery(pstmt,
1275  portal->sourceText,
1276  portal->portalParams,
1277  portal->queryEnv,
1278  altdest, NULL);
1279  }
1280 
1281  if (log_executor_stats)
1282  ShowUsage("EXECUTOR STATISTICS");
1283 
1284  TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
1285  }
1286  else
1287  {
1288  /*
1289  * process utility functions (create, destroy, etc..)
1290  *
1291  * We must not set a snapshot here for utility commands (if one is
1292  * needed, PortalRunUtility will do it). If a utility command is
1293  * alone in a portal then everything's fine. The only case where
1294  * a utility command can be part of a longer list is that rules
1295  * are allowed to include NotifyStmt. NotifyStmt doesn't care
1296  * whether it has a snapshot or not, so we just leave the current
1297  * snapshot alone if we have one.
1298  */
1299  if (pstmt->canSetTag)
1300  {
1301  Assert(!active_snapshot_set);
1302  /* statement can set tag string */
1303  PortalRunUtility(portal, pstmt, isTopLevel, false,
1304  dest, qc);
1305  }
1306  else
1307  {
1308  Assert(IsA(pstmt->utilityStmt, NotifyStmt));
1309  /* stmt added by rewrite cannot set tag */
1310  PortalRunUtility(portal, pstmt, isTopLevel, false,
1311  altdest, NULL);
1312  }
1313  }
1314 
1315  /*
1316  * Increment command counter between queries, but not after the last
1317  * one.
1318  */
1319  if (lnext(portal->stmts, stmtlist_item) != NULL)
1321 
1322  /*
1323  * Clear subsidiary contexts to recover temporary memory.
1324  */
1326 
1328  }
1329 
1330  /* Pop the snapshot if we pushed one. */
1331  if (active_snapshot_set)
1333 
1334  /*
1335  * If a query completion data was supplied, use it. Otherwise use the
1336  * portal's query completion data.
1337  *
1338  * Exception: Clients expect INSERT/UPDATE/DELETE tags to have counts, so
1339  * fake them with zeros. This can happen with DO INSTEAD rules if there
1340  * is no replacement query of the same type as the original. We print "0
1341  * 0" here because technically there is no query of the matching tag type,
1342  * and printing a non-zero count for a different query type seems wrong,
1343  * e.g. an INSERT that does an UPDATE instead should not print "0 1" if
1344  * one row was updated. See QueryRewrite(), step 3, for details.
1345  */
1346  if (qc && qc->commandTag == CMDTAG_UNKNOWN)
1347  {
1348  if (portal->qc.commandTag != CMDTAG_UNKNOWN)
1349  CopyQueryCompletion(qc, &portal->qc);
1350  /* If the caller supplied a qc, we should have set it by now. */
1351  Assert(qc->commandTag != CMDTAG_UNKNOWN);
1352  }
1353 }
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:783
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
void ShowUsage(const char *title)
Definition: postgres.c:4618
CommandDest mydest
Definition: dest.h:129
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
List * stmts
Definition: portal.h:138
DestReceiver * None_Receiver
Definition: dest.c:96
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
MemoryContext portalContext
Definition: portal.h:120
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:1113
void ResetUsage(void)
Definition: postgres.c:4611
ParamListInfo portalParams
Definition: portal.h:141
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:771
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Node * utilityStmt
Definition: plannodes.h:92
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:256
bool canSetTag
Definition: plannodes.h:54
void CommandCounterIncrement(void)
Definition: xact.c:1006
const char * sourceText
Definition: portal.h:135
CommandTag commandTag
Definition: cmdtag.h:30
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
QueryCompletion qc
Definition: portal.h:137
#define Assert(condition)
Definition: c.h:738
Snapshot holdSnapshot
Definition: portal.h:179
QueryEnvironment * queryEnv
Definition: portal.h:142
bool log_executor_stats
Definition: guc.c:526
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

◆ PortalRunSelect()

static uint64 PortalRunSelect ( Portal  portal,
bool  forward,
long  count,
DestReceiver dest 
)
static

Definition at line 855 of file pquery.c.

References Assert, PortalData::atEnd, PortalData::atStart, BackwardScanDirection, CURSOR_OPT_NO_SCROLL, PortalData::cursorOptions, QueryDesc::dest, generate_unaccent_rules::dest, ereport, errcode(), errhint(), errmsg(), ERROR, EState::es_processed, QueryDesc::estate, ExecutorRun(), FETCH_ALL, ForwardScanDirection, PortalData::holdStore, NoMovementScanDirection, PopActiveSnapshot(), PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, PortalData::run_once, RunFromStore(), ScanDirectionIsNoMovement, and QueryDesc::snapshot.

Referenced by DoPortalRunFetch(), and PortalRun().

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 }
static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count, DestReceiver *dest)
Definition: pquery.c:1047
int errhint(const char *fmt,...)
Definition: elog.c:1071
bool atEnd
Definition: portal.h:191
EState * estate
Definition: execdesc.h:48
int errcode(int sqlerrcode)
Definition: elog.c:610
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2708
Snapshot snapshot
Definition: execdesc.h:39
bool run_once
Definition: portal.h:147
#define ERROR
Definition: elog.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
ScanDirection
Definition: sdir.h:22
QueryDesc * queryDesc
Definition: portal.h:156
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
uint64 es_processed
Definition: execnodes.h:559
DestReceiver * dest
Definition: execdesc.h:41
bool atStart
Definition: portal.h:190
Tuplestorestate * holdStore
Definition: portal.h:168
int errmsg(const char *fmt,...)
Definition: elog.c:824
int cursorOptions
Definition: portal.h:146
uint64 portalPos
Definition: portal.h:192
#define FETCH_ALL
Definition: parsenodes.h:2750

◆ PortalRunUtility()

static void PortalRunUtility ( Portal  portal,
PlannedStmt pstmt,
bool  isTopLevel,
bool  setHoldSnapshot,
DestReceiver dest,
QueryCompletion qc 
)
static

Definition at line 1113 of file pquery.c.

References ActiveSnapshotSet(), GetActiveSnapshot(), GetTransactionSnapshot(), PortalData::holdSnapshot, IsA, MemoryContextSwitchTo(), PopActiveSnapshot(), PortalData::portalContext, PortalData::portalParams, PROCESS_UTILITY_QUERY, PROCESS_UTILITY_TOPLEVEL, ProcessUtility(), PushActiveSnapshot(), PortalData::queryEnv, RegisterSnapshot(), PortalData::sourceText, and PlannedStmt::utilityStmt.

Referenced by FillPortalStore(), and PortalRunMulti().

1116 {
1117  Node *utilityStmt = pstmt->utilityStmt;
1118  Snapshot snapshot;
1119 
1120  /*
1121  * Set snapshot if utility stmt needs one. Most reliable way to do this
1122  * seems to be to enumerate those that do not need one; this is a short
1123  * list. Transaction control, LOCK, and SET must *not* set a snapshot
1124  * since they need to be executable at the start of a transaction-snapshot
1125  * mode transaction without freezing a snapshot. By extension we allow
1126  * SHOW not to set a snapshot. The other stmts listed are just efficiency
1127  * hacks. Beware of listing anything that can modify the database --- if,
1128  * say, it has to update an index with expressions that invoke
1129  * user-defined functions, then it had better have a snapshot.
1130  */
1131  if (!(IsA(utilityStmt, TransactionStmt) ||
1132  IsA(utilityStmt, LockStmt) ||
1133  IsA(utilityStmt, VariableSetStmt) ||
1134  IsA(utilityStmt, VariableShowStmt) ||
1135  IsA(utilityStmt, ConstraintsSetStmt) ||
1136  /* efficiency hacks from here down */
1137  IsA(utilityStmt, FetchStmt) ||
1138  IsA(utilityStmt, ListenStmt) ||
1139  IsA(utilityStmt, NotifyStmt) ||
1140  IsA(utilityStmt, UnlistenStmt) ||
1141  IsA(utilityStmt, CheckPointStmt)))
1142  {
1143  snapshot = GetTransactionSnapshot();
1144  /* If told to, register the snapshot we're using and save in portal */
1145  if (setHoldSnapshot)
1146  {
1147  snapshot = RegisterSnapshot(snapshot);
1148  portal->holdSnapshot = snapshot;
1149  }
1150  PushActiveSnapshot(snapshot);
1151  /* PushActiveSnapshot might have copied the snapshot */
1152  snapshot = GetActiveSnapshot();
1153  }
1154  else
1155  snapshot = NULL;
1156 
1157  ProcessUtility(pstmt,
1158  portal->sourceText,
1160  portal->portalParams,
1161  portal->queryEnv,
1162  dest,
1163  qc);
1164 
1165  /* Some utility statements may change context on us */
1167 
1168  /*
1169  * Some utility commands may pop the ActiveSnapshot stack from under us,
1170  * so be careful to only pop the stack if our snapshot is still at the
1171  * top.
1172  */
1173  if (snapshot != NULL && ActiveSnapshotSet() &&
1174  snapshot == GetActiveSnapshot())
1176 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
Definition: nodes.h:529
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
MemoryContext portalContext
Definition: portal.h:120
ParamListInfo portalParams
Definition: portal.h:141
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
Node * utilityStmt
Definition: plannodes.h:92
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:853
const char * sourceText
Definition: portal.h:135
Snapshot holdSnapshot
Definition: portal.h:179
QueryEnvironment * queryEnv
Definition: portal.h:142
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:501

◆ PortalSetResultFormat()

void PortalSetResultFormat ( Portal  portal,
int  nFormats,
int16 formats 
)

Definition at line 611 of file pquery.c.

References ereport, errcode(), errmsg(), ERROR, PortalData::formats, i, MemoryContextAlloc(), TupleDescData::natts, PortalData::portalContext, and PortalData::tupDesc.

Referenced by exec_bind_message(), and exec_simple_query().

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 }
signed short int16
Definition: c.h:354
int errcode(int sqlerrcode)
Definition: elog.c:610
MemoryContext portalContext
Definition: portal.h:120
#define ERROR
Definition: elog.h:43
int16 * formats
Definition: portal.h:161
TupleDesc tupDesc
Definition: portal.h:159
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
int i

◆ PortalStart()

void PortalStart ( Portal  portal,
ParamListInfo  params,
int  eflags,
Snapshot  snapshot 
)

Definition at line 430 of file pquery.c.

References ActivePortal, Assert, AssertArg, AssertState, PortalData::atEnd, PortalData::atStart, ChoosePortalStrategy(), CMD_UTILITY, PlannedStmt::commandType, CreateQueryDesc(), CurrentResourceOwner, CURSOR_OPT_SCROLL, PortalData::cursorOptions, EXEC_FLAG_BACKWARD, EXEC_FLAG_REWIND, ExecCleanTypeFromTL(), ExecutorStart(), GetActiveSnapshot(), GetTransactionSnapshot(), InvalidSnapshot, linitial_node, MarkPortalFailed(), MemoryContextSwitchTo(), None_Receiver, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PlannedStmt::planTree, PopActiveSnapshot(), PORTAL_DEFINED, PORTAL_MULTI_QUERY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_READY, PORTAL_UTIL_SELECT, PortalContext, PortalData::portalContext, PortalGetPrimaryStmt(), PortalIsValid, PortalData::portalParams, PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, PortalData::queryEnv, PortalData::resowner, PortalData::sourceText, PortalData::status, PortalData::stmts, PortalData::strategy, Plan::targetlist, QueryDesc::tupDesc, PortalData::tupDesc, PlannedStmt::utilityStmt, and UtilityTupleDescriptor().

Referenced by exec_bind_message(), exec_simple_query(), ExecuteQuery(), PerformCursorOpen(), and SPI_cursor_open_internal().

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 }
#define AssertState(condition)
Definition: c.h:741
bool atEnd
Definition: portal.h:191
TupleDesc ExecCleanTypeFromTL(List *targetList)
Definition: execTuples.c:1920
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
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
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
List * stmts
Definition: portal.h:138
#define linitial_node(type, l)
Definition: pg_list.h:198
DestReceiver * None_Receiver
Definition: dest.c:96
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
MemoryContext portalContext
Definition: portal.h:120
struct Plan * planTree
Definition: plannodes.h:64
MemoryContext PortalContext
Definition: mcxt.c:53
ParamListInfo portalParams
Definition: portal.h:141
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition: portalmem.c:151
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
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
Node * utilityStmt
Definition: plannodes.h:92
PortalStrategy strategy
Definition: portal.h:145
#define EXEC_FLAG_REWIND
Definition: executor.h:57
#define AssertArg(condition)
Definition: c.h:740
QueryDesc * queryDesc
Definition: portal.h:156
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
#define PortalIsValid(p)
Definition: portal.h:203
CmdType commandType
Definition: plannodes.h:46
const char * sourceText
Definition: portal.h:135
TupleDesc tupDesc
Definition: portal.h:159
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:738
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:336
QueryEnvironment * queryEnv
Definition: portal.h:142
PortalStrategy ChoosePortalStrategy(List *stmts)
Definition: pquery.c:206
List * targetlist
Definition: plannodes.h:142
ResourceOwner resowner
Definition: portal.h:121
bool atStart
Definition: portal.h:190
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2707
int cursorOptions
Definition: portal.h:146
#define PG_TRY()
Definition: elog.h:295
TupleDesc UtilityTupleDescriptor(Node *parsetree)
Definition: utility.c:1969
#define PG_END_TRY()
Definition: elog.h:320
uint64 portalPos
Definition: portal.h:192

◆ ProcessQuery()

static void ProcessQuery ( PlannedStmt plan,
const char *  sourceText,
ParamListInfo  params,
QueryEnvironment queryEnv,
DestReceiver dest,
QueryCompletion qc 
)
static

Definition at line 136 of file pquery.c.

References CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, CreateQueryDesc(), EState::es_processed, QueryDesc::estate, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ForwardScanDirection, FreeQueryDesc(), GetActiveSnapshot(), InvalidSnapshot, QueryDesc::operation, and SetQueryCompletion().

Referenced by PortalRunMulti().

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 }
EState * estate
Definition: execdesc.h:48
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
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
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:123
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
uint64 es_processed
Definition: execnodes.h:559

◆ RunFromStore()

static uint64 RunFromStore ( Portal  portal,
ScanDirection  direction,
uint64  count,
DestReceiver dest 
)
static

Definition at line 1047 of file pquery.c.

References CMD_SELECT, ExecClearTuple(), ExecDropSingleTupleTableSlot(), PortalData::holdContext, PortalData::holdStore, MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), _DestReceiver::receiveSlot, _DestReceiver::rShutdown, _DestReceiver::rStartup, ScanDirectionIsForward, ScanDirectionIsNoMovement, TTSOpsMinimalTuple, PortalData::tupDesc, and tuplestore_gettupleslot().

Referenced by PortalRunSelect().

1049 {
1050  uint64 current_tuple_count = 0;
1051  TupleTableSlot *slot;
1052 
1054 
1055  dest->rStartup(dest, CMD_SELECT, portal->tupDesc);
1056 
1057  if (ScanDirectionIsNoMovement(direction))
1058  {
1059  /* do nothing except start/stop the destination */
1060  }
1061  else
1062  {
1063  bool forward = ScanDirectionIsForward(direction);
1064 
1065  for (;;)
1066  {
1067  MemoryContext oldcontext;
1068  bool ok;
1069 
1070  oldcontext = MemoryContextSwitchTo(portal->holdContext);
1071 
1072  ok = tuplestore_gettupleslot(portal->holdStore, forward, false,
1073  slot);
1074 
1075  MemoryContextSwitchTo(oldcontext);
1076 
1077  if (!ok)
1078  break;
1079 
1080  /*
1081  * If we are not able to send the tuple, we assume the destination
1082  * has closed and no more tuples can be sent. If that's the case,
1083  * end the loop.
1084  */
1085  if (!dest->receiveSlot(slot, dest))
1086  break;
1087 
1088  ExecClearTuple(slot);
1089 
1090  /*
1091  * check our tuple count.. if we've processed the proper number
1092  * then quit, else loop again and process more tuples. Zero count
1093  * means no limit.
1094  */
1095  current_tuple_count++;
1096  if (count && count == current_tuple_count)
1097  break;
1098  }
1099  }
1100 
1101  dest->rShutdown(dest);
1102 
1104 
1105  return current_tuple_count;
1106 }
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:119
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define ScanDirectionIsForward(direction)
Definition: sdir.h:55
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext holdContext
Definition: portal.h:169
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:122
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
TupleDesc tupDesc
Definition: portal.h:159
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:125
Tuplestorestate * holdStore
Definition: portal.h:168
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85

Variable Documentation

◆ ActivePortal

Portal ActivePortal = NULL