Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pquery.c
4 : : * POSTGRES process query command code
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/tcop/pquery.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include <limits.h>
19 : :
20 : : #include "access/xact.h"
21 : : #include "commands/prepare.h"
22 : : #include "executor/executor.h"
23 : : #include "executor/tstoreReceiver.h"
24 : : #include "miscadmin.h"
25 : : #include "pg_trace.h"
26 : : #include "tcop/pquery.h"
27 : : #include "tcop/utility.h"
28 : : #include "utils/memutils.h"
29 : : #include "utils/snapmgr.h"
30 : :
31 : :
32 : : /*
33 : : * ActivePortal is the currently executing Portal (the most closely nested,
34 : : * if there are several).
35 : : */
36 : : Portal ActivePortal = NULL;
37 : :
38 : :
39 : : static void ProcessQuery(PlannedStmt *plan,
40 : : const char *sourceText,
41 : : ParamListInfo params,
42 : : QueryEnvironment *queryEnv,
43 : : DestReceiver *dest,
44 : : QueryCompletion *qc);
45 : : static void FillPortalStore(Portal portal, bool isTopLevel);
46 : : static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count,
47 : : DestReceiver *dest);
48 : : static uint64 PortalRunSelect(Portal portal, bool forward, long count,
49 : : DestReceiver *dest);
50 : : static void PortalRunUtility(Portal portal, PlannedStmt *pstmt,
51 : : bool isTopLevel, bool setHoldSnapshot,
52 : : DestReceiver *dest, QueryCompletion *qc);
53 : : static void PortalRunMulti(Portal portal,
54 : : bool isTopLevel, bool setHoldSnapshot,
55 : : DestReceiver *dest, DestReceiver *altdest,
56 : : QueryCompletion *qc);
57 : : static uint64 DoPortalRunFetch(Portal portal,
58 : : FetchDirection fdirection,
59 : : long count,
60 : : DestReceiver *dest);
61 : : static void DoPortalRewind(Portal portal);
62 : :
63 : :
64 : : /*
65 : : * CreateQueryDesc
66 : : */
67 : : QueryDesc *
6906 bruce@momjian.us 68 :CBC 369920 : CreateQueryDesc(PlannedStmt *plannedstmt,
69 : : const char *sourceText,
70 : : Snapshot snapshot,
71 : : Snapshot crosscheck_snapshot,
72 : : DestReceiver *dest,
73 : : ParamListInfo params,
74 : : QueryEnvironment *queryEnv,
75 : : int instrument_options)
76 : : {
306 michael@paquier.xyz 77 : 369920 : QueryDesc *qd = palloc_object(QueryDesc);
78 : :
7174 tgl@sss.pgh.pa.us 79 : 369920 : qd->operation = plannedstmt->commandType; /* operation */
3400 80 : 369920 : qd->plannedstmt = plannedstmt; /* plan */
6332 bruce@momjian.us 81 : 369920 : qd->sourceText = sourceText; /* query text */
6727 alvherre@alvh.no-ip. 82 : 369920 : qd->snapshot = RegisterSnapshot(snapshot); /* snapshot */
83 : : /* RI check snapshot */
84 : 369920 : qd->crosscheck_snapshot = RegisterSnapshot(crosscheck_snapshot);
10627 bruce@momjian.us 85 : 369920 : qd->dest = dest; /* output dest */
8712 tgl@sss.pgh.pa.us 86 : 369920 : qd->params = params; /* parameter values passed into query */
3482 kgrittn@postgresql.o 87 : 369920 : qd->queryEnv = queryEnv;
3400 tgl@sss.pgh.pa.us 88 : 369920 : qd->instrument_options = instrument_options; /* instrumentation wanted? */
187 andres@anarazel.de 89 : 369920 : qd->query_instr_options = 0;
90 : :
91 : : /* null these fields until set by ExecutorStart */
8712 tgl@sss.pgh.pa.us 92 : 369920 : qd->tupDesc = NULL;
93 : 369920 : qd->estate = NULL;
94 : 369920 : qd->planstate = NULL;
187 andres@anarazel.de 95 : 369920 : qd->query_instr = NULL;
96 : :
97 : : /* not yet executed */
3490 rhaas@postgresql.org 98 : 369920 : qd->already_executed = false;
99 : :
8712 tgl@sss.pgh.pa.us 100 : 369920 : return qd;
101 : : }
102 : :
103 : : /*
104 : : * FreeQueryDesc
105 : : */
106 : : void
8702 107 : 350991 : FreeQueryDesc(QueryDesc *qdesc)
108 : : {
109 : : /* Can't be a live query */
110 [ - + ]: 350991 : Assert(qdesc->estate == NULL);
111 : :
112 : : /* forget our snapshots */
6727 alvherre@alvh.no-ip. 113 : 350991 : UnregisterSnapshot(qdesc->snapshot);
114 : 350991 : UnregisterSnapshot(qdesc->crosscheck_snapshot);
115 : :
116 : : /* Only the QueryDesc itself need be freed */
8702 tgl@sss.pgh.pa.us 117 : 350991 : pfree(qdesc);
118 : 350991 : }
119 : :
120 : :
121 : : /*
122 : : * ProcessQuery
123 : : * Execute a single plannable query within a PORTAL_MULTI_QUERY,
124 : : * PORTAL_ONE_RETURNING, or PORTAL_ONE_MOD_WITH portal
125 : : *
126 : : * plan: the plan tree for the query
127 : : * sourceText: the source text of the query
128 : : * params: any parameters needed
129 : : * dest: where to send results
130 : : * qc: where to store the command completion status data.
131 : : *
132 : : * qc may be NULL if caller doesn't want a status string.
133 : : *
134 : : * Must be called in a memory context that will be reset or deleted on
135 : : * error; otherwise the executor's memory usage will be leaked.
136 : : */
137 : : static void
6906 bruce@momjian.us 138 : 54133 : ProcessQuery(PlannedStmt *plan,
139 : : const char *sourceText,
140 : : ParamListInfo params,
141 : : QueryEnvironment *queryEnv,
142 : : DestReceiver *dest,
143 : : QueryCompletion *qc)
144 : : {
145 : : QueryDesc *queryDesc;
146 : :
147 : : /*
148 : : * Create the QueryDesc object
149 : : */
508 amitlan@postgresql.o 150 : 54133 : queryDesc = CreateQueryDesc(plan, sourceText,
151 : : GetActiveSnapshot(), InvalidSnapshot,
152 : : dest, params, queryEnv, 0);
153 : :
154 : : /*
155 : : * Call ExecutorStart to prepare the plan for execution
156 : : */
157 : 54133 : ExecutorStart(queryDesc, 0);
158 : :
159 : : /*
160 : : * Run the plan to completion.
161 : : */
672 tgl@sss.pgh.pa.us 162 : 53440 : ExecutorRun(queryDesc, ForwardScanDirection, 0);
163 : :
164 : : /*
165 : : * Build command completion status data, if caller wants one.
166 : : */
2415 alvherre@alvh.no-ip. 167 [ + + ]: 51271 : if (qc)
168 : : {
169 : : CommandTag tag;
170 : :
347 alvherre@kurilemu.de 171 [ + + ]: 50831 : if (queryDesc->operation == CMD_SELECT)
172 : 81 : tag = CMDTAG_SELECT;
173 [ + + ]: 50750 : else if (queryDesc->operation == CMD_INSERT)
174 : 40870 : tag = CMDTAG_INSERT;
175 [ + + ]: 9880 : else if (queryDesc->operation == CMD_UPDATE)
176 : 6872 : tag = CMDTAG_UPDATE;
177 [ + + ]: 3008 : else if (queryDesc->operation == CMD_DELETE)
178 : 2260 : tag = CMDTAG_DELETE;
179 [ + - ]: 748 : else if (queryDesc->operation == CMD_MERGE)
180 : 748 : tag = CMDTAG_MERGE;
181 : : else
347 alvherre@kurilemu.de 182 :UBC 0 : tag = CMDTAG_UNKNOWN;
183 : :
347 alvherre@kurilemu.de 184 :CBC 50831 : SetQueryCompletion(qc, tag, queryDesc->estate->es_processed);
185 : : }
186 : :
187 : : /*
188 : : * Now, we close down all the scans and free allocated resources.
189 : : */
5706 tgl@sss.pgh.pa.us 190 : 51271 : ExecutorFinish(queryDesc);
8712 191 : 50469 : ExecutorEnd(queryDesc);
192 : :
8702 193 : 50469 : FreeQueryDesc(queryDesc);
11052 scrappy@hub.org 194 : 50469 : }
195 : :
196 : : /*
197 : : * ChoosePortalStrategy
198 : : * Select portal execution strategy given the intended statement list.
199 : : *
200 : : * The list elements can be Querys or PlannedStmts.
201 : : * That's more general than portals need, but plancache.c uses this too.
202 : : *
203 : : * See the comments in portal.h.
204 : : */
205 : : PortalStrategy
7174 tgl@sss.pgh.pa.us 206 : 516388 : ChoosePortalStrategy(List *stmts)
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 [ + + ]: 516388 : if (list_length(stmts) == 1)
218 : : {
219 : 516140 : Node *stmt = (Node *) linitial(stmts);
220 : :
221 [ + + ]: 516140 : if (IsA(stmt, Query))
222 : : {
223 : 49687 : Query *query = (Query *) stmt;
224 : :
225 [ + - ]: 49687 : if (query->canSetTag)
226 : : {
3558 227 [ + + ]: 49687 : if (query->commandType == CMD_SELECT)
228 : : {
5708 229 [ - + ]: 33679 : if (query->hasModifyingCTE)
5708 tgl@sss.pgh.pa.us 230 :UBC 0 : return PORTAL_ONE_MOD_WITH;
231 : : else
5708 tgl@sss.pgh.pa.us 232 :CBC 33679 : return PORTAL_ONE_SELECT;
233 : : }
3558 234 [ + + ]: 16008 : if (query->commandType == CMD_UTILITY)
235 : : {
7174 236 [ + + ]: 12873 : if (UtilityReturnsTuples(query->utilityStmt))
237 : 6717 : return PORTAL_UTIL_SELECT;
238 : : /* it can't be ONE_RETURNING, so give up */
239 : 6156 : return PORTAL_MULTI_QUERY;
240 : : }
241 : : }
242 : : }
243 [ + - ]: 466453 : else if (IsA(stmt, PlannedStmt))
244 : : {
245 : 466453 : PlannedStmt *pstmt = (PlannedStmt *) stmt;
246 : :
247 [ + + ]: 466453 : if (pstmt->canSetTag)
248 : : {
3558 249 [ + + ]: 466429 : if (pstmt->commandType == CMD_SELECT)
250 : : {
5708 251 [ + + ]: 186094 : if (pstmt->hasModifyingCTE)
252 : 89 : return PORTAL_ONE_MOD_WITH;
253 : : else
254 : 186005 : return PORTAL_ONE_SELECT;
255 : : }
3558 256 [ + + ]: 280335 : if (pstmt->commandType == CMD_UTILITY)
257 : : {
258 [ + + ]: 226971 : if (UtilityReturnsTuples(pstmt->utilityStmt))
259 : 29602 : return PORTAL_UTIL_SELECT;
260 : : /* it can't be ONE_RETURNING, so give up */
261 : 197369 : return PORTAL_MULTI_QUERY;
262 : : }
263 : : }
264 : : }
265 : : else
3558 tgl@sss.pgh.pa.us 266 [ # # ]:UBC 0 : 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 : : */
7364 tgl@sss.pgh.pa.us 274 :CBC 56771 : nSetTag = 0;
7174 275 [ + + + + : 59206 : foreach(lc, stmts)
+ + ]
276 : : {
277 : 56899 : Node *stmt = (Node *) lfirst(lc);
278 : :
279 [ + + ]: 56899 : if (IsA(stmt, Query))
280 : : {
281 : 3143 : Query *query = (Query *) stmt;
282 : :
283 [ + + ]: 3143 : if (query->canSetTag)
284 : : {
285 [ - + ]: 3139 : if (++nSetTag > 1)
286 : 54464 : return PORTAL_MULTI_QUERY; /* no need to look further */
3558 287 [ + - ]: 3139 : if (query->commandType == CMD_UTILITY ||
288 [ + + ]: 3139 : query->returningList == NIL)
7174 289 : 2947 : return PORTAL_MULTI_QUERY; /* no need to look further */
290 : : }
291 : : }
292 [ + - ]: 53756 : else if (IsA(stmt, PlannedStmt))
293 : : {
294 : 53756 : PlannedStmt *pstmt = (PlannedStmt *) stmt;
295 : :
296 [ + + ]: 53756 : if (pstmt->canSetTag)
297 : : {
298 [ - + ]: 53600 : if (++nSetTag > 1)
7174 tgl@sss.pgh.pa.us 299 :UBC 0 : return PORTAL_MULTI_QUERY; /* no need to look further */
3558 tgl@sss.pgh.pa.us 300 [ + - ]:CBC 53600 : if (pstmt->commandType == CMD_UTILITY ||
301 [ + + ]: 53600 : !pstmt->hasReturning)
7174 302 : 51517 : return PORTAL_MULTI_QUERY; /* no need to look further */
303 : : }
304 : : }
305 : : else
3558 tgl@sss.pgh.pa.us 306 [ # # ]:UBC 0 : elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
307 : : }
7364 tgl@sss.pgh.pa.us 308 [ + + ]:CBC 2307 : if (nSetTag == 1)
309 : 2275 : return PORTAL_ONE_RETURNING;
310 : :
311 : : /* Else, it's the general case... */
312 : 32 : return PORTAL_MULTI_QUERY;
313 : : }
314 : :
315 : : /*
316 : : * FetchPortalTargetList
317 : : * Given a portal that returns tuples, extract the query targetlist.
318 : : * Returns NIL if the portal doesn't have a determinable targetlist.
319 : : *
320 : : * Note: do not modify the result.
321 : : */
322 : : List *
7782 323 : 200733 : FetchPortalTargetList(Portal portal)
324 : : {
325 : : /* no point in looking if we determined it doesn't return tuples */
7174 326 [ + + ]: 200733 : if (portal->strategy == PORTAL_MULTI_QUERY)
327 : 20 : return NIL;
328 : : /* get the primary statement and find out what it returns */
3558 329 : 200713 : return FetchStatementTargetList((Node *) PortalGetPrimaryStmt(portal));
330 : : }
331 : :
332 : : /*
333 : : * FetchStatementTargetList
334 : : * Given a statement that returns tuples, extract the query targetlist.
335 : : * Returns NIL if the statement doesn't have a determinable targetlist.
336 : : *
337 : : * This can be applied to a Query or a PlannedStmt.
338 : : * That's more general than portals need, but plancache.c uses this too.
339 : : *
340 : : * Note: do not modify the result.
341 : : *
342 : : * XXX be careful to keep this in sync with UtilityReturnsTuples.
343 : : */
344 : : List *
7174 345 : 209089 : FetchStatementTargetList(Node *stmt)
346 : : {
347 [ - + ]: 209089 : if (stmt == NULL)
7174 tgl@sss.pgh.pa.us 348 :UBC 0 : return NIL;
7174 tgl@sss.pgh.pa.us 349 [ + + ]:CBC 209089 : if (IsA(stmt, Query))
350 : : {
351 : 8376 : Query *query = (Query *) stmt;
352 : :
3558 353 [ + + ]: 8376 : if (query->commandType == CMD_UTILITY)
354 : : {
355 : : /* transfer attention to utility statement */
7174 356 : 9 : stmt = query->utilityStmt;
357 : : }
358 : : else
359 : : {
3558 360 [ + + ]: 8367 : if (query->commandType == CMD_SELECT)
7174 361 : 8357 : return query->targetList;
362 [ + - ]: 10 : if (query->returningList)
363 : 10 : return query->returningList;
7174 tgl@sss.pgh.pa.us 364 :UBC 0 : return NIL;
365 : : }
366 : : }
7174 tgl@sss.pgh.pa.us 367 [ + + ]:CBC 200722 : if (IsA(stmt, PlannedStmt))
368 : : {
369 : 200713 : PlannedStmt *pstmt = (PlannedStmt *) stmt;
370 : :
3558 371 [ + + ]: 200713 : if (pstmt->commandType == CMD_UTILITY)
372 : : {
373 : : /* transfer attention to utility statement */
374 : 23941 : stmt = pstmt->utilityStmt;
375 : : }
376 : : else
377 : : {
378 [ + + ]: 176772 : if (pstmt->commandType == CMD_SELECT)
379 : 174829 : return pstmt->planTree->targetlist;
380 [ + - ]: 1943 : if (pstmt->hasReturning)
381 : 1943 : return pstmt->planTree->targetlist;
3558 tgl@sss.pgh.pa.us 382 :UBC 0 : return NIL;
383 : : }
384 : : }
7174 tgl@sss.pgh.pa.us 385 [ + + ]:CBC 23950 : if (IsA(stmt, FetchStmt))
386 : : {
387 : 3122 : FetchStmt *fstmt = (FetchStmt *) stmt;
388 : : Portal subportal;
389 : :
390 [ - + ]: 3122 : Assert(!fstmt->ismove);
391 : 3122 : subportal = GetPortalByName(fstmt->portalname);
10 michael@paquier.xyz 392 [ + + ]: 3122 : if (!PortalIsValid(subportal))
393 [ + - ]: 1 : ereport(ERROR,
394 : : (errcode(ERRCODE_UNDEFINED_CURSOR),
395 : : errmsg("cursor \"%s\" does not exist",
396 : : fstmt->portalname)));
7174 tgl@sss.pgh.pa.us 397 : 3121 : return FetchPortalTargetList(subportal);
398 : : }
399 [ + + ]: 20828 : if (IsA(stmt, ExecuteStmt))
400 : : {
401 : 8325 : ExecuteStmt *estmt = (ExecuteStmt *) stmt;
402 : : PreparedStatement *entry;
403 : :
404 : 8325 : entry = FetchPreparedStatement(estmt->name, true);
405 : 8325 : return FetchPreparedStatementTargetList(entry);
406 : : }
7782 407 : 12503 : return NIL;
408 : : }
409 : :
410 : : /*
411 : : * PortalStart
412 : : * Prepare a portal for execution.
413 : : *
414 : : * Caller must already have created the portal, done PortalDefineQuery(),
415 : : * and adjusted portal options if needed.
416 : : *
417 : : * If parameters are needed by the query, they must be passed in "params"
418 : : * (caller is responsible for giving them appropriate lifetime).
419 : : *
420 : : * The caller can also provide an initial set of "eflags" to be passed to
421 : : * ExecutorStart (but note these can be modified internally, and they are
422 : : * currently only honored for PORTAL_ONE_SELECT portals). Most callers
423 : : * should simply pass zero.
424 : : *
425 : : * The caller can optionally pass a snapshot to be used; pass InvalidSnapshot
426 : : * for the normal behavior of setting a new snapshot. This parameter is
427 : : * presently ignored for non-PORTAL_ONE_SELECT portals (it's only intended
428 : : * to be used for cursors).
429 : : *
430 : : * On return, portal is ready to accept PortalRun() calls, and the result
431 : : * tupdesc (if any) is known.
432 : : */
433 : : void
5320 434 : 466693 : PortalStart(Portal portal, ParamListInfo params,
435 : : int eflags, Snapshot snapshot)
436 : : {
437 : : Portal saveActivePortal;
438 : : ResourceOwner saveResourceOwner;
439 : : MemoryContext savePortalContext;
440 : : MemoryContext oldContext;
441 : : QueryDesc *queryDesc;
442 : : int myeflags;
443 : :
1445 peter@eisentraut.org 444 [ - + ]: 466693 : Assert(PortalIsValid(portal));
445 [ - + ]: 466693 : Assert(portal->status == PORTAL_DEFINED);
446 : :
447 : : /*
448 : : * Set up global portal context pointers.
449 : : */
8122 tgl@sss.pgh.pa.us 450 : 466693 : saveActivePortal = ActivePortal;
451 : 466693 : saveResourceOwner = CurrentResourceOwner;
452 : 466693 : savePortalContext = PortalContext;
8108 453 [ + + ]: 466693 : PG_TRY();
454 : : {
455 : 466693 : ActivePortal = portal;
4869 456 [ + - ]: 466693 : if (portal->resowner)
457 : 466693 : CurrentResourceOwner = portal->resowner;
3222 peter_e@gmx.net 458 : 466693 : PortalContext = portal->portalContext;
459 : :
460 : 466693 : oldContext = MemoryContextSwitchTo(PortalContext);
461 : :
462 : : /* Must remember portal param list, if any */
8108 tgl@sss.pgh.pa.us 463 : 466693 : portal->portalParams = params;
464 : :
465 : : /*
466 : : * Determine the portal execution strategy
467 : : */
7174 468 : 466693 : portal->strategy = ChoosePortalStrategy(portal->stmts);
469 : :
470 : : /*
471 : : * Fire her up according to the strategy
472 : : */
8108 473 [ + + + + : 466693 : switch (portal->strategy)
- ]
474 : : {
475 : 186005 : case PORTAL_ONE_SELECT:
476 : :
477 : : /* Must set snapshot before starting executor. */
5068 478 [ + + ]: 186005 : if (snapshot)
479 : 13840 : PushActiveSnapshot(snapshot);
480 : : else
6727 alvherre@alvh.no-ip. 481 : 172165 : PushActiveSnapshot(GetTransactionSnapshot());
482 : :
483 : : /*
484 : : * We could remember the snapshot in portal->portalSnapshot,
485 : : * but presently there seems no need to, as this code path
486 : : * cannot be used for non-atomic execution. Hence there can't
487 : : * be any commit/abort that might destroy the snapshot. Since
488 : : * we don't do that, there's also no need to force a
489 : : * non-default nesting level for the snapshot.
490 : : */
491 : :
492 : : /*
493 : : * Create QueryDesc in portal's context; for the moment, set
494 : : * the destination to DestNone.
495 : : */
3472 tgl@sss.pgh.pa.us 496 : 186005 : queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
497 : : portal->sourceText,
498 : : GetActiveSnapshot(),
499 : : InvalidSnapshot,
500 : : None_Receiver,
501 : : params,
502 : : portal->queryEnv,
503 : : 0);
504 : :
505 : : /*
506 : : * If it's a scrollable cursor, executor needs to support
507 : : * REWIND and backwards scan, as well as whatever the caller
508 : : * might've asked for.
509 : : */
7531 510 [ + + ]: 186005 : if (portal->cursorOptions & CURSOR_OPT_SCROLL)
5320 511 : 2405 : myeflags = eflags | EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
512 : : else
513 : 183600 : myeflags = eflags;
514 : :
515 : : /*
516 : : * Call ExecutorStart to prepare the plan for execution
517 : : */
508 amitlan@postgresql.o 518 : 186005 : ExecutorStart(queryDesc, myeflags);
519 : :
520 : : /*
521 : : * This tells PortalCleanup to shut down the executor
522 : : */
8108 tgl@sss.pgh.pa.us 523 : 185592 : portal->queryDesc = queryDesc;
524 : :
525 : : /*
526 : : * Remember tuple descriptor (computed by ExecutorStart)
527 : : */
528 : 185592 : portal->tupDesc = queryDesc->tupDesc;
529 : :
530 : : /*
531 : : * Reset cursor position data to "start of query"
532 : : */
533 : 185592 : portal->atStart = true;
8079 bruce@momjian.us 534 : 185592 : portal->atEnd = false; /* allow fetches */
8108 tgl@sss.pgh.pa.us 535 : 185592 : portal->portalPos = 0;
536 : :
6727 alvherre@alvh.no-ip. 537 : 185592 : PopActiveSnapshot();
8108 tgl@sss.pgh.pa.us 538 : 185592 : break;
539 : :
7366 540 : 2172 : case PORTAL_ONE_RETURNING:
541 : : case PORTAL_ONE_MOD_WITH:
542 : :
543 : : /*
544 : : * We don't start the executor until we are told to run the
545 : : * portal. We do need to set up the result tupdesc.
546 : : */
547 : : {
548 : : PlannedStmt *pstmt;
549 : :
3558 550 : 2172 : pstmt = PortalGetPrimaryStmt(portal);
7174 551 : 2172 : portal->tupDesc =
2883 andres@anarazel.de 552 : 2172 : ExecCleanTypeFromTL(pstmt->planTree->targetlist);
553 : : }
554 : :
555 : : /*
556 : : * Reset cursor position data to "start of query"
557 : : */
7366 tgl@sss.pgh.pa.us 558 : 2172 : portal->atStart = true;
559 : 2172 : portal->atEnd = false; /* allow fetches */
560 : 2172 : portal->portalPos = 0;
561 : 2172 : break;
562 : :
8108 563 : 29602 : case PORTAL_UTIL_SELECT:
564 : :
565 : : /*
566 : : * We don't set snapshot here, because PortalRunUtility will
567 : : * take care of it if needed.
568 : : */
569 : : {
3558 570 : 29602 : PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
571 : :
572 [ - + ]: 29602 : Assert(pstmt->commandType == CMD_UTILITY);
573 : 29602 : portal->tupDesc = UtilityTupleDescriptor(pstmt->utilityStmt);
574 : : }
575 : :
576 : : /*
577 : : * Reset cursor position data to "start of query"
578 : : */
8108 579 : 29584 : portal->atStart = true;
8079 bruce@momjian.us 580 : 29584 : portal->atEnd = false; /* allow fetches */
8108 tgl@sss.pgh.pa.us 581 : 29584 : portal->portalPos = 0;
582 : 29584 : break;
583 : :
584 : 248914 : case PORTAL_MULTI_QUERY:
585 : : /* Need do nothing now */
586 : 248914 : portal->tupDesc = NULL;
587 : 248914 : break;
588 : : }
589 : : }
590 : 431 : PG_CATCH();
591 : : {
592 : : /* Uncaught error while executing portal: mark it dead */
5353 593 : 431 : MarkPortalFailed(portal);
594 : :
595 : : /* Restore global vars and propagate error */
8108 596 : 431 : ActivePortal = saveActivePortal;
597 : 431 : CurrentResourceOwner = saveResourceOwner;
598 : 431 : PortalContext = savePortalContext;
599 : :
600 : 431 : PG_RE_THROW();
601 : : }
602 [ - + ]: 466262 : PG_END_TRY();
603 : :
8564 604 : 466262 : MemoryContextSwitchTo(oldContext);
605 : :
8122 606 : 466262 : ActivePortal = saveActivePortal;
607 : 466262 : CurrentResourceOwner = saveResourceOwner;
608 : 466262 : PortalContext = savePortalContext;
609 : :
610 : 466262 : portal->status = PORTAL_READY;
8564 611 : 466262 : }
612 : :
613 : : /*
614 : : * PortalSetResultFormat
615 : : * Select the format codes for a portal's output.
616 : : *
617 : : * This must be run after PortalStart for a portal that will be read by
618 : : * a DestRemote or DestRemoteExecute destination. It is not presently needed
619 : : * for other destination types.
620 : : *
621 : : * formats[] is the client format request, as per Bind message conventions.
622 : : */
623 : : void
8558 624 : 446906 : PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
625 : : {
626 : : int natts;
627 : : int i;
628 : :
629 : : /* Do nothing if portal won't return tuples */
630 [ + + ]: 446906 : if (portal->tupDesc == NULL)
631 : 248852 : return;
632 : 198054 : natts = portal->tupDesc->natts;
633 : 198054 : portal->formats = (int16 *)
3222 peter_e@gmx.net 634 : 198054 : MemoryContextAlloc(portal->portalContext,
635 : : natts * sizeof(int16));
8558 tgl@sss.pgh.pa.us 636 [ - + ]: 198054 : if (nFormats > 1)
637 : : {
638 : : /* format specified for each column */
8558 tgl@sss.pgh.pa.us 639 [ # # ]:UBC 0 : if (nFormats != natts)
8483 640 [ # # ]: 0 : ereport(ERROR,
641 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
642 : : errmsg("bind message has %d result formats but query has %d columns",
643 : : nFormats, natts)));
8558 644 : 0 : memcpy(portal->formats, formats, natts * sizeof(int16));
645 : : }
8470 bruce@momjian.us 646 [ + - ]:CBC 198054 : else if (nFormats > 0)
647 : : {
648 : : /* single format specified, use for all columns */
8558 tgl@sss.pgh.pa.us 649 : 198054 : int16 format1 = formats[0];
650 : :
651 [ + + ]: 798832 : for (i = 0; i < natts; i++)
652 : 600778 : portal->formats[i] = format1;
653 : : }
654 : : else
655 : : {
656 : : /* use default format for all columns */
8558 tgl@sss.pgh.pa.us 657 [ # # ]:UBC 0 : for (i = 0; i < natts; i++)
658 : 0 : portal->formats[i] = 0;
659 : : }
660 : : }
661 : :
662 : : /*
663 : : * PortalRun
664 : : * Run a portal's query or queries.
665 : : *
666 : : * count <= 0 is interpreted as a no-op: the destination gets started up
667 : : * and shut down, but nothing else happens. Also, count == FETCH_ALL is
668 : : * interpreted as "all rows". Note that count is ignored in multi-query
669 : : * situations, where we always run the portal to completion.
670 : : *
671 : : * isTopLevel: true if query is being executed at backend "top level"
672 : : * (that is, directly from a client command message)
673 : : *
674 : : * dest: where to send output of primary (canSetTag) query
675 : : *
676 : : * altdest: where to send output of non-primary queries
677 : : *
678 : : * qc: where to store command completion status data.
679 : : * May be NULL if caller doesn't want status data.
680 : : *
681 : : * Returns true if the portal's execution is complete, false if it was
682 : : * suspended due to exhaustion of the count parameter.
683 : : */
684 : : bool
672 tgl@sss.pgh.pa.us 685 :CBC 455324 : PortalRun(Portal portal, long count, bool isTopLevel,
686 : : DestReceiver *dest, DestReceiver *altdest,
687 : : QueryCompletion *qc)
688 : : {
689 : : bool result;
690 : : uint64 nprocessed;
691 : : ResourceOwner saveTopTransactionResourceOwner;
692 : : MemoryContext saveTopTransactionContext;
693 : : Portal saveActivePortal;
694 : : ResourceOwner saveResourceOwner;
695 : : MemoryContext savePortalContext;
696 : : MemoryContext saveMemoryContext;
697 : :
1445 peter@eisentraut.org 698 [ - + ]: 455324 : Assert(PortalIsValid(portal));
699 : :
700 : : TRACE_POSTGRESQL_QUERY_EXECUTE_START();
701 : :
702 : : /* Initialize empty completion data */
2415 alvherre@alvh.no-ip. 703 [ + - ]: 455324 : if (qc)
704 : 455324 : InitializeQueryCompletion(qc);
705 : :
8243 bruce@momjian.us 706 [ - + - - ]: 455324 : if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
707 : : {
7153 tgl@sss.pgh.pa.us 708 [ # # ]:UBC 0 : elog(DEBUG3, "PortalRun");
709 : : /* PORTAL_MULTI_QUERY logs its own stats per query */
8243 bruce@momjian.us 710 : 0 : ResetUsage();
711 : : }
712 : :
713 : : /*
714 : : * Check for improper portal use, and mark portal active.
715 : : */
4056 tgl@sss.pgh.pa.us 716 :CBC 455324 : MarkPortalActive(portal);
717 : :
718 : : /*
719 : : * Set up global portal context pointers.
720 : : *
721 : : * We have to play a special game here to support utility commands like
722 : : * VACUUM and CLUSTER, which internally start and commit transactions.
723 : : * When we are called to execute such a command, CurrentResourceOwner will
724 : : * be pointing to the TopTransactionResourceOwner --- which will be
725 : : * destroyed and replaced in the course of the internal commit and
726 : : * restart. So we need to be prepared to restore it as pointing to the
727 : : * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
728 : : * internally starting whole new transactions is not good.)
729 : : * CurrentMemoryContext has a similar problem, but the other pointers we
730 : : * save here will be NULL or pointing to longer-lived objects.
731 : : */
8043 732 : 455324 : saveTopTransactionResourceOwner = TopTransactionResourceOwner;
733 : 455324 : saveTopTransactionContext = TopTransactionContext;
8240 734 : 455324 : saveActivePortal = ActivePortal;
8122 735 : 455324 : saveResourceOwner = CurrentResourceOwner;
8564 736 : 455324 : savePortalContext = PortalContext;
8043 737 : 455324 : saveMemoryContext = CurrentMemoryContext;
8108 738 [ + + ]: 455324 : PG_TRY();
739 : : {
740 : 455324 : ActivePortal = portal;
4869 741 [ + - ]: 455324 : if (portal->resowner)
742 : 455324 : CurrentResourceOwner = portal->resowner;
3222 peter_e@gmx.net 743 : 455324 : PortalContext = portal->portalContext;
744 : :
8043 tgl@sss.pgh.pa.us 745 : 455324 : MemoryContextSwitchTo(PortalContext);
746 : :
8108 747 [ + + - ]: 455324 : switch (portal->strategy)
748 : : {
749 : 206410 : case PORTAL_ONE_SELECT:
750 : : case PORTAL_ONE_RETURNING:
751 : : case PORTAL_ONE_MOD_WITH:
752 : : case PORTAL_UTIL_SELECT:
753 : :
754 : : /*
755 : : * If we have not yet run the command, do so, storing its
756 : : * results in the portal's tuplestore. But we don't do that
757 : : * for the PORTAL_ONE_SELECT case.
758 : : */
6082 bruce@momjian.us 759 [ + + + - ]: 206410 : if (portal->strategy != PORTAL_ONE_SELECT && !portal->holdStore)
7153 tgl@sss.pgh.pa.us 760 : 26316 : FillPortalStore(portal, isTopLevel);
761 : :
762 : : /*
763 : : * Now fetch desired portion of results.
764 : : */
6082 bruce@momjian.us 765 : 206067 : nprocessed = PortalRunSelect(portal, true, count, dest);
766 : :
767 : : /*
768 : : * If the portal result contains a command tag and the caller
769 : : * gave us a pointer to store it, copy it and update the
770 : : * rowcount.
771 : : */
2415 alvherre@alvh.no-ip. 772 [ + - + - ]: 200986 : if (qc && portal->qc.commandTag != CMDTAG_UNKNOWN)
773 : : {
774 : 200986 : CopyQueryCompletion(qc, &portal->qc);
775 : 200986 : qc->nprocessed = nprocessed;
776 : : }
777 : :
778 : : /* Mark portal not active */
8108 tgl@sss.pgh.pa.us 779 : 200986 : portal->status = PORTAL_READY;
780 : :
781 : : /*
782 : : * Since it's a forward fetch, say DONE iff atEnd is now true.
783 : : */
784 : 200986 : result = portal->atEnd;
785 : 200986 : break;
786 : :
787 : 248914 : case PORTAL_MULTI_QUERY:
3718 788 : 248914 : PortalRunMulti(portal, isTopLevel, false,
789 : : dest, altdest, qc);
790 : :
791 : : /* Prevent portal's commands from being re-executed */
5702 792 : 234269 : MarkPortalDone(portal);
793 : :
794 : : /* Always complete at end of RunMulti */
8108 795 : 234269 : result = true;
796 : 234269 : break;
797 : :
8108 tgl@sss.pgh.pa.us 798 :UBC 0 : default:
799 [ # # ]: 0 : elog(ERROR, "unrecognized portal strategy: %d",
800 : : (int) portal->strategy);
801 : : result = false; /* keep compiler quiet */
802 : : break;
803 : : }
804 : : }
8108 tgl@sss.pgh.pa.us 805 :CBC 20064 : PG_CATCH();
806 : : {
807 : : /* Uncaught error while executing portal: mark it dead */
5353 808 : 20064 : MarkPortalFailed(portal);
809 : :
810 : : /* Restore global vars and propagate error */
8043 811 [ + + ]: 20064 : if (saveMemoryContext == saveTopTransactionContext)
812 : 19799 : MemoryContextSwitchTo(TopTransactionContext);
813 : : else
814 : 265 : MemoryContextSwitchTo(saveMemoryContext);
8108 815 : 20064 : ActivePortal = saveActivePortal;
8043 816 [ + + ]: 20064 : if (saveResourceOwner == saveTopTransactionResourceOwner)
817 : 19852 : CurrentResourceOwner = TopTransactionResourceOwner;
818 : : else
819 : 212 : CurrentResourceOwner = saveResourceOwner;
8108 820 : 20064 : PortalContext = savePortalContext;
821 : :
822 : 20064 : PG_RE_THROW();
823 : : }
824 [ - + ]: 435255 : PG_END_TRY();
825 : :
8043 826 [ + + ]: 435255 : if (saveMemoryContext == saveTopTransactionContext)
827 : 410897 : MemoryContextSwitchTo(TopTransactionContext);
828 : : else
829 : 24358 : MemoryContextSwitchTo(saveMemoryContext);
8240 830 : 435255 : ActivePortal = saveActivePortal;
8043 831 [ + + ]: 435255 : if (saveResourceOwner == saveTopTransactionResourceOwner)
832 : 422918 : CurrentResourceOwner = TopTransactionResourceOwner;
833 : : else
834 : 12337 : CurrentResourceOwner = saveResourceOwner;
8564 835 : 435255 : PortalContext = savePortalContext;
836 : :
8256 bruce@momjian.us 837 [ - + - - ]: 435255 : if (log_executor_stats && portal->strategy != PORTAL_MULTI_QUERY)
8256 bruce@momjian.us 838 :UBC 0 : ShowUsage("EXECUTOR STATISTICS");
839 : :
840 : : TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
841 : :
8564 tgl@sss.pgh.pa.us 842 :CBC 435255 : return result;
843 : : }
844 : :
845 : : /*
846 : : * PortalRunSelect
847 : : * Execute a portal's query in PORTAL_ONE_SELECT mode, and also
848 : : * when fetching from a completed holdStore in PORTAL_ONE_RETURNING,
849 : : * PORTAL_ONE_MOD_WITH, and PORTAL_UTIL_SELECT cases.
850 : : *
851 : : * This handles simple N-rows-forward-or-backward cases. For more complex
852 : : * nonsequential access to a portal, see PortalRunFetch.
853 : : *
854 : : * count <= 0 is interpreted as a no-op: the destination gets started up
855 : : * and shut down, but nothing else happens. Also, count == FETCH_ALL is
856 : : * interpreted as "all rows". (cf FetchStmt.howMany)
857 : : *
858 : : * Caller must already have validated the Portal and done appropriate
859 : : * setup (cf. PortalRun).
860 : : *
861 : : * Returns number of rows processed (suitable for use in result tag)
862 : : */
863 : : static uint64
864 : 240238 : PortalRunSelect(Portal portal,
865 : : bool forward,
866 : : long count,
867 : : DestReceiver *dest)
868 : : {
869 : : QueryDesc *queryDesc;
870 : : ScanDirection direction;
871 : : uint64 nprocessed;
872 : :
873 : : /*
874 : : * NB: queryDesc will be NULL if we are fetching from a held cursor or a
875 : : * completed utility query; can't use it in that path.
876 : : */
3222 peter_e@gmx.net 877 : 240238 : queryDesc = portal->queryDesc;
878 : :
879 : : /* Caller messed up if we have neither a ready query nor held data. */
8564 tgl@sss.pgh.pa.us 880 [ + + - + ]: 240238 : Assert(queryDesc || portal->holdStore);
881 : :
882 : : /*
883 : : * Force the queryDesc destination to the right thing. This supports
884 : : * MOVE, for example, which will pass in dest = DestNone. This is okay to
885 : : * change as long as we do it on every fetch. (The Executor must not
886 : : * assume that dest never changes.)
887 : : */
888 [ + + ]: 240238 : if (queryDesc)
889 : 192801 : queryDesc->dest = dest;
890 : :
891 : : /*
892 : : * Determine which direction to go in, and check to see if we're already
893 : : * at the end of the available tuples in that direction. If so, set the
894 : : * direction to NoMovement to avoid trying to fetch any tuples. (This
895 : : * check exists because not all plan node types are robust about being
896 : : * called again if they've already returned NULL once.) Then call the
897 : : * executor (we must not skip this, because the destination needs to see a
898 : : * setup and shutdown even if no tuples are available). Finally, update
899 : : * the portal position state depending on the number of tuples that were
900 : : * retrieved.
901 : : */
902 [ + + ]: 240238 : if (forward)
903 : : {
904 [ + + + + ]: 239814 : if (portal->atEnd || count <= 0)
905 : : {
906 : 2496 : direction = NoMovementScanDirection;
3866 907 : 2496 : count = 0; /* don't pass negative count to executor */
908 : : }
909 : : else
8564 910 : 237318 : direction = ForwardScanDirection;
911 : :
912 : : /* In the executor, zero count processes all rows */
913 [ + + ]: 239814 : if (count == FETCH_ALL)
914 : 206286 : count = 0;
915 : :
916 [ + + ]: 239814 : if (portal->holdStore)
3866 917 : 47425 : nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
918 : : else
919 : : {
6727 alvherre@alvh.no-ip. 920 : 192389 : PushActiveSnapshot(queryDesc->snapshot);
672 tgl@sss.pgh.pa.us 921 : 192389 : ExecutorRun(queryDesc, direction, (uint64) count);
8564 922 : 187280 : nprocessed = queryDesc->estate->es_processed;
6727 alvherre@alvh.no-ip. 923 : 187280 : PopActiveSnapshot();
924 : : }
925 : :
7538 neilc@samurai.com 926 [ + + ]: 234705 : if (!ScanDirectionIsNoMovement(direction))
927 : : {
8564 tgl@sss.pgh.pa.us 928 [ + + ]: 232209 : if (nprocessed > 0)
3400 929 : 194248 : portal->atStart = false; /* OK to go backward now */
3866 930 [ + + + + ]: 232209 : if (count == 0 || nprocessed < (uint64) count)
8470 bruce@momjian.us 931 : 210453 : portal->atEnd = true; /* we retrieved 'em all */
8564 tgl@sss.pgh.pa.us 932 : 232209 : portal->portalPos += nprocessed;
933 : : }
934 : : }
935 : : else
936 : : {
937 [ + + ]: 424 : if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
8483 938 [ + - ]: 16 : ereport(ERROR,
939 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
940 : : errmsg("cursor can only scan forward"),
941 : : errhint("Declare it with SCROLL option to enable backward scan.")));
942 : :
8564 943 [ + + - + ]: 408 : if (portal->atStart || count <= 0)
944 : : {
945 : 48 : direction = NoMovementScanDirection;
3866 946 : 48 : count = 0; /* don't pass negative count to executor */
947 : : }
948 : : else
8564 949 : 360 : direction = BackwardScanDirection;
950 : :
951 : : /* In the executor, zero count processes all rows */
952 [ + + ]: 408 : if (count == FETCH_ALL)
953 : 42 : count = 0;
954 : :
955 [ + + ]: 408 : if (portal->holdStore)
3866 956 : 8 : nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
957 : : else
958 : : {
6727 alvherre@alvh.no-ip. 959 : 400 : PushActiveSnapshot(queryDesc->snapshot);
672 tgl@sss.pgh.pa.us 960 : 400 : ExecutorRun(queryDesc, direction, (uint64) count);
8564 961 : 400 : nprocessed = queryDesc->estate->es_processed;
6727 alvherre@alvh.no-ip. 962 : 400 : PopActiveSnapshot();
963 : : }
964 : :
7538 neilc@samurai.com 965 [ + + ]: 408 : if (!ScanDirectionIsNoMovement(direction))
966 : : {
8564 tgl@sss.pgh.pa.us 967 [ + + + + ]: 360 : if (nprocessed > 0 && portal->atEnd)
968 : : {
8470 bruce@momjian.us 969 : 110 : portal->atEnd = false; /* OK to go forward now */
970 : 110 : portal->portalPos++; /* adjust for endpoint case */
971 : : }
3866 tgl@sss.pgh.pa.us 972 [ + + + + ]: 360 : if (count == 0 || nprocessed < (uint64) count)
973 : : {
8470 bruce@momjian.us 974 : 126 : portal->atStart = true; /* we retrieved 'em all */
8564 tgl@sss.pgh.pa.us 975 : 126 : portal->portalPos = 0;
976 : : }
977 : : else
978 : : {
979 : 234 : portal->portalPos -= nprocessed;
980 : : }
981 : : }
982 : : }
983 : :
984 : 235113 : return nprocessed;
985 : : }
986 : :
987 : : /*
988 : : * FillPortalStore
989 : : * Run the query and load result tuples into the portal's tuple store.
990 : : *
991 : : * This is used for PORTAL_ONE_RETURNING, PORTAL_ONE_MOD_WITH, and
992 : : * PORTAL_UTIL_SELECT cases only.
993 : : */
994 : : static void
7153 995 : 31756 : FillPortalStore(Portal portal, bool isTopLevel)
996 : : {
997 : : DestReceiver *treceiver;
998 : : QueryCompletion qc;
999 : :
2415 alvherre@alvh.no-ip. 1000 : 31756 : InitializeQueryCompletion(&qc);
7366 tgl@sss.pgh.pa.us 1001 : 31756 : PortalCreateHoldStore(portal);
6525 1002 : 31756 : treceiver = CreateDestReceiver(DestTuplestore);
1003 : 31756 : SetTuplestoreDestReceiverParams(treceiver,
1004 : : portal->holdStore,
1005 : : portal->holdContext,
1006 : : false,
1007 : : portal->tupDesc,
1008 : : gettext_noop("query result type does not match portal result type"));
1009 : :
7366 1010 [ + + - ]: 31756 : switch (portal->strategy)
1011 : : {
1012 : 2172 : case PORTAL_ONE_RETURNING:
1013 : : case PORTAL_ONE_MOD_WITH:
1014 : :
1015 : : /*
1016 : : * Run the portal to completion just as for the default
1017 : : * PORTAL_MULTI_QUERY case, but send the primary query's output to
1018 : : * the tuplestore. Auxiliary query outputs are discarded. Set the
1019 : : * portal's holdSnapshot to the snapshot used (or a copy of it).
1020 : : */
3718 1021 : 2172 : PortalRunMulti(portal, isTopLevel, true,
1022 : : treceiver, None_Receiver, &qc);
7366 1023 : 2033 : break;
1024 : :
1025 : 29584 : case PORTAL_UTIL_SELECT:
3472 1026 : 29584 : PortalRunUtility(portal, linitial_node(PlannedStmt, portal->stmts),
1027 : : isTopLevel, true, treceiver, &qc);
7366 1028 : 29376 : break;
1029 : :
7366 tgl@sss.pgh.pa.us 1030 :UBC 0 : default:
1031 [ # # ]: 0 : elog(ERROR, "unsupported portal strategy: %d",
1032 : : (int) portal->strategy);
1033 : : break;
1034 : : }
1035 : :
1036 : : /* Override portal completion data with actual command results */
2415 alvherre@alvh.no-ip. 1037 [ + + ]:CBC 31409 : if (qc.commandTag != CMDTAG_UNKNOWN)
1038 : 13475 : CopyQueryCompletion(&portal->qc, &qc);
1039 : :
3322 peter_e@gmx.net 1040 : 31409 : treceiver->rDestroy(treceiver);
7366 tgl@sss.pgh.pa.us 1041 : 31409 : }
1042 : :
1043 : : /*
1044 : : * RunFromStore
1045 : : * Fetch tuples from the portal's tuple store.
1046 : : *
1047 : : * Calling conventions are similar to ExecutorRun, except that we
1048 : : * do not depend on having a queryDesc or estate. Therefore we return the
1049 : : * number of tuples processed as the result, not in estate->es_processed.
1050 : : *
1051 : : * One difference from ExecutorRun is that the destination receiver functions
1052 : : * are run in the caller's memory context (since we have no estate). Watch
1053 : : * out for memory leaks.
1054 : : */
1055 : : static uint64
3866 1056 : 47433 : RunFromStore(Portal portal, ScanDirection direction, uint64 count,
1057 : : DestReceiver *dest)
1058 : : {
1059 : 47433 : uint64 current_tuple_count = 0;
1060 : : TupleTableSlot *slot;
1061 : :
2888 andres@anarazel.de 1062 : 47433 : slot = MakeSingleTupleTableSlot(portal->tupDesc, &TTSOpsMinimalTuple);
1063 : :
3322 peter_e@gmx.net 1064 : 47433 : dest->rStartup(dest, CMD_SELECT, portal->tupDesc);
1065 : :
7538 neilc@samurai.com 1066 [ + + ]: 47433 : if (ScanDirectionIsNoMovement(direction))
1067 : : {
1068 : : /* do nothing except start/stop the destination */
1069 : : }
1070 : : else
1071 : : {
1072 : 45675 : bool forward = ScanDirectionIsForward(direction);
1073 : :
1074 : : for (;;)
8564 tgl@sss.pgh.pa.us 1075 : 267912 : {
1076 : : MemoryContext oldcontext;
1077 : : bool ok;
1078 : :
1079 : 313587 : oldcontext = MemoryContextSwitchTo(portal->holdContext);
1080 : :
6408 1081 : 313587 : ok = tuplestore_gettupleslot(portal->holdStore, forward, false,
1082 : : slot);
1083 : :
8564 1084 : 313587 : MemoryContextSwitchTo(oldcontext);
1085 : :
7412 1086 [ + + ]: 313587 : if (!ok)
8564 1087 : 31441 : break;
1088 : :
1089 : : /*
1090 : : * If we are not able to send the tuple, we assume the destination
1091 : : * has closed and no more tuples can be sent. If that's the case,
1092 : : * end the loop.
1093 : : */
3322 peter_e@gmx.net 1094 [ - + ]: 282146 : if (!dest->receiveSlot(slot, dest))
3780 rhaas@postgresql.org 1095 :UBC 0 : break;
1096 : :
7880 tgl@sss.pgh.pa.us 1097 :CBC 282146 : ExecClearTuple(slot);
1098 : :
1099 : : /*
1100 : : * check our tuple count.. if we've processed the proper number
1101 : : * then quit, else loop again and process more tuples. Zero count
1102 : : * means no limit.
1103 : : */
8564 1104 : 282146 : current_tuple_count++;
1105 [ + + + + ]: 282146 : if (count && count == current_tuple_count)
1106 : 14234 : break;
1107 : : }
1108 : : }
1109 : :
3322 peter_e@gmx.net 1110 : 47433 : dest->rShutdown(dest);
1111 : :
7880 tgl@sss.pgh.pa.us 1112 : 47433 : ExecDropSingleTupleTableSlot(slot);
1113 : :
3866 1114 : 47433 : return current_tuple_count;
1115 : : }
1116 : :
1117 : : /*
1118 : : * PortalRunUtility
1119 : : * Execute a utility statement inside a portal.
1120 : : */
1121 : : static void
3558 1122 : 226953 : PortalRunUtility(Portal portal, PlannedStmt *pstmt,
1123 : : bool isTopLevel, bool setHoldSnapshot,
1124 : : DestReceiver *dest, QueryCompletion *qc)
1125 : : {
1126 : : /*
1127 : : * Set snapshot if utility stmt needs one.
1128 : : */
1970 1129 [ + + ]: 226953 : if (PlannedStmtRequiresSnapshot(pstmt))
1130 : : {
1131 : 177271 : Snapshot snapshot = GetTransactionSnapshot();
1132 : :
1133 : : /* If told to, register the snapshot we're using and save in portal */
3718 1134 [ + + ]: 177271 : if (setHoldSnapshot)
1135 : : {
1136 : 25571 : snapshot = RegisterSnapshot(snapshot);
1137 : 25571 : portal->holdSnapshot = snapshot;
1138 : : }
1139 : :
1140 : : /*
1141 : : * In any case, make the snapshot active and remember it in portal.
1142 : : * Because the portal now references the snapshot, we must tell
1143 : : * snapmgr.c that the snapshot belongs to the portal's transaction
1144 : : * level, else we risk portalSnapshot becoming a dangling pointer.
1145 : : */
1837 1146 : 177271 : PushActiveSnapshotWithLevel(snapshot, portal->createLevel);
1147 : : /* PushActiveSnapshotWithLevel might have copied the snapshot */
1970 1148 : 177271 : portal->portalSnapshot = GetActiveSnapshot();
1149 : : }
1150 : : else
1151 : 49682 : portal->portalSnapshot = NULL;
1152 : :
3558 1153 : 226953 : ProcessUtility(pstmt,
1154 : : portal->sourceText,
1942 1155 : 226953 : (portal->cplan != NULL), /* protect tree if in plancache */
3400 1156 : 226953 : isTopLevel ? PROCESS_UTILITY_TOPLEVEL : PROCESS_UTILITY_QUERY,
1157 : : portal->portalParams,
1158 : : portal->queryEnv,
1159 : : dest,
1160 : : qc);
1161 : :
1162 : : /* Some utility statements may change context on us */
3222 peter_e@gmx.net 1163 : 215625 : MemoryContextSwitchTo(portal->portalContext);
1164 : :
1165 : : /*
1166 : : * Some utility commands (e.g., VACUUM, WAIT FOR) pop the ActiveSnapshot
1167 : : * stack from under us, so don't complain if it's now empty. Otherwise,
1168 : : * our snapshot should be the top one; pop it. Note that this could be a
1169 : : * different snapshot from the one we made above; see
1170 : : * EnsurePortalSnapshotExists.
1171 : : */
1970 tgl@sss.pgh.pa.us 1172 [ + + + - ]: 215625 : if (portal->portalSnapshot != NULL && ActiveSnapshotSet())
1173 : : {
1174 [ - + ]: 159983 : Assert(portal->portalSnapshot == GetActiveSnapshot());
6727 alvherre@alvh.no-ip. 1175 : 159983 : PopActiveSnapshot();
1176 : : }
1970 tgl@sss.pgh.pa.us 1177 : 215625 : portal->portalSnapshot = NULL;
8564 1178 : 215625 : }
1179 : :
1180 : : /*
1181 : : * PortalRunMulti
1182 : : * Execute a portal's queries in the general case (multi queries
1183 : : * or non-SELECT-like queries)
1184 : : */
1185 : : static void
3718 1186 : 251086 : PortalRunMulti(Portal portal,
1187 : : bool isTopLevel, bool setHoldSnapshot,
1188 : : DestReceiver *dest, DestReceiver *altdest,
1189 : : QueryCompletion *qc)
1190 : : {
5705 1191 : 251086 : bool active_snapshot_set = false;
1192 : : ListCell *stmtlist_item;
1193 : :
1194 : : /*
1195 : : * If the destination is DestRemoteExecute, change to DestNone. The
1196 : : * reason is that the client won't be expecting any tuples, and indeed has
1197 : : * no way to know what they are, since there is no provision for Describe
1198 : : * to send a RowDescription message when this portal execution strategy is
1199 : : * in effect. This presently will only affect SELECT commands added to
1200 : : * non-SELECT queries by rewrite rules: such commands will be executed,
1201 : : * but the results will be discarded unless you use "simple Query"
1202 : : * protocol.
1203 : : */
7648 alvherre@alvh.no-ip. 1204 [ + + ]: 251086 : if (dest->mydest == DestRemoteExecute)
8560 tgl@sss.pgh.pa.us 1205 : 5159 : dest = None_Receiver;
7648 alvherre@alvh.no-ip. 1206 [ + + ]: 251086 : if (altdest->mydest == DestRemoteExecute)
8560 tgl@sss.pgh.pa.us 1207 : 5159 : altdest = None_Receiver;
1208 : :
1209 : : /*
1210 : : * Loop to handle the individual queries generated from a single parsetree
1211 : : * by analysis and rewrite.
1212 : : */
7174 1213 [ + - + + : 487804 : foreach(stmtlist_item, portal->stmts)
+ + ]
1214 : : {
3472 1215 : 251502 : PlannedStmt *pstmt = lfirst_node(PlannedStmt, stmtlist_item);
1216 : :
1217 : : /*
1218 : : * If we got a cancel signal in prior command, quit
1219 : : */
8564 1220 [ - + ]: 251502 : CHECK_FOR_INTERRUPTS();
1221 : :
3558 1222 [ + + ]: 251502 : if (pstmt->utilityStmt == NULL)
1223 : : {
1224 : : /*
1225 : : * process a plannable query.
1226 : : */
1227 : : TRACE_POSTGRESQL_QUERY_EXECUTE_START();
1228 : :
8564 1229 [ - + ]: 54133 : if (log_executor_stats)
8564 tgl@sss.pgh.pa.us 1230 :UBC 0 : ResetUsage();
1231 : :
1232 : : /*
1233 : : * Must always have a snapshot for plannable queries. First time
1234 : : * through, take a new snapshot; for subsequent queries in the
1235 : : * same portal, just update the snapshot's copy of the command
1236 : : * counter.
1237 : : */
5705 tgl@sss.pgh.pa.us 1238 [ + + ]:CBC 54133 : if (!active_snapshot_set)
1239 : : {
3718 1240 : 53717 : Snapshot snapshot = GetTransactionSnapshot();
1241 : :
1242 : : /* If told to, register the snapshot and save in portal */
1243 [ + + ]: 53717 : if (setHoldSnapshot)
1244 : : {
1245 : 2172 : snapshot = RegisterSnapshot(snapshot);
1246 : 2172 : portal->holdSnapshot = snapshot;
1247 : : }
1248 : :
1249 : : /*
1250 : : * We can't have the holdSnapshot also be the active one,
1251 : : * because UpdateActiveSnapshotCommandId would complain. So
1252 : : * force an extra snapshot copy. Plain PushActiveSnapshot
1253 : : * would have copied the transaction snapshot anyway, so this
1254 : : * only adds a copy step when setHoldSnapshot is true. (It's
1255 : : * okay for the command ID of the active snapshot to diverge
1256 : : * from what holdSnapshot has.)
1257 : : */
1258 : 53717 : PushCopiedSnapshot(snapshot);
1259 : :
1260 : : /*
1261 : : * As for PORTAL_ONE_SELECT portals, it does not seem
1262 : : * necessary to maintain portal->portalSnapshot here.
1263 : : */
1264 : :
5705 1265 : 53717 : active_snapshot_set = true;
1266 : : }
1267 : : else
1268 : 416 : UpdateActiveSnapshotCommandId();
1269 : :
7174 1270 [ + + ]: 54133 : if (pstmt->canSetTag)
1271 : : {
1272 : : /* statement can set tag string */
1273 : 53689 : ProcessQuery(pstmt,
1274 : : portal->sourceText,
1275 : : portal->portalParams,
1276 : : portal->queryEnv,
1277 : : dest, qc);
1278 : : }
1279 : : else
1280 : : {
1281 : : /* stmt added by rewrite cannot set tag */
1282 : 444 : ProcessQuery(pstmt,
1283 : : portal->sourceText,
1284 : : portal->portalParams,
1285 : : portal->queryEnv,
1286 : : altdest, NULL);
1287 : : }
1288 : :
8564 1289 [ - + ]: 50469 : if (log_executor_stats)
8564 tgl@sss.pgh.pa.us 1290 :UBC 0 : ShowUsage("EXECUTOR STATISTICS");
1291 : :
1292 : : TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
1293 : : }
1294 : : else
1295 : : {
1296 : : /*
1297 : : * process utility functions (create, destroy, etc..)
1298 : : *
1299 : : * We must not set a snapshot here for utility commands (if one is
1300 : : * needed, PortalRunUtility will do it). If a utility command is
1301 : : * alone in a portal then everything's fine. The only case where
1302 : : * a utility command can be part of a longer list is that rules
1303 : : * are allowed to include NotifyStmt. NotifyStmt doesn't care
1304 : : * whether it has a snapshot or not, so we just leave the current
1305 : : * snapshot alone if we have one.
1306 : : */
3558 tgl@sss.pgh.pa.us 1307 [ + - ]:CBC 197369 : if (pstmt->canSetTag)
1308 : : {
5705 1309 [ - + ]: 197369 : Assert(!active_snapshot_set);
1310 : : /* statement can set tag string */
3558 1311 : 197369 : PortalRunUtility(portal, pstmt, isTopLevel, false,
1312 : : dest, qc);
1313 : : }
1314 : : else
1315 : : {
3558 tgl@sss.pgh.pa.us 1316 [ # # ]:UBC 0 : Assert(IsA(pstmt->utilityStmt, NotifyStmt));
1317 : : /* stmt added by rewrite cannot set tag */
1318 : 0 : PortalRunUtility(portal, pstmt, isTopLevel, false,
1319 : : altdest, NULL);
1320 : : }
1321 : : }
1322 : :
1323 : : /*
1324 : : * Clear subsidiary contexts to recover temporary memory.
1325 : : */
3222 peter_e@gmx.net 1326 [ - + ]:CBC 236718 : Assert(portal->portalContext == CurrentMemoryContext);
1327 : :
1328 : 236718 : MemoryContextDeleteChildren(portal->portalContext);
1329 : :
1330 : : /*
1331 : : * Avoid crashing if portal->stmts has been reset. This can only
1332 : : * occur if a CALL or DO utility statement executed an internal
1333 : : * COMMIT/ROLLBACK (cf PortalReleaseCachedPlan). The CALL or DO must
1334 : : * have been the only statement in the portal, so there's nothing left
1335 : : * for us to do; but we don't want to dereference a now-dangling list
1336 : : * pointer.
1337 : : */
2077 tgl@sss.pgh.pa.us 1338 [ - + ]: 236718 : if (portal->stmts == NIL)
2077 tgl@sss.pgh.pa.us 1339 :UBC 0 : break;
1340 : :
1341 : : /*
1342 : : * Increment command counter between queries, but not after the last
1343 : : * one.
1344 : : */
2077 tgl@sss.pgh.pa.us 1345 [ + + ]:CBC 236718 : if (lnext(portal->stmts, stmtlist_item) != NULL)
1346 : 416 : CommandCounterIncrement();
1347 : : }
1348 : :
1349 : : /* Pop the snapshot if we pushed one. */
5705 1350 [ + + ]: 236302 : if (active_snapshot_set)
1351 : 50053 : PopActiveSnapshot();
1352 : :
1353 : : /*
1354 : : * If a command tag was requested and we did not fill in a run-time-
1355 : : * determined tag above, copy the parse-time tag from the Portal. (There
1356 : : * might not be any tag there either, in edge cases such as empty prepared
1357 : : * statements. That's OK.)
1358 : : */
452 alvherre@kurilemu.de 1359 [ + - ]: 236302 : if (qc &&
1360 [ + + ]: 236302 : qc->commandTag == CMDTAG_UNKNOWN &&
1361 [ + - ]: 178778 : portal->qc.commandTag != CMDTAG_UNKNOWN)
1362 : 178778 : CopyQueryCompletion(qc, &portal->qc);
8564 tgl@sss.pgh.pa.us 1363 : 236302 : }
1364 : :
1365 : : /*
1366 : : * PortalRunFetch
1367 : : * Variant form of PortalRun that supports SQL FETCH directions.
1368 : : *
1369 : : * Note: we presently assume that no callers of this want isTopLevel = true.
1370 : : *
1371 : : * count <= 0 is interpreted as a no-op: the destination gets started up
1372 : : * and shut down, but nothing else happens. Also, count == FETCH_ALL is
1373 : : * interpreted as "all rows". (cf FetchStmt.howMany)
1374 : : *
1375 : : * Returns number of rows processed (suitable for use in result tag)
1376 : : */
1377 : : uint64
1378 : 34124 : PortalRunFetch(Portal portal,
1379 : : FetchDirection fdirection,
1380 : : long count,
1381 : : DestReceiver *dest)
1382 : : {
1383 : : uint64 result;
1384 : : Portal saveActivePortal;
1385 : : ResourceOwner saveResourceOwner;
1386 : : MemoryContext savePortalContext;
1387 : : MemoryContext oldContext;
1388 : :
1445 peter@eisentraut.org 1389 [ - + ]: 34124 : Assert(PortalIsValid(portal));
1390 : :
1391 : : /*
1392 : : * Check for improper portal use, and mark portal active.
1393 : : */
4056 tgl@sss.pgh.pa.us 1394 : 34124 : MarkPortalActive(portal);
1395 : :
1396 : : /*
1397 : : * Set up global portal context pointers.
1398 : : */
8240 1399 : 34112 : saveActivePortal = ActivePortal;
8122 1400 : 34112 : saveResourceOwner = CurrentResourceOwner;
8564 1401 : 34112 : savePortalContext = PortalContext;
8108 1402 [ + + ]: 34112 : PG_TRY();
1403 : : {
1404 : 34112 : ActivePortal = portal;
4869 1405 [ + + ]: 34112 : if (portal->resowner)
1406 : 34005 : CurrentResourceOwner = portal->resowner;
3222 peter_e@gmx.net 1407 : 34112 : PortalContext = portal->portalContext;
1408 : :
8108 tgl@sss.pgh.pa.us 1409 : 34112 : oldContext = MemoryContextSwitchTo(PortalContext);
1410 : :
1411 [ + + - ]: 34112 : switch (portal->strategy)
1412 : : {
1413 : 12751 : case PORTAL_ONE_SELECT:
1414 : 12751 : result = DoPortalRunFetch(portal, fdirection, count, dest);
1415 : 12703 : break;
1416 : :
7366 1417 : 21361 : case PORTAL_ONE_RETURNING:
1418 : : case PORTAL_ONE_MOD_WITH:
1419 : : case PORTAL_UTIL_SELECT:
1420 : :
1421 : : /*
1422 : : * If we have not yet run the command, do so, storing its
1423 : : * results in the portal's tuplestore.
1424 : : */
1425 [ + + ]: 21361 : if (!portal->holdStore)
6906 bruce@momjian.us 1426 : 5440 : FillPortalStore(portal, false /* isTopLevel */ );
1427 : :
1428 : : /*
1429 : : * Now fetch desired portion of results.
1430 : : */
7914 tgl@sss.pgh.pa.us 1431 : 21357 : result = DoPortalRunFetch(portal, fdirection, count, dest);
1432 : 21357 : break;
1433 : :
8108 tgl@sss.pgh.pa.us 1434 :UBC 0 : default:
1435 [ # # ]: 0 : elog(ERROR, "unsupported portal strategy");
1436 : : result = 0; /* keep compiler quiet */
1437 : : break;
1438 : : }
1439 : : }
8108 tgl@sss.pgh.pa.us 1440 :CBC 52 : PG_CATCH();
1441 : : {
1442 : : /* Uncaught error while executing portal: mark it dead */
5353 1443 : 52 : MarkPortalFailed(portal);
1444 : :
1445 : : /* Restore global vars and propagate error */
8108 1446 : 52 : ActivePortal = saveActivePortal;
1447 : 52 : CurrentResourceOwner = saveResourceOwner;
1448 : 52 : PortalContext = savePortalContext;
1449 : :
1450 : 52 : PG_RE_THROW();
1451 : : }
1452 [ - + ]: 34060 : PG_END_TRY();
1453 : :
8564 1454 : 34060 : MemoryContextSwitchTo(oldContext);
1455 : :
1456 : : /* Mark portal not active */
8122 1457 : 34060 : portal->status = PORTAL_READY;
1458 : :
8240 1459 : 34060 : ActivePortal = saveActivePortal;
8122 1460 : 34060 : CurrentResourceOwner = saveResourceOwner;
8564 1461 : 34060 : PortalContext = savePortalContext;
1462 : :
1463 : 34060 : return result;
1464 : : }
1465 : :
1466 : : /*
1467 : : * DoPortalRunFetch
1468 : : * Guts of PortalRunFetch --- the portal context is already set up
1469 : : *
1470 : : * Here, count < 0 typically reverses the direction. Also, count == FETCH_ALL
1471 : : * is interpreted as "all rows". (cf FetchStmt.howMany)
1472 : : *
1473 : : * Returns number of rows processed (suitable for use in result tag)
1474 : : */
1475 : : static uint64
1476 : 34108 : DoPortalRunFetch(Portal portal,
1477 : : FetchDirection fdirection,
1478 : : long count,
1479 : : DestReceiver *dest)
1480 : : {
1481 : : bool forward;
1482 : :
7914 1483 [ + + + + : 34108 : Assert(portal->strategy == PORTAL_ONE_SELECT ||
+ - - + ]
1484 : : portal->strategy == PORTAL_ONE_RETURNING ||
1485 : : portal->strategy == PORTAL_ONE_MOD_WITH ||
1486 : : portal->strategy == PORTAL_UTIL_SELECT);
1487 : :
1488 : : /*
1489 : : * Note: we disallow backwards fetch (including re-fetch of current row)
1490 : : * for NO SCROLL cursors, but we interpret that very loosely: you can use
1491 : : * any of the FetchDirection options, so long as the end result is to move
1492 : : * forwards by at least one row. Currently it's sufficient to check for
1493 : : * NO SCROLL in DoPortalRewind() and in the forward == false path in
1494 : : * PortalRunSelect(); but someday we might prefer to account for that
1495 : : * restriction explicitly here.
1496 : : */
8564 1497 [ + + + + : 34108 : switch (fdirection)
- ]
1498 : : {
1499 : 33592 : case FETCH_FORWARD:
1500 [ + + ]: 33592 : if (count < 0)
1501 : : {
1502 : 2 : fdirection = FETCH_BACKWARD;
1503 : 2 : count = -count;
1504 : : }
1505 : : /* fall out of switch to share code with FETCH_BACKWARD */
1506 : 33592 : break;
1507 : 352 : case FETCH_BACKWARD:
1508 [ + + ]: 352 : if (count < 0)
1509 : : {
1510 : 1 : fdirection = FETCH_FORWARD;
1511 : 1 : count = -count;
1512 : : }
1513 : : /* fall out of switch to share code with FETCH_FORWARD */
1514 : 352 : break;
1515 : 105 : case FETCH_ABSOLUTE:
1516 [ + + ]: 105 : if (count > 0)
1517 : : {
1518 : : /*
1519 : : * Definition: Rewind to start, advance count-1 rows, return
1520 : : * next row (if any).
1521 : : *
1522 : : * In practice, if the goal is less than halfway back to the
1523 : : * start, it's better to scan from where we are.
1524 : : *
1525 : : * Also, if current portalPos is outside the range of "long",
1526 : : * do it the hard way to avoid possible overflow of the count
1527 : : * argument to PortalRunSelect. We must exclude exactly
1528 : : * LONG_MAX, as well, lest the count look like FETCH_ALL.
1529 : : *
1530 : : * In any case, we arrange to fetch the target row going
1531 : : * forwards.
1532 : : */
3866 1533 [ + + ]: 63 : if ((uint64) (count - 1) <= portal->portalPos / 2 ||
1534 [ - + ]: 25 : portal->portalPos >= (uint64) LONG_MAX)
1535 : : {
8564 1536 : 38 : DoPortalRewind(portal);
1537 [ - + ]: 34 : if (count > 1)
8470 bruce@momjian.us 1538 :UBC 0 : PortalRunSelect(portal, true, count - 1,
1539 : : None_Receiver);
1540 : : }
1541 : : else
1542 : : {
3866 tgl@sss.pgh.pa.us 1543 :CBC 25 : long pos = (long) portal->portalPos;
1544 : :
8564 1545 [ - + ]: 25 : if (portal->atEnd)
8564 tgl@sss.pgh.pa.us 1546 :UBC 0 : pos++; /* need one extra fetch if off end */
8564 tgl@sss.pgh.pa.us 1547 [ + + ]:CBC 25 : if (count <= pos)
8470 bruce@momjian.us 1548 : 8 : PortalRunSelect(portal, false, pos - count + 1,
1549 : : None_Receiver);
1550 [ + + ]: 17 : else if (count > pos + 1)
1551 : 8 : PortalRunSelect(portal, true, count - pos - 1,
1552 : : None_Receiver);
1553 : : }
8564 tgl@sss.pgh.pa.us 1554 : 55 : return PortalRunSelect(portal, true, 1L, dest);
1555 : : }
1556 [ + + ]: 42 : else if (count < 0)
1557 : : {
1558 : : /*
1559 : : * Definition: Advance to end, back up abs(count)-1 rows,
1560 : : * return prior row (if any). We could optimize this if we
1561 : : * knew in advance where the end was, but typically we won't.
1562 : : * (Is it worth considering case where count > half of size of
1563 : : * query? We could rewind once we know the size ...)
1564 : : */
8560 1565 : 38 : PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
8564 1566 [ - + ]: 38 : if (count < -1)
8470 bruce@momjian.us 1567 :UBC 0 : PortalRunSelect(portal, false, -count - 1, None_Receiver);
8564 tgl@sss.pgh.pa.us 1568 :CBC 38 : return PortalRunSelect(portal, false, 1L, dest);
1569 : : }
1570 : : else
1571 : : {
1572 : : /* count == 0 */
1573 : : /* Rewind to start, return zero rows */
1574 : 4 : DoPortalRewind(portal);
1575 : 4 : return PortalRunSelect(portal, true, 0L, dest);
1576 : : }
1577 : : break;
1578 : 59 : case FETCH_RELATIVE:
1579 [ + + ]: 59 : if (count > 0)
1580 : : {
1581 : : /*
1582 : : * Definition: advance count-1 rows, return next row (if any).
1583 : : */
1584 [ + + ]: 26 : if (count > 1)
8470 bruce@momjian.us 1585 : 17 : PortalRunSelect(portal, true, count - 1, None_Receiver);
8564 tgl@sss.pgh.pa.us 1586 : 26 : return PortalRunSelect(portal, true, 1L, dest);
1587 : : }
1588 [ + + ]: 33 : else if (count < 0)
1589 : : {
1590 : : /*
1591 : : * Definition: back up abs(count)-1 rows, return prior row (if
1592 : : * any).
1593 : : */
1594 [ + + ]: 21 : if (count < -1)
8470 bruce@momjian.us 1595 : 12 : PortalRunSelect(portal, false, -count - 1, None_Receiver);
8564 tgl@sss.pgh.pa.us 1596 : 21 : return PortalRunSelect(portal, false, 1L, dest);
1597 : : }
1598 : : else
1599 : : {
1600 : : /* count == 0 */
1601 : : /* Same as FETCH FORWARD 0, so fall out of switch */
1602 : 12 : fdirection = FETCH_FORWARD;
1603 : : }
1604 : 12 : break;
8564 tgl@sss.pgh.pa.us 1605 :UBC 0 : default:
8483 1606 [ # # ]: 0 : elog(ERROR, "bogus direction");
1607 : : break;
1608 : : }
1609 : :
1610 : : /*
1611 : : * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1612 : : * >= 0.
1613 : : */
8564 tgl@sss.pgh.pa.us 1614 :CBC 33956 : forward = (fdirection == FETCH_FORWARD);
1615 : :
1616 : : /*
1617 : : * Zero count means to re-fetch the current row, if any (per SQL)
1618 : : */
1619 [ + + ]: 33956 : if (count == 0)
1620 : : {
1621 : : bool on_row;
1622 : :
1623 : : /* Are we sitting on a row? */
1624 [ + - + - ]: 12 : on_row = (!portal->atStart && !portal->atEnd);
1625 : :
7648 alvherre@alvh.no-ip. 1626 [ - + ]: 12 : if (dest->mydest == DestNone)
1627 : : {
1628 : : /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
3866 tgl@sss.pgh.pa.us 1629 :UBC 0 : return on_row ? 1 : 0;
1630 : : }
1631 : : else
1632 : : {
1633 : : /*
1634 : : * If we are sitting on a row, back up one so we can re-fetch it.
1635 : : * If we are not sitting on a row, we still have to start up and
1636 : : * shut down the executor so that the destination is initialized
1637 : : * and shut down correctly; so keep going. To PortalRunSelect,
1638 : : * count == 0 means we will retrieve no row.
1639 : : */
8564 tgl@sss.pgh.pa.us 1640 [ + - ]:CBC 12 : if (on_row)
1641 : : {
8560 1642 : 12 : PortalRunSelect(portal, false, 1L, None_Receiver);
1643 : : /* Set up to fetch one row forward */
8564 1644 : 8 : count = 1;
1645 : 8 : forward = true;
1646 : : }
1647 : : }
1648 : : }
1649 : :
1650 : : /*
1651 : : * Optimize MOVE BACKWARD ALL into a Rewind.
1652 : : */
7648 alvherre@alvh.no-ip. 1653 [ + + + + : 33952 : if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
+ + ]
1654 : : {
3866 tgl@sss.pgh.pa.us 1655 : 20 : uint64 result = portal->portalPos;
1656 : :
8564 1657 [ + + + + ]: 20 : if (result > 0 && !portal->atEnd)
1658 : 4 : result--;
1659 : 20 : DoPortalRewind(portal);
1660 : 20 : return result;
1661 : : }
1662 : :
1663 : 33932 : return PortalRunSelect(portal, forward, count, dest);
1664 : : }
1665 : :
1666 : : /*
1667 : : * DoPortalRewind - rewind a Portal to starting point
1668 : : */
1669 : : static void
1670 : 62 : DoPortalRewind(Portal portal)
1671 : : {
1672 : : QueryDesc *queryDesc;
1673 : :
1674 : : /*
1675 : : * No work is needed if we've not advanced nor attempted to advance the
1676 : : * cursor (and we don't want to throw a NO SCROLL error in this case).
1677 : : */
1858 1678 [ + + + - ]: 62 : if (portal->atStart && !portal->atEnd)
1679 : 12 : return;
1680 : :
1681 : : /* Otherwise, cursor must allow scrolling */
1682 [ + + ]: 50 : if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
1683 [ + - ]: 4 : ereport(ERROR,
1684 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1685 : : errmsg("cursor can only scan forward"),
1686 : : errhint("Declare it with SCROLL option to enable backward scan.")));
1687 : :
1688 : : /* Rewind holdStore, if we have one */
8564 1689 [ + + ]: 46 : if (portal->holdStore)
1690 : : {
1691 : : MemoryContext oldcontext;
1692 : :
1693 : 4 : oldcontext = MemoryContextSwitchTo(portal->holdContext);
1694 : 4 : tuplestore_rescan(portal->holdStore);
1695 : 4 : MemoryContextSwitchTo(oldcontext);
1696 : : }
1697 : :
1698 : : /* Rewind executor, if active */
3222 peter_e@gmx.net 1699 : 46 : queryDesc = portal->queryDesc;
4541 tgl@sss.pgh.pa.us 1700 [ + + ]: 46 : if (queryDesc)
1701 : : {
1702 : 42 : PushActiveSnapshot(queryDesc->snapshot);
1703 : 42 : ExecutorRewind(queryDesc);
1704 : 42 : PopActiveSnapshot();
1705 : : }
1706 : :
8564 1707 : 46 : portal->atStart = true;
1708 : 46 : portal->atEnd = false;
1709 : 46 : portal->portalPos = 0;
1710 : : }
1711 : :
1712 : : /*
1713 : : * PlannedStmtRequiresSnapshot - what it says on the tin
1714 : : */
1715 : : bool
1970 1716 : 304344 : PlannedStmtRequiresSnapshot(PlannedStmt *pstmt)
1717 : : {
1718 : 304344 : Node *utilityStmt = pstmt->utilityStmt;
1719 : :
1720 : : /* If it's not a utility statement, it definitely needs a snapshot */
1721 [ + + ]: 304344 : if (utilityStmt == NULL)
1722 : 59906 : return true;
1723 : :
1724 : : /*
1725 : : * Most utility statements need a snapshot, and the default presumption
1726 : : * about new ones should be that they do too. Hence, enumerate those that
1727 : : * do not need one.
1728 : : *
1729 : : * Transaction control, LOCK, and SET must *not* set a snapshot, since
1730 : : * they need to be executable at the start of a transaction-snapshot-mode
1731 : : * transaction without freezing a snapshot. By extension we allow SHOW
1732 : : * not to set a snapshot. The other stmts listed are just efficiency
1733 : : * hacks. Beware of listing anything that can modify the database --- if,
1734 : : * say, it has to update an index with expressions that invoke
1735 : : * user-defined functions, then it had better have a snapshot.
1736 : : */
1737 [ + + ]: 244438 : if (IsA(utilityStmt, TransactionStmt) ||
1738 [ + + ]: 217554 : IsA(utilityStmt, LockStmt) ||
1739 [ + + ]: 216955 : IsA(utilityStmt, VariableSetStmt) ||
1740 [ + + ]: 192045 : IsA(utilityStmt, VariableShowStmt) ||
1741 [ + + ]: 191492 : IsA(utilityStmt, ConstraintsSetStmt) ||
1742 : : /* efficiency hacks from here down */
1743 [ + + ]: 191421 : IsA(utilityStmt, FetchStmt) ||
1744 [ + + ]: 187048 : IsA(utilityStmt, ListenStmt) ||
1745 [ + + ]: 186996 : IsA(utilityStmt, NotifyStmt) ||
1746 [ + + ]: 186944 : IsA(utilityStmt, UnlistenStmt) ||
341 akorotkov@postgresql 1747 [ + + ]: 186882 : IsA(utilityStmt, CheckPointStmt) ||
1748 [ + + ]: 186409 : IsA(utilityStmt, WaitStmt))
1970 tgl@sss.pgh.pa.us 1749 : 58324 : return false;
1750 : :
1751 : 186114 : return true;
1752 : : }
1753 : :
1754 : : /*
1755 : : * EnsurePortalSnapshotExists - recreate Portal-level snapshot, if needed
1756 : : *
1757 : : * Generally, we will have an active snapshot whenever we are executing
1758 : : * inside a Portal, unless the Portal's query is one of the utility
1759 : : * statements exempted from that rule (see PlannedStmtRequiresSnapshot).
1760 : : * However, procedures and DO blocks can commit or abort the transaction,
1761 : : * and thereby destroy all snapshots. This function can be called to
1762 : : * re-establish the Portal-level snapshot when none exists.
1763 : : */
1764 : : void
1765 : 288917 : EnsurePortalSnapshotExists(void)
1766 : : {
1767 : : Portal portal;
1768 : :
1769 : : /*
1770 : : * Nothing to do if a snapshot is set. (We take it on faith that the
1771 : : * outermost active snapshot belongs to some Portal; or if there is no
1772 : : * Portal, it's somebody else's responsibility to manage things.)
1773 : : */
1774 [ + + ]: 288917 : if (ActiveSnapshotSet())
1775 : 286667 : return;
1776 : :
1777 : : /* Otherwise, we'd better have an active Portal */
1778 : 2250 : portal = ActivePortal;
1899 1779 [ - + ]: 2250 : if (unlikely(portal == NULL))
1899 tgl@sss.pgh.pa.us 1780 [ # # ]:UBC 0 : elog(ERROR, "cannot execute SQL without an outer snapshot or portal");
1970 tgl@sss.pgh.pa.us 1781 [ - + ]:CBC 2250 : Assert(portal->portalSnapshot == NULL);
1782 : :
1783 : : /*
1784 : : * Create a new snapshot, make it active, and remember it in portal.
1785 : : * Because the portal now references the snapshot, we must tell snapmgr.c
1786 : : * that the snapshot belongs to the portal's transaction level, else we
1787 : : * risk portalSnapshot becoming a dangling pointer.
1788 : : */
1837 1789 : 2250 : PushActiveSnapshotWithLevel(GetTransactionSnapshot(), portal->createLevel);
1790 : : /* PushActiveSnapshotWithLevel might have copied the snapshot */
1970 1791 : 2250 : portal->portalSnapshot = GetActiveSnapshot();
1792 : : }
|