PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
 
uint64 PortalRunFetch (Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
 
bool PlannedStmtRequiresSnapshot (PlannedStmt *pstmt)
 
void EnsurePortalSnapshotExists (void)
 

Variables

Portal ActivePortal = NULL
 

Function Documentation

◆ ChoosePortalStrategy()

PortalStrategy ChoosePortalStrategy ( List stmts)

Definition at line 209 of file pquery.c.

210{
211 int nSetTag;
212 ListCell *lc;
213
214 /*
215 * PORTAL_ONE_SELECT and PORTAL_UTIL_SELECT need only consider the
216 * single-statement case, since there are no rewrite rules that can add
217 * auxiliary queries to a SELECT or a utility command. PORTAL_ONE_MOD_WITH
218 * likewise allows only one top-level statement.
219 */
220 if (list_length(stmts) == 1)
221 {
222 Node *stmt = (Node *) linitial(stmts);
223
224 if (IsA(stmt, Query))
225 {
226 Query *query = (Query *) stmt;
227
228 if (query->canSetTag)
229 {
230 if (query->commandType == CMD_SELECT)
231 {
232 if (query->hasModifyingCTE)
233 return PORTAL_ONE_MOD_WITH;
234 else
235 return PORTAL_ONE_SELECT;
236 }
237 if (query->commandType == CMD_UTILITY)
238 {
240 return PORTAL_UTIL_SELECT;
241 /* it can't be ONE_RETURNING, so give up */
242 return PORTAL_MULTI_QUERY;
243 }
244 }
245 }
246 else if (IsA(stmt, PlannedStmt))
247 {
248 PlannedStmt *pstmt = (PlannedStmt *) stmt;
249
250 if (pstmt->canSetTag)
251 {
252 if (pstmt->commandType == CMD_SELECT)
253 {
254 if (pstmt->hasModifyingCTE)
255 return PORTAL_ONE_MOD_WITH;
256 else
257 return PORTAL_ONE_SELECT;
258 }
259 if (pstmt->commandType == CMD_UTILITY)
260 {
262 return PORTAL_UTIL_SELECT;
263 /* it can't be ONE_RETURNING, so give up */
264 return PORTAL_MULTI_QUERY;
265 }
266 }
267 }
268 else
269 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
270 }
271
272 /*
273 * PORTAL_ONE_RETURNING has to allow auxiliary queries added by rewrite.
274 * Choose PORTAL_ONE_RETURNING if there is exactly one canSetTag query and
275 * it has a RETURNING list.
276 */
277 nSetTag = 0;
278 foreach(lc, stmts)
279 {
280 Node *stmt = (Node *) lfirst(lc);
281
282 if (IsA(stmt, Query))
283 {
284 Query *query = (Query *) stmt;
285
286 if (query->canSetTag)
287 {
288 if (++nSetTag > 1)
289 return PORTAL_MULTI_QUERY; /* no need to look further */
290 if (query->commandType == CMD_UTILITY ||
291 query->returningList == NIL)
292 return PORTAL_MULTI_QUERY; /* no need to look further */
293 }
294 }
295 else if (IsA(stmt, PlannedStmt))
296 {
297 PlannedStmt *pstmt = (PlannedStmt *) stmt;
298
299 if (pstmt->canSetTag)
300 {
301 if (++nSetTag > 1)
302 return PORTAL_MULTI_QUERY; /* no need to look further */
303 if (pstmt->commandType == CMD_UTILITY ||
304 !pstmt->hasReturning)
305 return PORTAL_MULTI_QUERY; /* no need to look further */
306 }
307 }
308 else
309 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
310 }
311 if (nSetTag == 1)
313
314 /* Else, it's the general case... */
315 return PORTAL_MULTI_QUERY;
316}
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define stmt
Definition: indent_codes.h:59
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_SELECT
Definition: nodes.h:265
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define linitial(l)
Definition: pg_list.h:178
@ PORTAL_ONE_RETURNING
Definition: portal.h:92
@ PORTAL_MULTI_QUERY
Definition: portal.h:95
@ PORTAL_ONE_SELECT
Definition: portal.h:91
@ PORTAL_ONE_MOD_WITH
Definition: portal.h:93
@ PORTAL_UTIL_SELECT
Definition: portal.h:94
Definition: nodes.h:129
bool hasModifyingCTE
Definition: plannodes.h:58
bool canSetTag
Definition: plannodes.h:60
bool hasReturning
Definition: plannodes.h:56
CmdType commandType
Definition: plannodes.h:52
Node * utilityStmt
Definition: plannodes.h:95
List * returningList
Definition: parsenodes.h:200
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
bool UtilityReturnsTuples(Node *parsetree)
Definition: utility.c:2028

References PlannedStmt::canSetTag, CMD_SELECT, CMD_UTILITY, Query::commandType, PlannedStmt::commandType, elog, ERROR, PlannedStmt::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, stmt, UtilityReturnsTuples(), Query::utilityStmt, and PlannedStmt::utilityStmt.

Referenced by PlanCacheComputeResultDesc(), and PortalStart().

◆ 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.

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

References QueryDesc::already_executed, PlannedStmt::commandType, QueryDesc::crosscheck_snapshot, generate_unaccent_rules::dest, QueryDesc::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(), BeginCopyTo(), ExecCreateTableAs(), ExecParallelGetQueryDesc(), execute_sql_string(), ExplainOnePlan(), PortalStart(), postquel_start(), ProcessQuery(), and refresh_matview_datafill().

◆ DoPortalRewind()

static void DoPortalRewind ( Portal  portal)
static

Definition at line 1677 of file pquery.c.

1678{
1679 QueryDesc *queryDesc;
1680
1681 /*
1682 * No work is needed if we've not advanced nor attempted to advance the
1683 * cursor (and we don't want to throw a NO SCROLL error in this case).
1684 */
1685 if (portal->atStart && !portal->atEnd)
1686 return;
1687
1688 /* Otherwise, cursor must allow scrolling */
1689 if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
1690 ereport(ERROR,
1691 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1692 errmsg("cursor can only scan forward"),
1693 errhint("Declare it with SCROLL option to enable backward scan.")));
1694
1695 /* Rewind holdStore, if we have one */
1696 if (portal->holdStore)
1697 {
1698 MemoryContext oldcontext;
1699
1700 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1702 MemoryContextSwitchTo(oldcontext);
1703 }
1704
1705 /* Rewind executor, if active */
1706 queryDesc = portal->queryDesc;
1707 if (queryDesc)
1708 {
1709 PushActiveSnapshot(queryDesc->snapshot);
1710 ExecutorRewind(queryDesc);
1712 }
1713
1714 portal->atStart = true;
1715 portal->atEnd = false;
1716 portal->portalPos = 0;
1717}
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
void ExecutorRewind(QueryDesc *queryDesc)
Definition: execMain.c:533
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:3309
MemoryContextSwitchTo(old_ctx)
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:610
void PopActiveSnapshot(void)
Definition: snapmgr.c:703
uint64 portalPos
Definition: portal.h:200
QueryDesc * queryDesc
Definition: portal.h:156
bool atEnd
Definition: portal.h:199
bool atStart
Definition: portal.h:198
MemoryContext holdContext
Definition: portal.h:177
Tuplestorestate * holdStore
Definition: portal.h:176
int cursorOptions
Definition: portal.h:147
void tuplestore_rescan(Tuplestorestate *state)
Definition: tuplestore.c:1285

References PortalData::atEnd, PortalData::atStart, CURSOR_OPT_NO_SCROLL, PortalData::cursorOptions, ereport, errcode(), errhint(), errmsg(), ERROR, ExecutorRewind(), PortalData::holdContext, PortalData::holdStore, MemoryContextSwitchTo(), PopActiveSnapshot(), PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, QueryDesc::snapshot, and tuplestore_rescan().

Referenced by DoPortalRunFetch().

◆ DoPortalRunFetch()

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

Definition at line 1483 of file pquery.c.

1487{
1488 bool forward;
1489
1490 Assert(portal->strategy == PORTAL_ONE_SELECT ||
1491 portal->strategy == PORTAL_ONE_RETURNING ||
1492 portal->strategy == PORTAL_ONE_MOD_WITH ||
1493 portal->strategy == PORTAL_UTIL_SELECT);
1494
1495 /*
1496 * Note: we disallow backwards fetch (including re-fetch of current row)
1497 * for NO SCROLL cursors, but we interpret that very loosely: you can use
1498 * any of the FetchDirection options, so long as the end result is to move
1499 * forwards by at least one row. Currently it's sufficient to check for
1500 * NO SCROLL in DoPortalRewind() and in the forward == false path in
1501 * PortalRunSelect(); but someday we might prefer to account for that
1502 * restriction explicitly here.
1503 */
1504 switch (fdirection)
1505 {
1506 case FETCH_FORWARD:
1507 if (count < 0)
1508 {
1509 fdirection = FETCH_BACKWARD;
1510 count = -count;
1511 }
1512 /* fall out of switch to share code with FETCH_BACKWARD */
1513 break;
1514 case FETCH_BACKWARD:
1515 if (count < 0)
1516 {
1517 fdirection = FETCH_FORWARD;
1518 count = -count;
1519 }
1520 /* fall out of switch to share code with FETCH_FORWARD */
1521 break;
1522 case FETCH_ABSOLUTE:
1523 if (count > 0)
1524 {
1525 /*
1526 * Definition: Rewind to start, advance count-1 rows, return
1527 * next row (if any).
1528 *
1529 * In practice, if the goal is less than halfway back to the
1530 * start, it's better to scan from where we are.
1531 *
1532 * Also, if current portalPos is outside the range of "long",
1533 * do it the hard way to avoid possible overflow of the count
1534 * argument to PortalRunSelect. We must exclude exactly
1535 * LONG_MAX, as well, lest the count look like FETCH_ALL.
1536 *
1537 * In any case, we arrange to fetch the target row going
1538 * forwards.
1539 */
1540 if ((uint64) (count - 1) <= portal->portalPos / 2 ||
1541 portal->portalPos >= (uint64) LONG_MAX)
1542 {
1543 DoPortalRewind(portal);
1544 if (count > 1)
1545 PortalRunSelect(portal, true, count - 1,
1547 }
1548 else
1549 {
1550 long pos = (long) portal->portalPos;
1551
1552 if (portal->atEnd)
1553 pos++; /* need one extra fetch if off end */
1554 if (count <= pos)
1555 PortalRunSelect(portal, false, pos - count + 1,
1557 else if (count > pos + 1)
1558 PortalRunSelect(portal, true, count - pos - 1,
1560 }
1561 return PortalRunSelect(portal, true, 1L, dest);
1562 }
1563 else if (count < 0)
1564 {
1565 /*
1566 * Definition: Advance to end, back up abs(count)-1 rows,
1567 * return prior row (if any). We could optimize this if we
1568 * knew in advance where the end was, but typically we won't.
1569 * (Is it worth considering case where count > half of size of
1570 * query? We could rewind once we know the size ...)
1571 */
1572 PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1573 if (count < -1)
1574 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1575 return PortalRunSelect(portal, false, 1L, dest);
1576 }
1577 else
1578 {
1579 /* count == 0 */
1580 /* Rewind to start, return zero rows */
1581 DoPortalRewind(portal);
1582 return PortalRunSelect(portal, true, 0L, dest);
1583 }
1584 break;
1585 case FETCH_RELATIVE:
1586 if (count > 0)
1587 {
1588 /*
1589 * Definition: advance count-1 rows, return next row (if any).
1590 */
1591 if (count > 1)
1592 PortalRunSelect(portal, true, count - 1, None_Receiver);
1593 return PortalRunSelect(portal, true, 1L, dest);
1594 }
1595 else if (count < 0)
1596 {
1597 /*
1598 * Definition: back up abs(count)-1 rows, return prior row (if
1599 * any).
1600 */
1601 if (count < -1)
1602 PortalRunSelect(portal, false, -count - 1, None_Receiver);
1603 return PortalRunSelect(portal, false, 1L, dest);
1604 }
1605 else
1606 {
1607 /* count == 0 */
1608 /* Same as FETCH FORWARD 0, so fall out of switch */
1609 fdirection = FETCH_FORWARD;
1610 }
1611 break;
1612 default:
1613 elog(ERROR, "bogus direction");
1614 break;
1615 }
1616
1617 /*
1618 * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1619 * >= 0.
1620 */
1621 forward = (fdirection == FETCH_FORWARD);
1622
1623 /*
1624 * Zero count means to re-fetch the current row, if any (per SQL)
1625 */
1626 if (count == 0)
1627 {
1628 bool on_row;
1629
1630 /* Are we sitting on a row? */
1631 on_row = (!portal->atStart && !portal->atEnd);
1632
1633 if (dest->mydest == DestNone)
1634 {
1635 /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1636 return on_row ? 1 : 0;
1637 }
1638 else
1639 {
1640 /*
1641 * If we are sitting on a row, back up one so we can re-fetch it.
1642 * If we are not sitting on a row, we still have to start up and
1643 * shut down the executor so that the destination is initialized
1644 * and shut down correctly; so keep going. To PortalRunSelect,
1645 * count == 0 means we will retrieve no row.
1646 */
1647 if (on_row)
1648 {
1649 PortalRunSelect(portal, false, 1L, None_Receiver);
1650 /* Set up to fetch one row forward */
1651 count = 1;
1652 forward = true;
1653 }
1654 }
1655 }
1656
1657 /*
1658 * Optimize MOVE BACKWARD ALL into a Rewind.
1659 */
1660 if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1661 {
1662 uint64 result = portal->portalPos;
1663
1664 if (result > 0 && !portal->atEnd)
1665 result--;
1666 DoPortalRewind(portal);
1667 return result;
1668 }
1669
1670 return PortalRunSelect(portal, forward, count, dest);
1671}
#define Assert(condition)
Definition: c.h:812
uint64_t uint64
Definition: c.h:486
DestReceiver * None_Receiver
Definition: dest.c:96
@ DestNone
Definition: dest.h:87
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
#define FETCH_ALL
Definition: parsenodes.h:3352
@ FETCH_RELATIVE
Definition: parsenodes.h:3349
@ FETCH_ABSOLUTE
Definition: parsenodes.h:3348
@ FETCH_FORWARD
Definition: parsenodes.h:3345
@ FETCH_BACKWARD
Definition: parsenodes.h:3346
static uint64 PortalRunSelect(Portal portal, bool forward, long count, DestReceiver *dest)
Definition: pquery.c:863
static void DoPortalRewind(Portal portal)
Definition: pquery.c:1677
PortalStrategy strategy
Definition: portal.h:146

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

Referenced by PortalRunFetch().

◆ EnsurePortalSnapshotExists()

void EnsurePortalSnapshotExists ( void  )

Definition at line 1771 of file pquery.c.

1772{
1773 Portal portal;
1774
1775 /*
1776 * Nothing to do if a snapshot is set. (We take it on faith that the
1777 * outermost active snapshot belongs to some Portal; or if there is no
1778 * Portal, it's somebody else's responsibility to manage things.)
1779 */
1780 if (ActiveSnapshotSet())
1781 return;
1782
1783 /* Otherwise, we'd better have an active Portal */
1784 portal = ActivePortal;
1785 if (unlikely(portal == NULL))
1786 elog(ERROR, "cannot execute SQL without an outer snapshot or portal");
1787 Assert(portal->portalSnapshot == NULL);
1788
1789 /*
1790 * Create a new snapshot, make it active, and remember it in portal.
1791 * Because the portal now references the snapshot, we must tell snapmgr.c
1792 * that the snapshot belongs to the portal's transaction level, else we
1793 * risk portalSnapshot becoming a dangling pointer.
1794 */
1796 /* PushActiveSnapshotWithLevel might have copied the snapshot */
1798}
#define unlikely(x)
Definition: c.h:330
Portal ActivePortal
Definition: pquery.c:35
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:212
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:740
void PushActiveSnapshotWithLevel(Snapshot snapshot, int snap_level)
Definition: snapmgr.c:624
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:728
Snapshot portalSnapshot
Definition: portal.h:169
int createLevel
Definition: portal.h:133

References ActivePortal, ActiveSnapshotSet(), Assert, PortalData::createLevel, elog, ERROR, GetActiveSnapshot(), GetTransactionSnapshot(), PortalData::portalSnapshot, PushActiveSnapshotWithLevel(), and unlikely.

Referenced by _SPI_execute_plan(), exec_eval_simple_expr(), and ExecuteCallStmt().

◆ FetchPortalTargetList()

List * FetchPortalTargetList ( Portal  portal)

Definition at line 326 of file pquery.c.

327{
328 /* no point in looking if we determined it doesn't return tuples */
329 if (portal->strategy == PORTAL_MULTI_QUERY)
330 return NIL;
331 /* get the primary statement and find out what it returns */
333}
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition: portalmem.c:151
List * FetchStatementTargetList(Node *stmt)
Definition: pquery.c:348

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

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

◆ FetchStatementTargetList()

List * FetchStatementTargetList ( Node stmt)

Definition at line 348 of file pquery.c.

349{
350 if (stmt == NULL)
351 return NIL;
352 if (IsA(stmt, Query))
353 {
354 Query *query = (Query *) stmt;
355
356 if (query->commandType == CMD_UTILITY)
357 {
358 /* transfer attention to utility statement */
359 stmt = query->utilityStmt;
360 }
361 else
362 {
363 if (query->commandType == CMD_SELECT)
364 return query->targetList;
365 if (query->returningList)
366 return query->returningList;
367 return NIL;
368 }
369 }
370 if (IsA(stmt, PlannedStmt))
371 {
372 PlannedStmt *pstmt = (PlannedStmt *) stmt;
373
374 if (pstmt->commandType == CMD_UTILITY)
375 {
376 /* transfer attention to utility statement */
377 stmt = pstmt->utilityStmt;
378 }
379 else
380 {
381 if (pstmt->commandType == CMD_SELECT)
382 return pstmt->planTree->targetlist;
383 if (pstmt->hasReturning)
384 return pstmt->planTree->targetlist;
385 return NIL;
386 }
387 }
388 if (IsA(stmt, FetchStmt))
389 {
390 FetchStmt *fstmt = (FetchStmt *) stmt;
391 Portal subportal;
392
393 Assert(!fstmt->ismove);
394 subportal = GetPortalByName(fstmt->portalname);
395 Assert(PortalIsValid(subportal));
396 return FetchPortalTargetList(subportal);
397 }
398 if (IsA(stmt, ExecuteStmt))
399 {
400 ExecuteStmt *estmt = (ExecuteStmt *) stmt;
401 PreparedStatement *entry;
402
403 entry = FetchPreparedStatement(estmt->name, true);
405 }
406 return NIL;
407}
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:431
List * FetchPreparedStatementTargetList(PreparedStatement *stmt)
Definition: prepare.c:486
#define PortalIsValid(p)
Definition: portal.h:211
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:326
char * name
Definition: parsenodes.h:4075
bool ismove
Definition: parsenodes.h:3360
char * portalname
Definition: parsenodes.h:3359
List * targetlist
Definition: plannodes.h:153
struct Plan * planTree
Definition: plannodes.h:70
List * targetList
Definition: parsenodes.h:193

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

Referenced by CachedPlanGetTargetList(), and FetchPortalTargetList().

◆ FillPortalStore()

static void FillPortalStore ( Portal  portal,
bool  isTopLevel 
)
static

Definition at line 994 of file pquery.c.

995{
996 DestReceiver *treceiver;
998
1000 PortalCreateHoldStore(portal);
1003 portal->holdStore,
1004 portal->holdContext,
1005 false,
1006 NULL,
1007 NULL);
1008
1009 switch (portal->strategy)
1010 {
1013
1014 /*
1015 * Run the portal to completion just as for the default
1016 * PORTAL_MULTI_QUERY case, but send the primary query's output to
1017 * the tuplestore. Auxiliary query outputs are discarded. Set the
1018 * portal's holdSnapshot to the snapshot used (or a copy of it).
1019 */
1020 PortalRunMulti(portal, isTopLevel, true,
1021 treceiver, None_Receiver, &qc);
1022 break;
1023
1024 case PORTAL_UTIL_SELECT:
1026 isTopLevel, true, treceiver, &qc);
1027 break;
1028
1029 default:
1030 elog(ERROR, "unsupported portal strategy: %d",
1031 (int) portal->strategy);
1032 break;
1033 }
1034
1035 /* Override portal completion data with actual command results */
1036 if (qc.commandTag != CMDTAG_UNKNOWN)
1037 CopyQueryCompletion(&portal->qc, &qc);
1038
1039 treceiver->rDestroy(treceiver);
1040}
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:40
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:45
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
@ DestTuplestore
Definition: dest.h:93
#define linitial_node(type, l)
Definition: pg_list.h:181
void PortalCreateHoldStore(Portal portal)
Definition: portalmem.c:331
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:1184
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:1121
List * stmts
Definition: portal.h:139
QueryCompletion qc
Definition: portal.h:138
CommandTag commandTag
Definition: cmdtag.h:31
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:126
void SetTuplestoreDestReceiverParams(DestReceiver *self, Tuplestorestate *tStore, MemoryContext tContext, bool detoast, TupleDesc target_tupdesc, const char *map_failure_msg)

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().

◆ FreeQueryDesc()

void FreeQueryDesc ( QueryDesc qdesc)

Definition at line 105 of file pquery.c.

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}
void pfree(void *pointer)
Definition: mcxt.c:1521
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:794

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().

◆ PlannedStmtRequiresSnapshot()

bool PlannedStmtRequiresSnapshot ( PlannedStmt pstmt)

Definition at line 1723 of file pquery.c.

1724{
1725 Node *utilityStmt = pstmt->utilityStmt;
1726
1727 /* If it's not a utility statement, it definitely needs a snapshot */
1728 if (utilityStmt == NULL)
1729 return true;
1730
1731 /*
1732 * Most utility statements need a snapshot, and the default presumption
1733 * about new ones should be that they do too. Hence, enumerate those that
1734 * do not need one.
1735 *
1736 * Transaction control, LOCK, and SET must *not* set a snapshot, since
1737 * they need to be executable at the start of a transaction-snapshot-mode
1738 * transaction without freezing a snapshot. By extension we allow SHOW
1739 * not to set a snapshot. The other stmts listed are just efficiency
1740 * hacks. Beware of listing anything that can modify the database --- if,
1741 * say, it has to update an index with expressions that invoke
1742 * user-defined functions, then it had better have a snapshot.
1743 */
1744 if (IsA(utilityStmt, TransactionStmt) ||
1745 IsA(utilityStmt, LockStmt) ||
1746 IsA(utilityStmt, VariableSetStmt) ||
1747 IsA(utilityStmt, VariableShowStmt) ||
1748 IsA(utilityStmt, ConstraintsSetStmt) ||
1749 /* efficiency hacks from here down */
1750 IsA(utilityStmt, FetchStmt) ||
1751 IsA(utilityStmt, ListenStmt) ||
1752 IsA(utilityStmt, NotifyStmt) ||
1753 IsA(utilityStmt, UnlistenStmt) ||
1754 IsA(utilityStmt, CheckPointStmt))
1755 return false;
1756
1757 return true;
1758}

References IsA, and PlannedStmt::utilityStmt.

Referenced by _SPI_execute_plan(), and PortalRunUtility().

◆ PortalRun()

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

Definition at line 684 of file pquery.c.

687{
688 bool result;
689 uint64 nprocessed;
690 ResourceOwner saveTopTransactionResourceOwner;
691 MemoryContext saveTopTransactionContext;
692 Portal saveActivePortal;
693 ResourceOwner saveResourceOwner;
694 MemoryContext savePortalContext;
695 MemoryContext saveMemoryContext;
696
697 Assert(PortalIsValid(portal));
698
699 TRACE_POSTGRESQL_QUERY_EXECUTE_START();
700
701 /* Initialize empty completion data */
702 if (qc)
704
706 {
707 elog(DEBUG3, "PortalRun");
708 /* PORTAL_MULTI_QUERY logs its own stats per query */
709 ResetUsage();
710 }
711
712 /*
713 * Check for improper portal use, and mark portal active.
714 */
715 MarkPortalActive(portal);
716
717 /*
718 * Set up global portal context pointers.
719 *
720 * We have to play a special game here to support utility commands like
721 * VACUUM and CLUSTER, which internally start and commit transactions.
722 * When we are called to execute such a command, CurrentResourceOwner will
723 * be pointing to the TopTransactionResourceOwner --- which will be
724 * destroyed and replaced in the course of the internal commit and
725 * restart. So we need to be prepared to restore it as pointing to the
726 * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
727 * internally starting whole new transactions is not good.)
728 * CurrentMemoryContext has a similar problem, but the other pointers we
729 * save here will be NULL or pointing to longer-lived objects.
730 */
731 saveTopTransactionResourceOwner = TopTransactionResourceOwner;
732 saveTopTransactionContext = TopTransactionContext;
733 saveActivePortal = ActivePortal;
734 saveResourceOwner = CurrentResourceOwner;
735 savePortalContext = PortalContext;
736 saveMemoryContext = CurrentMemoryContext;
737 PG_TRY();
738 {
739 ActivePortal = portal;
740 if (portal->resowner)
743
745
746 switch (portal->strategy)
747 {
752
753 /*
754 * If we have not yet run the command, do so, storing its
755 * results in the portal's tuplestore. But we don't do that
756 * for the PORTAL_ONE_SELECT case.
757 */
758 if (portal->strategy != PORTAL_ONE_SELECT && !portal->holdStore)
759 FillPortalStore(portal, isTopLevel);
760
761 /*
762 * Now fetch desired portion of results.
763 */
764 nprocessed = PortalRunSelect(portal, true, count, dest);
765
766 /*
767 * If the portal result contains a command tag and the caller
768 * gave us a pointer to store it, copy it and update the
769 * rowcount.
770 */
771 if (qc && portal->qc.commandTag != CMDTAG_UNKNOWN)
772 {
773 CopyQueryCompletion(qc, &portal->qc);
774 qc->nprocessed = nprocessed;
775 }
776
777 /* Mark portal not active */
778 portal->status = PORTAL_READY;
779
780 /*
781 * Since it's a forward fetch, say DONE iff atEnd is now true.
782 */
783 result = portal->atEnd;
784 break;
785
787 PortalRunMulti(portal, isTopLevel, false,
788 dest, altdest, qc);
789
790 /* Prevent portal's commands from being re-executed */
791 MarkPortalDone(portal);
792
793 /* Always complete at end of RunMulti */
794 result = true;
795 break;
796
797 default:
798 elog(ERROR, "unrecognized portal strategy: %d",
799 (int) portal->strategy);
800 result = false; /* keep compiler quiet */
801 break;
802 }
803 }
804 PG_CATCH();
805 {
806 /* Uncaught error while executing portal: mark it dead */
807 MarkPortalFailed(portal);
808
809 /* Restore global vars and propagate error */
810 if (saveMemoryContext == saveTopTransactionContext)
812 else
813 MemoryContextSwitchTo(saveMemoryContext);
814 ActivePortal = saveActivePortal;
815 if (saveResourceOwner == saveTopTransactionResourceOwner)
817 else
818 CurrentResourceOwner = saveResourceOwner;
819 PortalContext = savePortalContext;
820
821 PG_RE_THROW();
822 }
823 PG_END_TRY();
824
825 if (saveMemoryContext == saveTopTransactionContext)
827 else
828 MemoryContextSwitchTo(saveMemoryContext);
829 ActivePortal = saveActivePortal;
830 if (saveResourceOwner == saveTopTransactionResourceOwner)
832 else
833 CurrentResourceOwner = saveResourceOwner;
834 PortalContext = savePortalContext;
835
837 ShowUsage("EXECUTOR STATISTICS");
838
839 TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
840
841 return result;
842}
#define PG_RE_THROW()
Definition: elog.h:412
#define DEBUG3
Definition: elog.h:28
#define PG_TRY(...)
Definition: elog.h:371
#define PG_END_TRY(...)
Definition: elog.h:396
#define PG_CATCH(...)
Definition: elog.h:381
bool log_executor_stats
Definition: guc_tables.c:504
MemoryContext TopTransactionContext
Definition: mcxt.c:154
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
MemoryContext PortalContext
Definition: mcxt.c:158
@ PORTAL_READY
Definition: portal.h:107
void MarkPortalDone(Portal portal)
Definition: portalmem.c:414
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:442
void MarkPortalActive(Portal portal)
Definition: portalmem.c:395
void ShowUsage(const char *title)
Definition: postgres.c:4984
void ResetUsage(void)
Definition: postgres.c:4977
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:994
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:167
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
ResourceOwner resowner
Definition: portal.h:121
MemoryContext portalContext
Definition: portal.h:120
PortalStatus status
Definition: portal.h:150
uint64 nprocessed
Definition: cmdtag.h:32

References ActivePortal, Assert, PortalData::atEnd, QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, CurrentResourceOwner, DEBUG3, generate_unaccent_rules::dest, 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, ShowUsage(), PortalData::status, PortalData::strategy, TopTransactionContext, and TopTransactionResourceOwner.

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

◆ PortalRunFetch()

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

Definition at line 1385 of file pquery.c.

1389{
1390 uint64 result;
1391 Portal saveActivePortal;
1392 ResourceOwner saveResourceOwner;
1393 MemoryContext savePortalContext;
1394 MemoryContext oldContext;
1395
1396 Assert(PortalIsValid(portal));
1397
1398 /*
1399 * Check for improper portal use, and mark portal active.
1400 */
1401 MarkPortalActive(portal);
1402
1403 /*
1404 * Set up global portal context pointers.
1405 */
1406 saveActivePortal = ActivePortal;
1407 saveResourceOwner = CurrentResourceOwner;
1408 savePortalContext = PortalContext;
1409 PG_TRY();
1410 {
1411 ActivePortal = portal;
1412 if (portal->resowner)
1414 PortalContext = portal->portalContext;
1415
1417
1418 switch (portal->strategy)
1419 {
1420 case PORTAL_ONE_SELECT:
1421 result = DoPortalRunFetch(portal, fdirection, count, dest);
1422 break;
1423
1426 case PORTAL_UTIL_SELECT:
1427
1428 /*
1429 * If we have not yet run the command, do so, storing its
1430 * results in the portal's tuplestore.
1431 */
1432 if (!portal->holdStore)
1433 FillPortalStore(portal, false /* isTopLevel */ );
1434
1435 /*
1436 * Now fetch desired portion of results.
1437 */
1438 result = DoPortalRunFetch(portal, fdirection, count, dest);
1439 break;
1440
1441 default:
1442 elog(ERROR, "unsupported portal strategy");
1443 result = 0; /* keep compiler quiet */
1444 break;
1445 }
1446 }
1447 PG_CATCH();
1448 {
1449 /* Uncaught error while executing portal: mark it dead */
1450 MarkPortalFailed(portal);
1451
1452 /* Restore global vars and propagate error */
1453 ActivePortal = saveActivePortal;
1454 CurrentResourceOwner = saveResourceOwner;
1455 PortalContext = savePortalContext;
1456
1457 PG_RE_THROW();
1458 }
1459 PG_END_TRY();
1460
1461 MemoryContextSwitchTo(oldContext);
1462
1463 /* Mark portal not active */
1464 portal->status = PORTAL_READY;
1465
1466 ActivePortal = saveActivePortal;
1467 CurrentResourceOwner = saveResourceOwner;
1468 PortalContext = savePortalContext;
1469
1470 return result;
1471}
static uint64 DoPortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1483

References ActivePortal, Assert, CurrentResourceOwner, generate_unaccent_rules::dest, 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::status, and PortalData::strategy.

Referenced by _SPI_cursor_operation(), and PerformPortalFetch().

◆ 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.

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)
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
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
1258 /*
1259 * As for PORTAL_ONE_SELECT portals, it does not seem
1260 * necessary to maintain portal->portalSnapshot here.
1261 */
1262
1263 active_snapshot_set = true;
1264 }
1265 else
1267
1268 if (pstmt->canSetTag)
1269 {
1270 /* statement can set tag string */
1271 ProcessQuery(pstmt,
1272 portal->sourceText,
1273 portal->portalParams,
1274 portal->queryEnv,
1275 dest, qc);
1276 }
1277 else
1278 {
1279 /* stmt added by rewrite cannot set tag */
1280 ProcessQuery(pstmt,
1281 portal->sourceText,
1282 portal->portalParams,
1283 portal->queryEnv,
1284 altdest, NULL);
1285 }
1286
1288 ShowUsage("EXECUTOR STATISTICS");
1289
1290 TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
1291 }
1292 else
1293 {
1294 /*
1295 * process utility functions (create, destroy, etc..)
1296 *
1297 * We must not set a snapshot here for utility commands (if one is
1298 * needed, PortalRunUtility will do it). If a utility command is
1299 * alone in a portal then everything's fine. The only case where
1300 * a utility command can be part of a longer list is that rules
1301 * are allowed to include NotifyStmt. NotifyStmt doesn't care
1302 * whether it has a snapshot or not, so we just leave the current
1303 * snapshot alone if we have one.
1304 */
1305 if (pstmt->canSetTag)
1306 {
1307 Assert(!active_snapshot_set);
1308 /* statement can set tag string */
1309 PortalRunUtility(portal, pstmt, isTopLevel, false,
1310 dest, qc);
1311 }
1312 else
1313 {
1314 Assert(IsA(pstmt->utilityStmt, NotifyStmt));
1315 /* stmt added by rewrite cannot set tag */
1316 PortalRunUtility(portal, pstmt, isTopLevel, false,
1317 altdest, NULL);
1318 }
1319 }
1320
1321 /*
1322 * Clear subsidiary contexts to recover temporary memory.
1323 */
1325
1327
1328 /*
1329 * Avoid crashing if portal->stmts has been reset. This can only
1330 * occur if a CALL or DO utility statement executed an internal
1331 * COMMIT/ROLLBACK (cf PortalReleaseCachedPlan). The CALL or DO must
1332 * have been the only statement in the portal, so there's nothing left
1333 * for us to do; but we don't want to dereference a now-dangling list
1334 * pointer.
1335 */
1336 if (portal->stmts == NIL)
1337 break;
1338
1339 /*
1340 * Increment command counter between queries, but not after the last
1341 * one.
1342 */
1343 if (lnext(portal->stmts, stmtlist_item) != NULL)
1345 }
1346
1347 /* Pop the snapshot if we pushed one. */
1348 if (active_snapshot_set)
1350
1351 /*
1352 * If a query completion data was supplied, use it. Otherwise use the
1353 * portal's query completion data.
1354 *
1355 * Exception: Clients expect INSERT/UPDATE/DELETE tags to have counts, so
1356 * fake them with zeros. This can happen with DO INSTEAD rules if there
1357 * is no replacement query of the same type as the original. We print "0
1358 * 0" here because technically there is no query of the matching tag type,
1359 * and printing a non-zero count for a different query type seems wrong,
1360 * e.g. an INSERT that does an UPDATE instead should not print "0 1" if
1361 * one row was updated. See QueryRewrite(), step 3, for details.
1362 */
1363 if (qc && qc->commandTag == CMDTAG_UNKNOWN)
1364 {
1365 if (portal->qc.commandTag != CMDTAG_UNKNOWN)
1366 CopyQueryCompletion(qc, &portal->qc);
1367 /* If the caller supplied a qc, we should have set it by now. */
1368 Assert(qc->commandTag != CMDTAG_UNKNOWN);
1369 }
1370}
@ DestRemoteExecute
Definition: dest.h:90
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:539
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
static void ProcessQuery(PlannedStmt *plan, const char *sourceText, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:136
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:672
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:660
const char * sourceText
Definition: portal.h:136
QueryEnvironment * queryEnv
Definition: portal.h:143
ParamListInfo portalParams
Definition: portal.h:142
Snapshot holdSnapshot
Definition: portal.h:187
CommandDest mydest
Definition: dest.h:128
void CommandCounterIncrement(void)
Definition: xact.c:1099

References Assert, PlannedStmt::canSetTag, CHECK_FOR_INTERRUPTS, CommandCounterIncrement(), QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, generate_unaccent_rules::dest, DestRemoteExecute, GetTransactionSnapshot(), PortalData::holdSnapshot, IsA, lfirst_node, lnext(), log_executor_stats, MemoryContextDeleteChildren(), _DestReceiver::mydest, NIL, 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().

◆ PortalRunSelect()

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

Definition at line 863 of file pquery.c.

867{
868 QueryDesc *queryDesc;
869 ScanDirection direction;
870 uint64 nprocessed;
871
872 /*
873 * NB: queryDesc will be NULL if we are fetching from a held cursor or a
874 * completed utility query; can't use it in that path.
875 */
876 queryDesc = portal->queryDesc;
877
878 /* Caller messed up if we have neither a ready query nor held data. */
879 Assert(queryDesc || portal->holdStore);
880
881 /*
882 * Force the queryDesc destination to the right thing. This supports
883 * MOVE, for example, which will pass in dest = DestNone. This is okay to
884 * change as long as we do it on every fetch. (The Executor must not
885 * assume that dest never changes.)
886 */
887 if (queryDesc)
888 queryDesc->dest = dest;
889
890 /*
891 * Determine which direction to go in, and check to see if we're already
892 * at the end of the available tuples in that direction. If so, set the
893 * direction to NoMovement to avoid trying to fetch any tuples. (This
894 * check exists because not all plan node types are robust about being
895 * called again if they've already returned NULL once.) Then call the
896 * executor (we must not skip this, because the destination needs to see a
897 * setup and shutdown even if no tuples are available). Finally, update
898 * the portal position state depending on the number of tuples that were
899 * retrieved.
900 */
901 if (forward)
902 {
903 if (portal->atEnd || count <= 0)
904 {
905 direction = NoMovementScanDirection;
906 count = 0; /* don't pass negative count to executor */
907 }
908 else
909 direction = ForwardScanDirection;
910
911 /* In the executor, zero count processes all rows */
912 if (count == FETCH_ALL)
913 count = 0;
914
915 if (portal->holdStore)
916 nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
917 else
918 {
919 PushActiveSnapshot(queryDesc->snapshot);
920 ExecutorRun(queryDesc, direction, (uint64) count);
921 nprocessed = queryDesc->estate->es_processed;
923 }
924
925 if (!ScanDirectionIsNoMovement(direction))
926 {
927 if (nprocessed > 0)
928 portal->atStart = false; /* OK to go backward now */
929 if (count == 0 || nprocessed < (uint64) count)
930 portal->atEnd = true; /* we retrieved 'em all */
931 portal->portalPos += nprocessed;
932 }
933 }
934 else
935 {
938 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
939 errmsg("cursor can only scan forward"),
940 errhint("Declare it with SCROLL option to enable backward scan.")));
941
942 if (portal->atStart || count <= 0)
943 {
944 direction = NoMovementScanDirection;
945 count = 0; /* don't pass negative count to executor */
946 }
947 else
948 direction = BackwardScanDirection;
949
950 /* In the executor, zero count processes all rows */
951 if (count == FETCH_ALL)
952 count = 0;
953
954 if (portal->holdStore)
955 nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
956 else
957 {
958 PushActiveSnapshot(queryDesc->snapshot);
959 ExecutorRun(queryDesc, direction, (uint64) count);
960 nprocessed = queryDesc->estate->es_processed;
962 }
963
964 if (!ScanDirectionIsNoMovement(direction))
965 {
966 if (nprocessed > 0 && portal->atEnd)
967 {
968 portal->atEnd = false; /* OK to go forward now */
969 portal->portalPos++; /* adjust for endpoint case */
970 }
971 if (count == 0 || nprocessed < (uint64) count)
972 {
973 portal->atStart = true; /* we retrieved 'em all */
974 portal->portalPos = 0;
975 }
976 else
977 {
978 portal->portalPos -= nprocessed;
979 }
980 }
981 }
982
983 return nprocessed;
984}
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:294
static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count, DestReceiver *dest)
Definition: pquery.c:1055
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:57
ScanDirection
Definition: sdir.h:25
@ NoMovementScanDirection
Definition: sdir.h:27
@ BackwardScanDirection
Definition: sdir.h:26
@ ForwardScanDirection
Definition: sdir.h:28
uint64 es_processed
Definition: execnodes.h:679

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

Referenced by DoPortalRunFetch(), and PortalRun().

◆ PortalRunUtility()

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

Definition at line 1121 of file pquery.c.

1124{
1125 /*
1126 * Set snapshot if utility stmt needs one.
1127 */
1128 if (PlannedStmtRequiresSnapshot(pstmt))
1129 {
1130 Snapshot snapshot = GetTransactionSnapshot();
1131
1132 /* If told to, register the snapshot we're using and save in portal */
1133 if (setHoldSnapshot)
1134 {
1135 snapshot = RegisterSnapshot(snapshot);
1136 portal->holdSnapshot = snapshot;
1137 }
1138
1139 /*
1140 * In any case, make the snapshot active and remember it in portal.
1141 * Because the portal now references the snapshot, we must tell
1142 * snapmgr.c that the snapshot belongs to the portal's transaction
1143 * level, else we risk portalSnapshot becoming a dangling pointer.
1144 */
1145 PushActiveSnapshotWithLevel(snapshot, portal->createLevel);
1146 /* PushActiveSnapshotWithLevel might have copied the snapshot */
1148 }
1149 else
1150 portal->portalSnapshot = NULL;
1151
1152 ProcessUtility(pstmt,
1153 portal->sourceText,
1154 (portal->cplan != NULL), /* protect tree if in plancache */
1156 portal->portalParams,
1157 portal->queryEnv,
1158 dest,
1159 qc);
1160
1161 /* Some utility statements may change context on us */
1163
1164 /*
1165 * Some utility commands (e.g., VACUUM) pop the ActiveSnapshot stack from
1166 * under us, so don't complain if it's now empty. Otherwise, our snapshot
1167 * should be the top one; pop it. Note that this could be a different
1168 * snapshot from the one we made above; see EnsurePortalSnapshotExists.
1169 */
1170 if (portal->portalSnapshot != NULL && ActiveSnapshotSet())
1171 {
1174 }
1175 portal->portalSnapshot = NULL;
1176}
bool PlannedStmtRequiresSnapshot(PlannedStmt *pstmt)
Definition: pquery.c:1723
CachedPlan * cplan
Definition: portal.h:140
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:499
@ PROCESS_UTILITY_TOPLEVEL
Definition: utility.h:22
@ PROCESS_UTILITY_QUERY
Definition: utility.h:23

References ActiveSnapshotSet(), Assert, PortalData::cplan, PortalData::createLevel, generate_unaccent_rules::dest, GetActiveSnapshot(), GetTransactionSnapshot(), PortalData::holdSnapshot, MemoryContextSwitchTo(), PlannedStmtRequiresSnapshot(), PopActiveSnapshot(), PortalData::portalContext, PortalData::portalParams, PortalData::portalSnapshot, PROCESS_UTILITY_QUERY, PROCESS_UTILITY_TOPLEVEL, ProcessUtility(), PushActiveSnapshotWithLevel(), PortalData::queryEnv, RegisterSnapshot(), and PortalData::sourceText.

Referenced by FillPortalStore(), and PortalRunMulti().

◆ PortalSetResultFormat()

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

Definition at line 623 of file pquery.c.

624{
625 int natts;
626 int i;
627
628 /* Do nothing if portal won't return tuples */
629 if (portal->tupDesc == NULL)
630 return;
631 natts = portal->tupDesc->natts;
632 portal->formats = (int16 *)
634 natts * sizeof(int16));
635 if (nFormats > 1)
636 {
637 /* format specified for each column */
638 if (nFormats != natts)
640 (errcode(ERRCODE_PROTOCOL_VIOLATION),
641 errmsg("bind message has %d result formats but query has %d columns",
642 nFormats, natts)));
643 memcpy(portal->formats, formats, natts * sizeof(int16));
644 }
645 else if (nFormats > 0)
646 {
647 /* single format specified, use for all columns */
648 int16 format1 = formats[0];
649
650 for (i = 0; i < natts; i++)
651 portal->formats[i] = format1;
652 }
653 else
654 {
655 /* use default format for all columns */
656 for (i = 0; i < natts; i++)
657 portal->formats[i] = 0;
658 }
659}
int16_t int16
Definition: c.h:480
int i
Definition: isn.c:72
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1181
int16 * formats
Definition: portal.h:161
TupleDesc tupDesc
Definition: portal.h:159

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().

◆ PortalStart()

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

Definition at line 433 of file pquery.c.

435{
436 Portal saveActivePortal;
437 ResourceOwner saveResourceOwner;
438 MemoryContext savePortalContext;
439 MemoryContext oldContext;
440 QueryDesc *queryDesc;
441 int myeflags;
442
443 Assert(PortalIsValid(portal));
444 Assert(portal->status == PORTAL_DEFINED);
445
446 /*
447 * Set up global portal context pointers.
448 */
449 saveActivePortal = ActivePortal;
450 saveResourceOwner = CurrentResourceOwner;
451 savePortalContext = PortalContext;
452 PG_TRY();
453 {
454 ActivePortal = portal;
455 if (portal->resowner)
458
460
461 /* Must remember portal param list, if any */
462 portal->portalParams = params;
463
464 /*
465 * Determine the portal execution strategy
466 */
467 portal->strategy = ChoosePortalStrategy(portal->stmts);
468
469 /*
470 * Fire her up according to the strategy
471 */
472 switch (portal->strategy)
473 {
475
476 /* Must set snapshot before starting executor. */
477 if (snapshot)
478 PushActiveSnapshot(snapshot);
479 else
481
482 /*
483 * We could remember the snapshot in portal->portalSnapshot,
484 * but presently there seems no need to, as this code path
485 * cannot be used for non-atomic execution. Hence there can't
486 * be any commit/abort that might destroy the snapshot. Since
487 * we don't do that, there's also no need to force a
488 * non-default nesting level for the snapshot.
489 */
490
491 /*
492 * Create QueryDesc in portal's context; for the moment, set
493 * the destination to DestNone.
494 */
495 queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
496 portal->sourceText,
500 params,
501 portal->queryEnv,
502 0);
503
504 /*
505 * If it's a scrollable cursor, executor needs to support
506 * REWIND and backwards scan, as well as whatever the caller
507 * might've asked for.
508 */
509 if (portal->cursorOptions & CURSOR_OPT_SCROLL)
510 myeflags = eflags | EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
511 else
512 myeflags = eflags;
513
514 /*
515 * Call ExecutorStart to prepare the plan for execution
516 */
517 ExecutorStart(queryDesc, myeflags);
518
519 /*
520 * This tells PortalCleanup to shut down the executor
521 */
522 portal->queryDesc = queryDesc;
523
524 /*
525 * Remember tuple descriptor (computed by ExecutorStart)
526 */
527 portal->tupDesc = queryDesc->tupDesc;
528
529 /*
530 * Reset cursor position data to "start of query"
531 */
532 portal->atStart = true;
533 portal->atEnd = false; /* allow fetches */
534 portal->portalPos = 0;
535
537 break;
538
541
542 /*
543 * We don't start the executor until we are told to run the
544 * portal. We do need to set up the result tupdesc.
545 */
546 {
547 PlannedStmt *pstmt;
548
549 pstmt = PortalGetPrimaryStmt(portal);
550 portal->tupDesc =
552 }
553
554 /*
555 * Reset cursor position data to "start of query"
556 */
557 portal->atStart = true;
558 portal->atEnd = false; /* allow fetches */
559 portal->portalPos = 0;
560 break;
561
563
564 /*
565 * We don't set snapshot here, because PortalRunUtility will
566 * take care of it if needed.
567 */
568 {
569 PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
570
571 Assert(pstmt->commandType == CMD_UTILITY);
573 }
574
575 /*
576 * Reset cursor position data to "start of query"
577 */
578 portal->atStart = true;
579 portal->atEnd = false; /* allow fetches */
580 portal->portalPos = 0;
581 break;
582
584 /* Need do nothing now */
585 portal->tupDesc = NULL;
586 break;
587 }
588 }
589 PG_CATCH();
590 {
591 /* Uncaught error while executing portal: mark it dead */
592 MarkPortalFailed(portal);
593
594 /* Restore global vars and propagate error */
595 ActivePortal = saveActivePortal;
596 CurrentResourceOwner = saveResourceOwner;
597 PortalContext = savePortalContext;
598
599 PG_RE_THROW();
600 }
601 PG_END_TRY();
602
603 MemoryContextSwitchTo(oldContext);
604
605 ActivePortal = saveActivePortal;
606 CurrentResourceOwner = saveResourceOwner;
607 PortalContext = savePortalContext;
608
609 portal->status = PORTAL_READY;
610}
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:119
TupleDesc ExecCleanTypeFromTL(List *targetList)
Definition: execTuples.c:2137
#define EXEC_FLAG_BACKWARD
Definition: executor.h:68
#define EXEC_FLAG_REWIND
Definition: executor.h:67
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:3308
@ PORTAL_DEFINED
Definition: portal.h:106
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
PortalStrategy ChoosePortalStrategy(List *stmts)
Definition: pquery.c:209
#define InvalidSnapshot
Definition: snapshot.h:119
TupleDesc UtilityTupleDescriptor(Node *parsetree)
Definition: utility.c:2084

References ActivePortal, Assert, 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().

◆ 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.

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, 0);
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 case CMD_MERGE:
182 SetQueryCompletion(qc, CMDTAG_MERGE, queryDesc->estate->es_processed);
183 break;
184 default:
185 SetQueryCompletion(qc, CMDTAG_UNKNOWN, queryDesc->estate->es_processed);
186 break;
187 }
188 }
189
190 /*
191 * Now, we close down all the scans and free allocated resources.
192 */
193 ExecutorFinish(queryDesc);
194 ExecutorEnd(queryDesc);
195
196 FreeQueryDesc(queryDesc);
197}
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:37
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:463
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:403
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
#define plan(x)
Definition: pg_regress.c:161
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105

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

Referenced by PortalRunMulti().

◆ RunFromStore()

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

Definition at line 1055 of file pquery.c.

1057{
1058 uint64 current_tuple_count = 0;
1059 TupleTableSlot *slot;
1060
1062
1063 dest->rStartup(dest, CMD_SELECT, portal->tupDesc);
1064
1065 if (ScanDirectionIsNoMovement(direction))
1066 {
1067 /* do nothing except start/stop the destination */
1068 }
1069 else
1070 {
1071 bool forward = ScanDirectionIsForward(direction);
1072
1073 for (;;)
1074 {
1075 MemoryContext oldcontext;
1076 bool ok;
1077
1078 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1079
1080 ok = tuplestore_gettupleslot(portal->holdStore, forward, false,
1081 slot);
1082
1083 MemoryContextSwitchTo(oldcontext);
1084
1085 if (!ok)
1086 break;
1087
1088 /*
1089 * If we are not able to send the tuple, we assume the destination
1090 * has closed and no more tuples can be sent. If that's the case,
1091 * end the loop.
1092 */
1093 if (!dest->receiveSlot(slot, dest))
1094 break;
1095
1096 ExecClearTuple(slot);
1097
1098 /*
1099 * check our tuple count.. if we've processed the proper number
1100 * then quit, else loop again and process more tuples. Zero count
1101 * means no limit.
1102 */
1103 current_tuple_count++;
1104 if (count && count == current_tuple_count)
1105 break;
1106 }
1107 }
1108
1109 dest->rShutdown(dest);
1110
1112
1113 return current_tuple_count;
1114}
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1425
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1441
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:86
#define ScanDirectionIsForward(direction)
Definition: sdir.h:64
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1130
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454

References CMD_SELECT, generate_unaccent_rules::dest, ExecClearTuple(), ExecDropSingleTupleTableSlot(), PortalData::holdContext, PortalData::holdStore, MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), ScanDirectionIsForward, ScanDirectionIsNoMovement, TTSOpsMinimalTuple, PortalData::tupDesc, and tuplestore_gettupleslot().

Referenced by PortalRunSelect().

Variable Documentation

◆ ActivePortal