Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * portalmem.c
4 : : * backend portal memory management
5 : : *
6 : : * Portals are objects representing the execution state of a query.
7 : : * This module provides memory management services for portals, but it
8 : : * doesn't actually run the executor for them.
9 : : *
10 : : *
11 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
12 : : * Portions Copyright (c) 1994, Regents of the University of California
13 : : *
14 : : * IDENTIFICATION
15 : : * src/backend/utils/mmgr/portalmem.c
16 : : *
17 : : *-------------------------------------------------------------------------
18 : : */
19 : : #include "postgres.h"
20 : :
21 : : #include "access/xact.h"
22 : : #include "commands/portalcmds.h"
23 : : #include "funcapi.h"
24 : : #include "miscadmin.h"
25 : : #include "storage/ipc.h"
26 : : #include "utils/builtins.h"
27 : : #include "utils/hsearch.h"
28 : : #include "utils/memutils.h"
29 : : #include "utils/snapmgr.h"
30 : : #include "utils/timestamp.h"
31 : : #include "utils/tuplestore.h"
32 : :
33 : : /*
34 : : * Estimate of the maximum number of open portals a user would have,
35 : : * used in initially sizing the PortalHashTable in EnablePortalManager().
36 : : * Since the hash table can expand, there's no need to make this overly
37 : : * generous, and keeping it small avoids unnecessary overhead in the
38 : : * hash_seq_search() calls executed during transaction end.
39 : : */
40 : : #define PORTALS_PER_USER 16
41 : :
42 : :
43 : : /* ----------------
44 : : * Global state
45 : : * ----------------
46 : : */
47 : :
48 : : #define MAX_PORTALNAME_LEN NAMEDATALEN
49 : :
50 : : typedef struct portalhashent
51 : : {
52 : : char portalname[MAX_PORTALNAME_LEN];
53 : : Portal portal;
54 : : } PortalHashEnt;
55 : :
56 : : static HTAB *PortalHashTable = NULL;
57 : :
58 : : #define PortalHashTableLookup(NAME, PORTAL) \
59 : : do { \
60 : : PortalHashEnt *hentry; \
61 : : \
62 : : hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
63 : : (NAME), HASH_FIND, NULL); \
64 : : if (hentry) \
65 : : PORTAL = hentry->portal; \
66 : : else \
67 : : PORTAL = NULL; \
68 : : } while(0)
69 : :
70 : : #define PortalHashTableInsert(PORTAL, NAME) \
71 : : do { \
72 : : PortalHashEnt *hentry; bool found; \
73 : : \
74 : : hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
75 : : (NAME), HASH_ENTER, &found); \
76 : : if (found) \
77 : : elog(ERROR, "duplicate portal name"); \
78 : : hentry->portal = PORTAL; \
79 : : /* To avoid duplicate storage, make PORTAL->name point to htab entry */ \
80 : : PORTAL->name = hentry->portalname; \
81 : : } while(0)
82 : :
83 : : #define PortalHashTableDelete(PORTAL) \
84 : : do { \
85 : : PortalHashEnt *hentry; \
86 : : \
87 : : hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
88 : : PORTAL->name, HASH_REMOVE, NULL); \
89 : : if (hentry == NULL) \
90 : : elog(WARNING, "trying to delete portal name that does not exist"); \
91 : : } while(0)
92 : :
93 : : static MemoryContext TopPortalContext = NULL;
94 : :
95 : :
96 : : /* ----------------------------------------------------------------
97 : : * public portal interface functions
98 : : * ----------------------------------------------------------------
99 : : */
100 : :
101 : : /*
102 : : * EnablePortalManager
103 : : * Enables the portal management module at backend startup.
104 : : */
105 : : void
9649 tgl@sss.pgh.pa.us 106 :CBC 20451 : EnablePortalManager(void)
107 : : {
108 : : HASHCTL ctl;
109 : :
3269 peter_e@gmx.net 110 [ - + ]: 20451 : Assert(TopPortalContext == NULL);
111 : :
112 : 20451 : TopPortalContext = AllocSetContextCreate(TopMemoryContext,
113 : : "TopPortalContext",
114 : : ALLOCSET_DEFAULT_SIZES);
115 : :
9649 tgl@sss.pgh.pa.us 116 : 20451 : ctl.keysize = MAX_PORTALNAME_LEN;
9189 117 : 20451 : ctl.entrysize = sizeof(PortalHashEnt);
118 : :
119 : : /*
120 : : * use PORTALS_PER_USER as a guess of how many hash table entries to
121 : : * create, initially
122 : : */
9185 123 : 20451 : PortalHashTable = hash_create("Portal hash", PORTALS_PER_USER,
124 : : &ctl, HASH_ELEM | HASH_STRINGS);
11099 scrappy@hub.org 125 : 20451 : }
126 : :
127 : : /*
128 : : * GetPortalByName
129 : : * Returns a portal given a portal name, or NULL if name not found.
130 : : */
131 : : Portal
8734 tgl@sss.pgh.pa.us 132 : 552182 : GetPortalByName(const char *name)
133 : : {
134 : : Portal portal;
135 : :
430 peter@eisentraut.org 136 [ + + ]: 552182 : if (name)
10674 bruce@momjian.us 137 [ + + ]: 552181 : PortalHashTableLookup(name, portal);
138 : : else
9649 tgl@sss.pgh.pa.us 139 : 1 : portal = NULL;
140 : :
10315 bruce@momjian.us 141 : 552182 : return portal;
142 : : }
143 : :
144 : : /*
145 : : * PortalGetPrimaryStmt
146 : : * Get the "primary" stmt within a portal, ie, the one marked canSetTag.
147 : : *
148 : : * Returns NULL if no such stmt. If multiple PlannedStmt structs within the
149 : : * portal are marked canSetTag, returns the first one. Neither of these
150 : : * cases should occur in present usages of this function.
151 : : */
152 : : PlannedStmt *
3605 tgl@sss.pgh.pa.us 153 : 239824 : PortalGetPrimaryStmt(Portal portal)
154 : : {
155 : : ListCell *lc;
156 : :
157 [ + - + - : 239824 : foreach(lc, portal->stmts)
+ - ]
158 : : {
3519 159 : 239824 : PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
160 : :
3605 161 [ + - ]: 239824 : if (stmt->canSetTag)
162 : 239824 : return stmt;
163 : : }
7411 tgl@sss.pgh.pa.us 164 :UBC 0 : return NULL;
165 : : }
166 : :
167 : : /*
168 : : * CreatePortal
169 : : * Returns a new portal given a name.
170 : : *
171 : : * allowDup: if true, automatically drop any pre-existing portal of the
172 : : * same name (if false, an error is raised).
173 : : *
174 : : * dupSilent: if true, don't even emit a WARNING.
175 : : */
176 : : Portal
8611 tgl@sss.pgh.pa.us 177 :CBC 485562 : CreatePortal(const char *name, bool allowDup, bool dupSilent)
178 : : {
179 : : Portal portal;
180 : :
430 peter@eisentraut.org 181 [ - + ]: 485562 : Assert(name);
182 : :
10674 bruce@momjian.us 183 : 485562 : portal = GetPortalByName(name);
184 [ + + ]: 485562 : if (PortalIsValid(portal))
185 : : {
8611 tgl@sss.pgh.pa.us 186 [ - + ]: 7142 : if (!allowDup)
8527 tgl@sss.pgh.pa.us 187 [ # # ]:UBC 0 : ereport(ERROR,
188 : : (errcode(ERRCODE_DUPLICATE_CURSOR),
189 : : errmsg("cursor \"%s\" already exists", name)));
8611 tgl@sss.pgh.pa.us 190 [ - + ]:CBC 7142 : if (!dupSilent)
8527 tgl@sss.pgh.pa.us 191 [ # # ]:UBC 0 : ereport(WARNING,
192 : : (errcode(ERRCODE_DUPLICATE_CURSOR),
193 : : errmsg("closing existing cursor \"%s\"",
194 : : name)));
8611 tgl@sss.pgh.pa.us 195 :CBC 7142 : PortalDrop(portal, false);
196 : : }
197 : :
198 : : /* make new portal structure */
3269 peter_e@gmx.net 199 : 485562 : portal = (Portal) MemoryContextAllocZero(TopPortalContext, sizeof *portal);
200 : :
201 : : /* initialize portal context; typically it won't store much */
202 : 485562 : portal->portalContext = AllocSetContextCreate(TopPortalContext,
203 : : "PortalContext",
204 : : ALLOCSET_SMALL_SIZES);
205 : :
206 : : /* create a resource owner for the portal */
8169 tgl@sss.pgh.pa.us 207 : 485562 : portal->resowner = ResourceOwnerCreate(CurTransactionResourceOwner,
208 : : "Portal");
209 : :
210 : : /* initialize portal fields that don't start off zero */
7619 neilc@samurai.com 211 : 485562 : portal->status = PORTAL_NEW;
8614 tgl@sss.pgh.pa.us 212 : 485562 : portal->cleanup = PortalCleanup;
8108 213 : 485562 : portal->createSubid = GetCurrentSubTransactionId();
4103 214 : 485562 : portal->activeSubid = portal->createSubid;
1884 215 : 485562 : portal->createLevel = GetCurrentTransactionNestLevel();
8611 216 : 485562 : portal->strategy = PORTAL_MULTI_QUERY;
217 : 485562 : portal->cursorOptions = CURSOR_OPT_NO_SCROLL;
8663 218 : 485562 : portal->atStart = true;
219 : 485562 : portal->atEnd = true; /* disallow fetches until query is set */
7619 neilc@samurai.com 220 : 485562 : portal->visible = true;
7466 tgl@sss.pgh.pa.us 221 : 485562 : portal->creation_time = GetCurrentStatementStartTimestamp();
222 : :
223 : : /* put portal in table (sets portal->name) */
8611 224 [ - + - - ]: 485562 : PortalHashTableInsert(portal, name);
225 : :
226 : : /* for named portals reuse portal->name copy */
2272 peter@eisentraut.org 227 [ + + ]: 485562 : MemoryContextSetIdentifier(portal->portalContext, portal->name[0] ? portal->name : "<unnamed>");
228 : :
10315 bruce@momjian.us 229 : 485562 : return portal;
230 : : }
231 : :
232 : : /*
233 : : * CreateNewPortal
234 : : * Create a new portal, assigning it a random nonconflicting name.
235 : : */
236 : : Portal
8611 tgl@sss.pgh.pa.us 237 : 16940 : CreateNewPortal(void)
238 : : {
239 : : static unsigned int unnamed_portal_count = 0;
240 : :
241 : : char portalname[MAX_PORTALNAME_LEN];
242 : :
243 : : /* Select a nonconflicting name */
244 : : for (;;)
245 : : {
246 : 16940 : unnamed_portal_count++;
247 : 16940 : sprintf(portalname, "<unnamed portal %u>", unnamed_portal_count);
248 [ + - ]: 16940 : if (GetPortalByName(portalname) == NULL)
249 : 16940 : break;
250 : : }
251 : :
252 : 16940 : return CreatePortal(portalname, false, false);
253 : : }
254 : :
255 : : /*
256 : : * PortalDefineQuery
257 : : * A simple subroutine to establish a portal's query.
258 : : *
259 : : * Notes: as of PG 8.4, caller MUST supply a sourceText string; it is not
260 : : * allowed anymore to pass NULL. (If you really don't have source text,
261 : : * you can pass a constant string, perhaps "(query not available)".)
262 : : *
263 : : * commandTag shall be NULL if and only if the original query string
264 : : * (before rewriting) was an empty string. Also, the passed commandTag must
265 : : * be a pointer to a constant string, since it is not copied.
266 : : *
267 : : * If cplan is provided, then it is a cached plan containing the stmts, and
268 : : * the caller must have done GetCachedPlan(), causing a refcount increment.
269 : : * The refcount will be released when the portal is destroyed.
270 : : *
271 : : * If cplan is NULL, then it is the caller's responsibility to ensure that
272 : : * the passed plan trees have adequate lifetime. Typically this is done by
273 : : * copying them into the portal's context.
274 : : *
275 : : * The caller is also responsible for ensuring that the passed prepStmtName
276 : : * (if not NULL) and sourceText have adequate lifetime.
277 : : *
278 : : * NB: this function mustn't do much beyond storing the passed values; in
279 : : * particular don't do anything that risks elog(ERROR). If that were to
280 : : * happen here before storing the cplan reference, we'd leak the plancache
281 : : * refcount that the caller is trying to hand off to us.
282 : : */
283 : : void
284 : 485532 : PortalDefineQuery(Portal portal,
285 : : const char *prepStmtName,
286 : : const char *sourceText,
287 : : CommandTag commandTag,
288 : : List *stmts,
289 : : CachedPlan *cplan)
290 : : {
1492 peter@eisentraut.org 291 [ - + ]: 485532 : Assert(PortalIsValid(portal));
292 [ - + ]: 485532 : Assert(portal->status == PORTAL_NEW);
293 : :
294 [ - + ]: 485532 : Assert(sourceText != NULL);
295 [ - + - - ]: 485532 : Assert(commandTag != CMDTAG_UNKNOWN || stmts == NIL);
296 : :
6814 tgl@sss.pgh.pa.us 297 : 485532 : portal->prepStmtName = prepStmtName;
298 : 485532 : portal->sourceText = sourceText;
8611 299 : 485532 : portal->commandTag = commandTag;
302 alvherre@kurilemu.de 300 : 485532 : SetQueryCompletion(&portal->qc, commandTag, 0);
7221 tgl@sss.pgh.pa.us 301 : 485532 : portal->stmts = stmts;
7200 302 : 485532 : portal->cplan = cplan;
303 : 485532 : portal->status = PORTAL_DEFINED;
304 : 485532 : }
305 : :
306 : : /*
307 : : * PortalReleaseCachedPlan
308 : : * Release a portal's reference to its cached plan, if any.
309 : : */
310 : : static void
311 : 508754 : PortalReleaseCachedPlan(Portal portal)
312 : : {
313 [ + + ]: 508754 : if (portal->cplan)
314 : : {
2133 315 : 24142 : ReleaseCachedPlan(portal->cplan, NULL);
7200 316 : 24142 : portal->cplan = NULL;
317 : :
318 : : /*
319 : : * We must also clear portal->stmts which is now a dangling reference
320 : : * to the cached plan's plan list. This protects any code that might
321 : : * try to examine the Portal later.
322 : : */
6158 323 : 24142 : portal->stmts = NIL;
324 : : }
8611 325 : 508754 : }
326 : :
327 : : /*
328 : : * PortalCreateHoldStore
329 : : * Create the tuplestore for a portal.
330 : : */
331 : : void
8607 332 : 32846 : PortalCreateHoldStore(Portal portal)
333 : : {
334 : : MemoryContext oldcxt;
335 : :
336 [ - + ]: 32846 : Assert(portal->holdContext == NULL);
337 [ - + ]: 32846 : Assert(portal->holdStore == NULL);
3765 338 [ - + ]: 32846 : Assert(portal->holdSnapshot == NULL);
339 : :
340 : : /*
341 : : * Create the memory context that is used for storage of the tuple set.
342 : : * Note this is NOT a child of the portal's portalContext.
343 : : */
8607 344 : 32846 : portal->holdContext =
3269 peter_e@gmx.net 345 : 32846 : AllocSetContextCreate(TopPortalContext,
346 : : "PortalHoldContext",
347 : : ALLOCSET_DEFAULT_SIZES);
348 : :
349 : : /*
350 : : * Create the tuple store, selecting cross-transaction temp files, and
351 : : * enabling random access only if cursor requires scrolling.
352 : : *
353 : : * XXX: Should maintenance_work_mem be used for the portal size?
354 : : */
8607 tgl@sss.pgh.pa.us 355 : 32846 : oldcxt = MemoryContextSwitchTo(portal->holdContext);
356 : :
6604 357 : 32846 : portal->holdStore =
358 : 32846 : tuplestore_begin_heap(portal->cursorOptions & CURSOR_OPT_SCROLL,
359 : : true, work_mem);
360 : :
8607 361 : 32846 : MemoryContextSwitchTo(oldcxt);
362 : 32846 : }
363 : :
364 : : /*
365 : : * PinPortal
366 : : * Protect a portal from dropping.
367 : : *
368 : : * A pinned portal is still unpinned and dropped at transaction or
369 : : * subtransaction abort.
370 : : */
371 : : void
5990 heikki.linnakangas@i 372 : 8116 : PinPortal(Portal portal)
373 : : {
374 [ - + ]: 8116 : if (portal->portalPinned)
5990 heikki.linnakangas@i 375 [ # # ]:UBC 0 : elog(ERROR, "portal already pinned");
376 : :
5990 heikki.linnakangas@i 377 :CBC 8116 : portal->portalPinned = true;
378 : 8116 : }
379 : :
380 : : void
381 : 8068 : UnpinPortal(Portal portal)
382 : : {
383 [ - + ]: 8068 : if (!portal->portalPinned)
5990 heikki.linnakangas@i 384 [ # # ]:UBC 0 : elog(ERROR, "portal not pinned");
385 : :
5990 heikki.linnakangas@i 386 :CBC 8068 : portal->portalPinned = false;
387 : 8068 : }
388 : :
389 : : /*
390 : : * MarkPortalActive
391 : : * Transition a portal from READY to ACTIVE state.
392 : : *
393 : : * NOTE: never set portal->status = PORTAL_ACTIVE directly; call this instead.
394 : : */
395 : : void
4103 tgl@sss.pgh.pa.us 396 : 508518 : MarkPortalActive(Portal portal)
397 : : {
398 : : /* For safety, this is a runtime test not just an Assert */
399 [ + + ]: 508518 : if (portal->status != PORTAL_READY)
400 [ + - ]: 12 : ereport(ERROR,
401 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
402 : : errmsg("portal \"%s\" cannot be run", portal->name)));
403 : : /* Perform the state transition */
404 : 508506 : portal->status = PORTAL_ACTIVE;
405 : 508506 : portal->activeSubid = GetCurrentSubTransactionId();
406 : 508506 : }
407 : :
408 : : /*
409 : : * MarkPortalDone
410 : : * Transition a portal from ACTIVE to DONE state.
411 : : *
412 : : * NOTE: never set portal->status = PORTAL_DONE directly; call this instead.
413 : : */
414 : : void
5749 415 : 245906 : MarkPortalDone(Portal portal)
416 : : {
417 : : /* Perform the state transition */
418 [ - + ]: 245906 : Assert(portal->status == PORTAL_ACTIVE);
419 : 245906 : portal->status = PORTAL_DONE;
420 : :
421 : : /*
422 : : * Allow portalcmds.c to clean up the state it knows about. We might as
423 : : * well do that now, since the portal can't be executed any more.
424 : : *
425 : : * In some cases involving execution of a ROLLBACK command in an already
426 : : * aborted transaction, this is necessary, or we'd reach AtCleanup_Portals
427 : : * with the cleanup hook still unexecuted.
428 : : */
430 peter@eisentraut.org 429 [ + + ]: 245906 : if (portal->cleanup)
430 : : {
3369 peter_e@gmx.net 431 : 245865 : portal->cleanup(portal);
5400 tgl@sss.pgh.pa.us 432 : 245865 : portal->cleanup = NULL;
433 : : }
434 : 245906 : }
435 : :
436 : : /*
437 : : * MarkPortalFailed
438 : : * Transition a portal into FAILED state.
439 : : *
440 : : * NOTE: never set portal->status = PORTAL_FAILED directly; call this instead.
441 : : */
442 : : void
443 : 22941 : MarkPortalFailed(Portal portal)
444 : : {
445 : : /* Perform the state transition */
446 [ - + ]: 22941 : Assert(portal->status != PORTAL_DONE);
447 : 22941 : portal->status = PORTAL_FAILED;
448 : :
449 : : /*
450 : : * Allow portalcmds.c to clean up the state it knows about. We might as
451 : : * well do that now, since the portal can't be executed any more.
452 : : *
453 : : * In some cases involving cleanup of an already aborted transaction, this
454 : : * is necessary, or we'd reach AtCleanup_Portals with the cleanup hook
455 : : * still unexecuted.
456 : : */
430 peter@eisentraut.org 457 [ + + ]: 22941 : if (portal->cleanup)
458 : : {
3369 peter_e@gmx.net 459 : 22898 : portal->cleanup(portal);
5749 tgl@sss.pgh.pa.us 460 : 22898 : portal->cleanup = NULL;
461 : : }
462 : 22941 : }
463 : :
464 : : /*
465 : : * PortalDrop
466 : : * Destroy the portal.
467 : : */
468 : : void
8169 469 : 485527 : PortalDrop(Portal portal, bool isTopCommit)
470 : : {
1492 peter@eisentraut.org 471 [ - + ]: 485527 : Assert(PortalIsValid(portal));
472 : :
473 : : /*
474 : : * Don't allow dropping a pinned portal, it's still needed by whoever
475 : : * pinned it.
476 : : */
3244 peter_e@gmx.net 477 [ - + ]: 485527 : if (portal->portalPinned)
3244 peter_e@gmx.net 478 [ # # ]:UBC 0 : ereport(ERROR,
479 : : (errcode(ERRCODE_INVALID_CURSOR_STATE),
480 : : errmsg("cannot drop pinned portal \"%s\"", portal->name)));
481 : :
482 : : /*
483 : : * Don't allow dropping a portal being set up.
484 : : */
19 michael@paquier.xyz 485 [ + + + + ]:CBC 485527 : if (portal->status == PORTAL_NEW || portal->status == PORTAL_DEFINED)
486 [ + - ]: 8 : ereport(ERROR,
487 : : (errcode(ERRCODE_INVALID_CURSOR_STATE),
488 : : errmsg("cannot drop portal \"%s\" while it is being set up",
489 : : portal->name)));
490 : :
491 : :
492 : : /*
493 : : * Not sure if the PORTAL_ACTIVE case can validly happen or not...
494 : : */
3244 peter_e@gmx.net 495 [ - + ]: 485519 : if (portal->status == PORTAL_ACTIVE)
5990 heikki.linnakangas@i 496 [ # # ]:UBC 0 : ereport(ERROR,
497 : : (errcode(ERRCODE_INVALID_CURSOR_STATE),
498 : : errmsg("cannot drop active portal \"%s\"", portal->name)));
499 : :
500 : : /*
501 : : * Allow portalcmds.c to clean up the state it knows about, in particular
502 : : * shutting down the executor if still active. This step potentially runs
503 : : * user-defined code so failure has to be expected. It's the cleanup
504 : : * hook's responsibility to not try to do that more than once, in the case
505 : : * that failure occurs and then we come back to drop the portal again
506 : : * during transaction abort.
507 : : *
508 : : * Note: in most paths of control, this will have been done already in
509 : : * MarkPortalDone or MarkPortalFailed. We're just making sure.
510 : : */
430 peter@eisentraut.org 511 [ + + ]:CBC 485519 : if (portal->cleanup)
512 : : {
3369 peter_e@gmx.net 513 : 216669 : portal->cleanup(portal);
5753 tgl@sss.pgh.pa.us 514 : 216668 : portal->cleanup = NULL;
515 : : }
516 : :
517 : : /* There shouldn't be an active snapshot anymore, except after error */
2017 518 [ + + - + ]: 485518 : Assert(portal->portalSnapshot == NULL || !isTopCommit);
519 : :
520 : : /*
521 : : * Remove portal from hash table. Because we do this here, we will not
522 : : * come back to try to remove the portal again if there's any error in the
523 : : * subsequent steps. Better to leak a little memory than to get into an
524 : : * infinite error-recovery loop.
525 : : */
9649 526 [ - + - - ]: 485518 : PortalHashTableDelete(portal);
527 : :
528 : : /* drop cached plan reference, if any */
6158 529 : 485518 : PortalReleaseCachedPlan(portal);
530 : :
531 : : /*
532 : : * If portal has a snapshot protecting its data, release that. This needs
533 : : * a little care since the registration will be attached to the portal's
534 : : * resowner; if the portal failed, we will already have released the
535 : : * resowner (and the snapshot) during transaction abort.
536 : : */
3765 537 [ + + ]: 485518 : if (portal->holdSnapshot)
538 : : {
539 [ + + ]: 28460 : if (portal->resowner)
540 : 27999 : UnregisterSnapshotFromOwner(portal->holdSnapshot,
541 : : portal->resowner);
542 : 28460 : portal->holdSnapshot = NULL;
543 : : }
544 : :
545 : : /*
546 : : * Release any resources still attached to the portal. There are several
547 : : * cases being covered here:
548 : : *
549 : : * Top transaction commit (indicated by isTopCommit): normally we should
550 : : * do nothing here and let the regular end-of-transaction resource
551 : : * releasing mechanism handle these resources too. However, if we have a
552 : : * FAILED portal (eg, a cursor that got an error), we'd better clean up
553 : : * its resources to avoid resource-leakage warning messages.
554 : : *
555 : : * Sub transaction commit: never comes here at all, since we don't kill
556 : : * any portals in AtSubCommit_Portals().
557 : : *
558 : : * Main or sub transaction abort: we will do nothing here because
559 : : * portal->resowner was already set NULL; the resources were already
560 : : * cleaned up in transaction abort.
561 : : *
562 : : * Ordinary portal drop: must release resources. However, if the portal
563 : : * is not FAILED then we do not release its locks. The locks become the
564 : : * responsibility of the transaction's ResourceOwner (since it is the
565 : : * parent of the portal's owner) and will be released when the transaction
566 : : * eventually ends.
567 : : */
8169 568 [ + + ]: 485518 : if (portal->resowner &&
569 [ + + - + ]: 455633 : (!isTopCommit || portal->status == PORTAL_FAILED))
570 : : {
8126 bruce@momjian.us 571 : 447973 : bool isCommit = (portal->status != PORTAL_FAILED);
572 : :
8169 tgl@sss.pgh.pa.us 573 : 447973 : ResourceOwnerRelease(portal->resowner,
574 : : RESOURCE_RELEASE_BEFORE_LOCKS,
575 : : isCommit, false);
576 : 447973 : ResourceOwnerRelease(portal->resowner,
577 : : RESOURCE_RELEASE_LOCKS,
578 : : isCommit, false);
579 : 447973 : ResourceOwnerRelease(portal->resowner,
580 : : RESOURCE_RELEASE_AFTER_LOCKS,
581 : : isCommit, false);
8130 582 : 447973 : ResourceOwnerDelete(portal->resowner);
583 : : }
8169 584 : 485518 : portal->resowner = NULL;
585 : :
586 : : /*
587 : : * Delete tuplestore if present. We should do this even under error
588 : : * conditions; since the tuplestore would have been using cross-
589 : : * transaction storage, its temp files need to be explicitly deleted.
590 : : */
8607 591 [ + + ]: 485518 : if (portal->holdStore)
592 : : {
593 : : MemoryContext oldcontext;
594 : :
595 : 32802 : oldcontext = MemoryContextSwitchTo(portal->holdContext);
596 : 32802 : tuplestore_end(portal->holdStore);
597 : 32802 : MemoryContextSwitchTo(oldcontext);
598 : 32802 : portal->holdStore = NULL;
599 : : }
600 : :
601 : : /* delete tuplestore storage, if any */
8647 bruce@momjian.us 602 [ + + ]: 485518 : if (portal->holdContext)
603 : 32802 : MemoryContextDelete(portal->holdContext);
604 : :
605 : : /* release subsidiary storage */
3269 peter_e@gmx.net 606 : 485518 : MemoryContextDelete(portal->portalContext);
607 : :
608 : : /* release portal struct (it's in TopPortalContext) */
9649 tgl@sss.pgh.pa.us 609 : 485518 : pfree(portal);
11099 scrappy@hub.org 610 : 485518 : }
611 : :
612 : : /*
613 : : * Delete all declared cursors.
614 : : *
615 : : * Used by commands: CLOSE ALL, DISCARD ALL
616 : : */
617 : : void
7170 neilc@samurai.com 618 : 147 : PortalHashTableDeleteAll(void)
619 : : {
620 : : HASH_SEQ_STATUS status;
621 : : PortalHashEnt *hentry;
622 : :
623 [ - + ]: 147 : if (PortalHashTable == NULL)
7170 neilc@samurai.com 624 :UBC 0 : return;
625 : :
7170 neilc@samurai.com 626 :CBC 147 : hash_seq_init(&status, PortalHashTable);
627 [ + + ]: 345 : while ((hentry = hash_seq_search(&status)) != NULL)
628 : : {
6953 bruce@momjian.us 629 : 198 : Portal portal = hentry->portal;
630 : :
631 : : /*
632 : : * Can't close the active portal (the one running the command), or
633 : : * portals being set up.
634 : : */
19 michael@paquier.xyz 635 [ + + ]: 198 : if (portal->status == PORTAL_ACTIVE ||
636 [ + + ]: 53 : portal->status == PORTAL_NEW ||
637 [ + + ]: 33 : portal->status == PORTAL_DEFINED)
5753 tgl@sss.pgh.pa.us 638 : 181 : continue;
639 : :
640 : 17 : PortalDrop(portal, false);
641 : :
642 : : /* Restart the iteration in case that led to other drops */
643 : 17 : hash_seq_term(&status);
644 : 17 : hash_seq_init(&status, PortalHashTable);
645 : : }
646 : : }
647 : :
648 : : /*
649 : : * Drop portals dependent on the given queryEnv.
650 : : */
651 : : void
19 jdavis@postgresql.or 652 : 375 : DropQueryEnvPortals(QueryEnvironment *queryEnv)
653 : : {
654 : : HASH_SEQ_STATUS status;
655 : : PortalHashEnt *hentry;
656 : :
657 [ - + ]: 375 : if (PortalHashTable == NULL)
19 jdavis@postgresql.or 658 :UBC 0 : return;
659 : :
19 jdavis@postgresql.or 660 :CBC 375 : hash_seq_init(&status, PortalHashTable);
661 [ + + ]: 750 : while ((hentry = hash_seq_search(&status)) != NULL)
662 : : {
663 : 375 : Portal portal = hentry->portal;
664 : :
665 [ + - ]: 375 : if (portal->queryEnv != queryEnv)
666 : 375 : continue;
667 : :
668 : : /*
669 : : * It's safe to unpin and close, because any reference preserved past
670 : : * SPI_finish() must be by name, not a raw pointer.
671 : : */
19 jdavis@postgresql.or 672 :UBC 0 : portal->portalPinned = false;
673 : :
674 : 0 : PortalDrop(portal, false);
675 : :
676 : : /* Restart the iteration in case that led to other drops */
677 : 0 : hash_seq_term(&status);
678 : 0 : hash_seq_init(&status, PortalHashTable);
679 : : }
680 : : }
681 : :
682 : : /*
683 : : * "Hold" a portal. Prepare it for access by later transactions.
684 : : */
685 : : static void
3167 peter_e@gmx.net 686 :CBC 118 : HoldPortal(Portal portal)
687 : : {
688 : : /*
689 : : * Note that PersistHoldablePortal() must release all resources used by
690 : : * the portal that are local to the creating transaction.
691 : : */
692 : 118 : PortalCreateHoldStore(portal);
693 : 118 : PersistHoldablePortal(portal);
694 : :
695 : : /* drop cached plan reference, if any */
696 : 116 : PortalReleaseCachedPlan(portal);
697 : :
698 : : /*
699 : : * Any resources belonging to the portal will be released in the upcoming
700 : : * transaction-wide cleanup; the portal will no longer have its own
701 : : * resources.
702 : : */
703 : 116 : portal->resowner = NULL;
704 : :
705 : : /*
706 : : * Having successfully exported the holdable cursor, mark it as not
707 : : * belonging to this transaction.
708 : : */
709 : 116 : portal->createSubid = InvalidSubTransactionId;
710 : 116 : portal->activeSubid = InvalidSubTransactionId;
1884 tgl@sss.pgh.pa.us 711 : 116 : portal->createLevel = 0;
3167 peter_e@gmx.net 712 : 116 : }
713 : :
714 : : /*
715 : : * Pre-commit processing for portals.
716 : : *
717 : : * Holdable cursors created in this transaction need to be converted to
718 : : * materialized form, since we are going to close down the executor and
719 : : * release locks. Non-holdable portals created in this transaction are
720 : : * simply removed. Portals remaining from prior transactions should be
721 : : * left untouched.
722 : : *
723 : : * Returns true if any portals changed state (possibly causing user-defined
724 : : * code to be run), false if not.
725 : : */
726 : : bool
5753 tgl@sss.pgh.pa.us 727 : 414739 : PreCommit_Portals(bool isPrepare)
728 : : {
7714 bruce@momjian.us 729 : 414739 : bool result = false;
730 : : HASH_SEQ_STATUS status;
731 : : PortalHashEnt *hentry;
732 : :
9185 tgl@sss.pgh.pa.us 733 : 414739 : hash_seq_init(&status, PortalHashTable);
734 : :
735 [ + + ]: 460913 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
736 : : {
8517 bruce@momjian.us 737 : 46174 : Portal portal = hentry->portal;
738 : :
739 : : /*
740 : : * There should be no pinned portals anymore. Complain if someone
741 : : * leaked one. Auto-held portals are allowed; we assume that whoever
742 : : * pinned them is managing them.
743 : : */
3167 peter_e@gmx.net 744 [ + + - + ]: 46174 : if (portal->portalPinned && !portal->autoHeld)
5753 tgl@sss.pgh.pa.us 745 [ # # ]:UBC 0 : elog(ERROR, "cannot commit while a portal is pinned");
746 : :
747 : : /*
748 : : * Do not touch active portals --- this can only happen in the case of
749 : : * a multi-transaction utility command, such as VACUUM, or a commit in
750 : : * a procedure.
751 : : *
752 : : * Note however that any resource owner attached to such a portal is
753 : : * still going to go away, so don't leave a dangling pointer. Also
754 : : * unregister any snapshots held by the portal, mainly to avoid
755 : : * snapshot leak warnings from ResourceOwnerRelease().
756 : : */
5753 tgl@sss.pgh.pa.us 757 [ + + ]:CBC 46174 : if (portal->status == PORTAL_ACTIVE)
758 : : {
3019 peter_e@gmx.net 759 [ + + ]: 36819 : if (portal->holdSnapshot)
760 : : {
761 [ + - ]: 1 : if (portal->resowner)
762 : 1 : UnregisterSnapshotFromOwner(portal->holdSnapshot,
763 : : portal->resowner);
764 : 1 : portal->holdSnapshot = NULL;
765 : : }
5753 tgl@sss.pgh.pa.us 766 : 36819 : portal->resowner = NULL;
767 : : /* Clear portalSnapshot too, for cleanliness */
2017 768 : 36819 : portal->portalSnapshot = NULL;
5753 769 : 36819 : continue;
770 : : }
771 : :
772 : : /* Is it a holdable portal created in the current xact? */
8169 773 [ + + ]: 9355 : if ((portal->cursorOptions & CURSOR_OPT_HOLD) &&
7901 774 [ + + ]: 1607 : portal->createSubid != InvalidSubTransactionId &&
8169 775 [ + - ]: 84 : portal->status == PORTAL_READY)
776 : : {
777 : : /*
778 : : * We are exiting the transaction that created a holdable cursor.
779 : : * Instead of dropping the portal, prepare it for access by later
780 : : * transactions.
781 : : *
782 : : * However, if this is PREPARE TRANSACTION rather than COMMIT,
783 : : * refuse PREPARE, because the semantics seem pretty unclear.
784 : : */
5753 785 [ - + ]: 84 : if (isPrepare)
5753 tgl@sss.pgh.pa.us 786 [ # # ]:UBC 0 : ereport(ERROR,
787 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
788 : : errmsg("cannot PREPARE a transaction that has created a cursor WITH HOLD")));
789 : :
3167 peter_e@gmx.net 790 :CBC 84 : HoldPortal(portal);
791 : :
792 : : /* Report we changed state */
7901 tgl@sss.pgh.pa.us 793 : 84 : result = true;
794 : : }
5753 795 [ + + ]: 9271 : else if (portal->createSubid == InvalidSubTransactionId)
796 : : {
797 : : /*
798 : : * Do nothing to cursors held over from a previous transaction
799 : : * (including ones we just froze in a previous cycle of this loop)
800 : : */
7901 801 : 1573 : continue;
802 : : }
803 : : else
804 : : {
805 : : /* Zap all non-holdable portals */
5753 806 : 7698 : PortalDrop(portal, true);
807 : :
808 : : /* Report we changed state */
809 : 7698 : result = true;
810 : : }
811 : :
812 : : /*
813 : : * After either freezing or dropping a portal, we have to restart the
814 : : * iteration, because we could have invoked user-defined code that
815 : : * caused a drop of the next portal in the hash chain.
816 : : */
7156 817 : 7782 : hash_seq_term(&status);
7871 bruce@momjian.us 818 : 7782 : hash_seq_init(&status, PortalHashTable);
819 : : }
820 : :
5753 tgl@sss.pgh.pa.us 821 : 414739 : return result;
822 : : }
823 : :
824 : : /*
825 : : * Abort processing for portals.
826 : : *
827 : : * At this point we run the cleanup hook if present, but we can't release the
828 : : * portal's memory until the cleanup call.
829 : : */
830 : : void
8611 831 : 37281 : AtAbort_Portals(void)
832 : : {
833 : : HASH_SEQ_STATUS status;
834 : : PortalHashEnt *hentry;
835 : :
836 : 37281 : hash_seq_init(&status, PortalHashTable);
837 : :
838 [ + + ]: 59723 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
839 : : {
8517 bruce@momjian.us 840 : 22442 : Portal portal = hentry->portal;
841 : :
842 : : /*
843 : : * When elog(FATAL) is progress, we need to set the active portal to
844 : : * failed, so that PortalCleanup() doesn't run the executor shutdown.
845 : : */
3222 peter_e@gmx.net 846 [ + + + + ]: 22442 : if (portal->status == PORTAL_ACTIVE && shmem_exit_inprogress)
847 : 5 : MarkPortalFailed(portal);
848 : :
849 : : /*
850 : : * Do nothing else to cursors held over from a previous transaction.
851 : : */
8108 tgl@sss.pgh.pa.us 852 [ + + ]: 22442 : if (portal->createSubid == InvalidSubTransactionId)
8611 853 : 252 : continue;
854 : :
855 : : /*
856 : : * Do nothing to auto-held cursors. This is similar to the case of a
857 : : * cursor from a previous transaction, but it could also be that the
858 : : * cursor was auto-held in this transaction, so it wants to live on.
859 : : */
3167 peter_e@gmx.net 860 [ - + ]: 22190 : if (portal->autoHeld)
3167 peter_e@gmx.net 861 :UBC 0 : continue;
862 : :
863 : : /*
864 : : * If it was created in the current transaction, we can't do normal
865 : : * shutdown on a READY portal either; it might refer to objects
866 : : * created in the failed transaction. See comments in
867 : : * AtSubAbort_Portals.
868 : : *
869 : : * A portal that was still being set up is also failed here, so that
870 : : * PortalDrop() accepts it later.
871 : : */
19 michael@paquier.xyz 872 [ + + ]:CBC 22190 : if (portal->status == PORTAL_NEW ||
873 [ + + ]: 22162 : portal->status == PORTAL_DEFINED ||
874 [ + + ]: 22156 : portal->status == PORTAL_READY)
5400 tgl@sss.pgh.pa.us 875 : 704 : MarkPortalFailed(portal);
876 : :
877 : : /*
878 : : * Allow portalcmds.c to clean up the state it knows about, if we
879 : : * haven't already.
880 : : */
430 peter@eisentraut.org 881 [ + + ]: 22190 : if (portal->cleanup)
882 : : {
3369 peter_e@gmx.net 883 : 87 : portal->cleanup(portal);
8611 tgl@sss.pgh.pa.us 884 : 87 : portal->cleanup = NULL;
885 : : }
886 : :
887 : : /* drop cached plan reference, if any */
6158 888 : 22190 : PortalReleaseCachedPlan(portal);
889 : :
890 : : /*
891 : : * Any resources belonging to the portal will be released in the
892 : : * upcoming transaction-wide cleanup; they will be gone before we run
893 : : * PortalDrop.
894 : : */
8169 895 : 22190 : portal->resowner = NULL;
896 : :
897 : : /*
898 : : * Although we can't delete the portal data structure proper, we can
899 : : * release any memory in subsidiary contexts, such as executor state.
900 : : * The cleanup hook was the last thing that might have needed data
901 : : * there. But leave active portals alone.
902 : : */
3232 peter_e@gmx.net 903 [ + + ]: 22190 : if (portal->status != PORTAL_ACTIVE)
904 : 22046 : MemoryContextDeleteChildren(portal->portalContext);
905 : : }
9461 tgl@sss.pgh.pa.us 906 : 37281 : }
907 : :
908 : : /*
909 : : * Post-abort cleanup for portals.
910 : : *
911 : : * Delete all portals not held over from prior transactions.
912 : : */
913 : : void
8611 914 : 37262 : AtCleanup_Portals(void)
915 : : {
916 : : HASH_SEQ_STATUS status;
917 : : PortalHashEnt *hentry;
918 : :
919 : 37262 : hash_seq_init(&status, PortalHashTable);
920 : :
921 [ + + ]: 58802 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
922 : : {
8517 bruce@momjian.us 923 : 21540 : Portal portal = hentry->portal;
924 : :
925 : : /*
926 : : * Do not touch active portals --- this can only happen in the case of
927 : : * a multi-transaction command.
928 : : */
3232 peter_e@gmx.net 929 [ + + ]: 21540 : if (portal->status == PORTAL_ACTIVE)
930 : 144 : continue;
931 : :
932 : : /*
933 : : * Do nothing to cursors held over from a previous transaction or
934 : : * auto-held ones.
935 : : */
3167 936 [ + + - + ]: 21396 : if (portal->createSubid == InvalidSubTransactionId || portal->autoHeld)
937 : : {
8153 tgl@sss.pgh.pa.us 938 [ - + ]: 248 : Assert(portal->status != PORTAL_ACTIVE);
939 [ - + ]: 248 : Assert(portal->resowner == NULL);
8611 940 : 248 : continue;
941 : : }
942 : :
943 : : /*
944 : : * If a portal is still pinned, forcibly unpin it. PortalDrop will not
945 : : * let us drop the portal otherwise. Whoever pinned the portal was
946 : : * interrupted by the abort too and won't try to use it anymore.
947 : : */
5990 heikki.linnakangas@i 948 [ + + ]: 21148 : if (portal->portalPinned)
949 : 27 : portal->portalPinned = false;
950 : :
951 : : /*
952 : : * We had better not call any user-defined code during cleanup, so if
953 : : * the cleanup hook hasn't been run yet, too bad; we'll just skip it.
954 : : */
430 peter@eisentraut.org 955 [ - + ]: 21148 : if (portal->cleanup)
956 : : {
3393 tgl@sss.pgh.pa.us 957 [ # # ]:UBC 0 : elog(WARNING, "skipping cleanup for portal \"%s\"", portal->name);
958 : 0 : portal->cleanup = NULL;
959 : : }
960 : :
961 : : /* Zap it. */
8169 tgl@sss.pgh.pa.us 962 :CBC 21148 : PortalDrop(portal, false);
963 : : }
8611 964 : 37262 : }
965 : :
966 : : /*
967 : : * Portal-related cleanup when we return to the main loop on error.
968 : : *
969 : : * This is different from the cleanup at transaction abort. Auto-held portals
970 : : * are cleaned up on error but not on transaction abort.
971 : : *
972 : : * If an error happened while a portal was being set up and the transaction
973 : : * is already aborted, whoever was setting up the portal is gone, so mark it
974 : : * as droppable.
975 : : */
976 : : void
3167 peter_e@gmx.net 977 : 32106 : PortalErrorCleanup(void)
978 : : {
979 : : HASH_SEQ_STATUS status;
980 : : PortalHashEnt *hentry;
981 : :
982 : 32106 : hash_seq_init(&status, PortalHashTable);
983 : :
984 [ + + ]: 34531 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
985 : : {
986 : 2425 : Portal portal = hentry->portal;
987 : :
988 [ + + ]: 2425 : if (portal->autoHeld)
989 : : {
990 : 18 : portal->portalPinned = false;
991 : 18 : PortalDrop(portal, false);
992 : : }
19 michael@paquier.xyz 993 [ + + ]: 2407 : else if (portal->status == PORTAL_NEW ||
994 [ + + ]: 2405 : portal->status == PORTAL_DEFINED)
995 : : {
996 : 4 : portal->portalPinned = false;
997 : 4 : MarkPortalFailed(portal);
998 : : }
999 : : }
3167 peter_e@gmx.net 1000 : 32106 : }
1001 : :
1002 : : /*
1003 : : * Pre-subcommit processing for portals.
1004 : : *
1005 : : * Reassign portals created or used in the current subtransaction to the
1006 : : * parent subtransaction.
1007 : : */
1008 : : void
8108 tgl@sss.pgh.pa.us 1009 : 17424 : AtSubCommit_Portals(SubTransactionId mySubid,
1010 : : SubTransactionId parentSubid,
1011 : : int parentLevel,
1012 : : ResourceOwner parentXactOwner)
1013 : : {
1014 : : HASH_SEQ_STATUS status;
1015 : : PortalHashEnt *hentry;
1016 : :
8185 1017 : 17424 : hash_seq_init(&status, PortalHashTable);
1018 : :
1019 [ + + ]: 51539 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1020 : : {
8126 bruce@momjian.us 1021 : 16691 : Portal portal = hentry->portal;
1022 : :
8108 tgl@sss.pgh.pa.us 1023 [ + + ]: 16691 : if (portal->createSubid == mySubid)
1024 : : {
1025 : 30 : portal->createSubid = parentSubid;
1884 1026 : 30 : portal->createLevel = parentLevel;
8169 1027 [ + - ]: 30 : if (portal->resowner)
1028 : 30 : ResourceOwnerNewParent(portal->resowner, parentXactOwner);
1029 : : }
4103 1030 [ + + ]: 16691 : if (portal->activeSubid == mySubid)
1031 : 111 : portal->activeSubid = parentSubid;
1032 : : }
8185 1033 : 17424 : }
1034 : :
1035 : : /*
1036 : : * Subtransaction abort handling for portals.
1037 : : *
1038 : : * Deactivate portals created or used during the failed subtransaction.
1039 : : * Note that per AtSubCommit_Portals, this will catch portals created/used
1040 : : * in descendants of the subtransaction too.
1041 : : *
1042 : : * We don't destroy any portals here; that's done in AtSubCleanup_Portals.
1043 : : */
1044 : : void
8108 1045 : 5720 : AtSubAbort_Portals(SubTransactionId mySubid,
1046 : : SubTransactionId parentSubid,
1047 : : ResourceOwner myXactOwner,
1048 : : ResourceOwner parentXactOwner)
1049 : : {
1050 : : HASH_SEQ_STATUS status;
1051 : : PortalHashEnt *hentry;
1052 : :
8185 1053 : 5720 : hash_seq_init(&status, PortalHashTable);
1054 : :
1055 [ + + ]: 14268 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1056 : : {
8126 bruce@momjian.us 1057 : 8548 : Portal portal = hentry->portal;
1058 : :
1059 : : /* Was it created in this subtransaction? */
8108 tgl@sss.pgh.pa.us 1060 [ + + ]: 8548 : if (portal->createSubid != mySubid)
1061 : : {
1062 : : /* No, but maybe it was used in this subtransaction? */
4103 1063 [ + + ]: 7618 : if (portal->activeSubid == mySubid)
1064 : : {
1065 : : /* Maintain activeSubid until the portal is removed */
1066 : 57 : portal->activeSubid = parentSubid;
1067 : :
1068 : : /*
1069 : : * A MarkPortalActive() caller ran an upper-level portal in
1070 : : * this subtransaction and left the portal ACTIVE. This can't
1071 : : * happen, but force the portal into FAILED state for the same
1072 : : * reasons discussed below.
1073 : : *
1074 : : * We assume we can get away without forcing upper-level READY
1075 : : * portals to fail, even if they were run and then suspended.
1076 : : * In theory a suspended upper-level portal could have
1077 : : * acquired some references to objects that are about to be
1078 : : * destroyed, but there should be sufficient defenses against
1079 : : * such cases: the portal's original query cannot contain such
1080 : : * references, and any references within, say, cached plans of
1081 : : * PL/pgSQL functions are not from active queries and should
1082 : : * be protected by revalidation logic.
1083 : : */
1084 [ - + ]: 57 : if (portal->status == PORTAL_ACTIVE)
4103 tgl@sss.pgh.pa.us 1085 :UBC 0 : MarkPortalFailed(portal);
1086 : :
1087 : : /*
1088 : : * Also, if we failed it during the current subtransaction
1089 : : * (either just above, or earlier), reattach its resource
1090 : : * owner to the current subtransaction's resource owner, so
1091 : : * that any resources it still holds will be released while
1092 : : * cleaning up this subtransaction. This prevents some corner
1093 : : * cases wherein we might get Asserts or worse while cleaning
1094 : : * up objects created during the current subtransaction
1095 : : * (because they're still referenced within this portal).
1096 : : */
4103 tgl@sss.pgh.pa.us 1097 [ + + + - ]:CBC 57 : if (portal->status == PORTAL_FAILED && portal->resowner)
1098 : : {
1099 : 9 : ResourceOwnerNewParent(portal->resowner, myXactOwner);
1100 : 9 : portal->resowner = NULL;
1101 : : }
1102 : : }
1103 : : /* Done if it wasn't created in this subtransaction */
8185 1104 : 7618 : continue;
1105 : : }
1106 : :
1107 : : /*
1108 : : * Force any live portals of my own subtransaction into FAILED state.
1109 : : * We have to do this because they might refer to objects created or
1110 : : * changed in the failed subtransaction, leading to crashes within
1111 : : * ExecutorEnd when portalcmds.c tries to close down the portal.
1112 : : * Currently, every MarkPortalActive() caller ensures it updates the
1113 : : * portal status again before relinquishing control, so ACTIVE can't
1114 : : * happen here. If it does happen, dispose the portal like existing
1115 : : * MarkPortalActive() callers would.
1116 : : */
19 michael@paquier.xyz 1117 [ + - ]: 930 : if (portal->status == PORTAL_NEW ||
1118 [ + + ]: 930 : portal->status == PORTAL_DEFINED ||
1119 [ + + ]: 926 : portal->status == PORTAL_READY ||
6127 tgl@sss.pgh.pa.us 1120 [ - + ]: 243 : portal->status == PORTAL_ACTIVE)
5400 1121 : 687 : MarkPortalFailed(portal);
1122 : :
1123 : : /*
1124 : : * Allow portalcmds.c to clean up the state it knows about, if we
1125 : : * haven't already.
1126 : : */
430 peter@eisentraut.org 1127 [ - + ]: 930 : if (portal->cleanup)
1128 : : {
3369 peter_e@gmx.net 1129 :UBC 0 : portal->cleanup(portal);
6127 tgl@sss.pgh.pa.us 1130 : 0 : portal->cleanup = NULL;
1131 : : }
1132 : :
1133 : : /* drop cached plan reference, if any */
6127 tgl@sss.pgh.pa.us 1134 :CBC 930 : PortalReleaseCachedPlan(portal);
1135 : :
1136 : : /*
1137 : : * Any resources belonging to the portal will be released in the
1138 : : * upcoming transaction-wide cleanup; they will be gone before we run
1139 : : * PortalDrop.
1140 : : */
1141 : 930 : portal->resowner = NULL;
1142 : :
1143 : : /*
1144 : : * Although we can't delete the portal data structure proper, we can
1145 : : * release any memory in subsidiary contexts, such as executor state.
1146 : : * The cleanup hook was the last thing that might have needed data
1147 : : * there.
1148 : : */
3269 peter_e@gmx.net 1149 : 930 : MemoryContextDeleteChildren(portal->portalContext);
1150 : : }
8185 tgl@sss.pgh.pa.us 1151 : 5720 : }
1152 : :
1153 : : /*
1154 : : * Post-subabort cleanup for portals.
1155 : : *
1156 : : * Drop all portals created in the failed subtransaction (but note that
1157 : : * we will not drop any that were reassigned to the parent above).
1158 : : */
1159 : : void
8108 1160 : 5720 : AtSubCleanup_Portals(SubTransactionId mySubid)
1161 : : {
1162 : : HASH_SEQ_STATUS status;
1163 : : PortalHashEnt *hentry;
1164 : :
8185 1165 : 5720 : hash_seq_init(&status, PortalHashTable);
1166 : :
1167 [ + + ]: 14034 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1168 : : {
1169 : 8314 : Portal portal = hentry->portal;
1170 : :
8108 1171 [ + + ]: 8314 : if (portal->createSubid != mySubid)
8185 1172 : 7618 : continue;
1173 : :
1174 : : /*
1175 : : * If a portal is still pinned, forcibly unpin it. PortalDrop will not
1176 : : * let us drop the portal otherwise. Whoever pinned the portal was
1177 : : * interrupted by the abort too and won't try to use it anymore.
1178 : : */
5982 heikki.linnakangas@i 1179 [ + + ]: 696 : if (portal->portalPinned)
1180 : 3 : portal->portalPinned = false;
1181 : :
1182 : : /*
1183 : : * We had better not call any user-defined code during cleanup, so if
1184 : : * the cleanup hook hasn't been run yet, too bad; we'll just skip it.
1185 : : */
430 peter@eisentraut.org 1186 [ - + ]: 696 : if (portal->cleanup)
1187 : : {
3393 tgl@sss.pgh.pa.us 1188 [ # # ]:UBC 0 : elog(WARNING, "skipping cleanup for portal \"%s\"", portal->name);
1189 : 0 : portal->cleanup = NULL;
1190 : : }
1191 : :
1192 : : /* Zap it. */
8169 tgl@sss.pgh.pa.us 1193 :CBC 696 : PortalDrop(portal, false);
1194 : : }
8185 1195 : 5720 : }
1196 : :
1197 : : /* Find all available cursors */
1198 : : Datum
7619 neilc@samurai.com 1199 : 169 : pg_cursor(PG_FUNCTION_ARGS)
1200 : : {
7156 tgl@sss.pgh.pa.us 1201 : 169 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1202 : : HASH_SEQ_STATUS hash_seq;
1203 : : PortalHashEnt *hentry;
1204 : :
1205 : : /*
1206 : : * We put all the tuples into a tuplestore in one scan of the hashtable.
1207 : : * This avoids any issue of the hashtable possibly changing between calls.
1208 : : */
1502 michael@paquier.xyz 1209 : 169 : InitMaterializedSRF(fcinfo, 0);
1210 : :
7156 tgl@sss.pgh.pa.us 1211 : 169 : hash_seq_init(&hash_seq, PortalHashTable);
1212 [ + + ]: 458 : while ((hentry = hash_seq_search(&hash_seq)) != NULL)
1213 : : {
1214 : 289 : Portal portal = hentry->portal;
1215 : : Datum values[6];
1596 peter@eisentraut.org 1216 : 289 : bool nulls[6] = {0};
1217 : :
1218 : : /* report only "visible" entries */
7156 tgl@sss.pgh.pa.us 1219 [ + + ]: 289 : if (!portal->visible)
1220 : 149 : continue;
1221 : : /* also ignore it if PortalDefineQuery hasn't been called yet */
783 1222 [ + + ]: 170 : if (!portal->sourceText)
1223 : 30 : continue;
1224 : :
6822 1225 : 140 : values[0] = CStringGetTextDatum(portal->name);
6707 1226 : 140 : values[1] = CStringGetTextDatum(portal->sourceText);
7619 neilc@samurai.com 1227 : 140 : values[2] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_HOLD);
1228 : 140 : values[3] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_BINARY);
1229 : 140 : values[4] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_SCROLL);
1230 : 140 : values[5] = TimestampTzGetDatum(portal->creation_time);
1231 : :
1727 michael@paquier.xyz 1232 : 140 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1233 : : }
1234 : :
7156 tgl@sss.pgh.pa.us 1235 : 169 : return (Datum) 0;
1236 : : }
1237 : :
1238 : : bool
5110 simon@2ndQuadrant.co 1239 : 38 : ThereAreNoReadyPortals(void)
1240 : : {
1241 : : HASH_SEQ_STATUS status;
1242 : : PortalHashEnt *hentry;
1243 : :
1244 : 38 : hash_seq_init(&status, PortalHashTable);
1245 : :
1246 [ + + ]: 76 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1247 : : {
1248 : 38 : Portal portal = hentry->portal;
1249 : :
1250 [ - + ]: 38 : if (portal->status == PORTAL_READY)
1251 : : {
107 heikki.linnakangas@i 1252 :UNC 0 : hash_seq_term(&status);
5110 simon@2ndQuadrant.co 1253 :UBC 0 : return false;
1254 : : }
1255 : : }
1256 : :
5110 simon@2ndQuadrant.co 1257 :CBC 38 : return true;
1258 : : }
1259 : :
1260 : : /*
1261 : : * Hold all pinned portals.
1262 : : *
1263 : : * When initiating a COMMIT or ROLLBACK inside a procedure, this must be
1264 : : * called to protect internally-generated cursors from being dropped during
1265 : : * the transaction shutdown. Currently, SPI calls this automatically; PLs
1266 : : * that initiate COMMIT or ROLLBACK some other way are on the hook to do it
1267 : : * themselves. (Note that we couldn't do this in, say, AtAbort_Portals
1268 : : * because we need to run user-defined code while persisting a portal.
1269 : : * It's too late to do that once transaction abort has started.)
1270 : : *
1271 : : * We protect such portals by converting them to held cursors. We mark them
1272 : : * as "auto-held" so that exception exit knows to clean them up. (In normal,
1273 : : * non-exception code paths, the PL needs to clean such portals itself, since
1274 : : * transaction end won't do it anymore; but that should be normal practice
1275 : : * anyway.)
1276 : : */
1277 : : void
3167 peter_e@gmx.net 1278 : 2340 : HoldPinnedPortals(void)
1279 : : {
1280 : : HASH_SEQ_STATUS status;
1281 : : PortalHashEnt *hentry;
1282 : :
3232 1283 : 2340 : hash_seq_init(&status, PortalHashTable);
1284 : :
1285 [ + + ]: 4756 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1286 : : {
1287 : 2419 : Portal portal = hentry->portal;
1288 : :
3167 1289 [ + + + + ]: 2419 : if (portal->portalPinned && !portal->autoHeld)
1290 : : {
1291 : : /*
1292 : : * Doing transaction control, especially abort, inside a cursor
1293 : : * loop that is not read-only, for example using UPDATE ...
1294 : : * RETURNING, has weird semantics issues. Also, this
1295 : : * implementation wouldn't work, because such portals cannot be
1296 : : * held. (The core grammar enforces that only SELECT statements
1297 : : * can drive a cursor, but for example PL/pgSQL does not restrict
1298 : : * it.)
1299 : : */
1300 [ + + ]: 35 : if (portal->strategy != PORTAL_ONE_SELECT)
1301 [ + - ]: 1 : ereport(ERROR,
1302 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1303 : : errmsg("cannot perform transaction commands inside a cursor loop that is not read-only")));
1304 : :
1305 : : /* Verify it's in a suitable state to be held */
2780 tgl@sss.pgh.pa.us 1306 [ - + ]: 34 : if (portal->status != PORTAL_READY)
2780 tgl@sss.pgh.pa.us 1307 [ # # ]:UBC 0 : elog(ERROR, "pinned portal is not ready to be auto-held");
1308 : :
3167 peter_e@gmx.net 1309 :CBC 34 : HoldPortal(portal);
2780 tgl@sss.pgh.pa.us 1310 : 32 : portal->autoHeld = true;
1311 : : }
1312 : : }
3232 peter_e@gmx.net 1313 : 2337 : }
1314 : :
1315 : : /*
1316 : : * Drop the outer active snapshots for all portals, so that no snapshots
1317 : : * remain active.
1318 : : *
1319 : : * Like HoldPinnedPortals, this must be called when initiating a COMMIT or
1320 : : * ROLLBACK inside a procedure. This has to be separate from that since it
1321 : : * should not be run until we're done with steps that are likely to fail.
1322 : : *
1323 : : * It's tempting to fold this into PreCommit_Portals, but to do so, we'd
1324 : : * need to clean up snapshot management in VACUUM and perhaps other places.
1325 : : */
1326 : : void
2017 tgl@sss.pgh.pa.us 1327 : 2337 : ForgetPortalSnapshots(void)
1328 : : {
1329 : : HASH_SEQ_STATUS status;
1330 : : PortalHashEnt *hentry;
1331 : 2337 : int numPortalSnaps = 0;
1332 : 2337 : int numActiveSnaps = 0;
1333 : :
1334 : : /* First, scan PortalHashTable and clear portalSnapshot fields */
1335 : 2337 : hash_seq_init(&status, PortalHashTable);
1336 : :
1337 [ + + ]: 7090 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1338 : : {
1339 : 2416 : Portal portal = hentry->portal;
1340 : :
1341 [ + + ]: 2416 : if (portal->portalSnapshot != NULL)
1342 : : {
1343 : 2337 : portal->portalSnapshot = NULL;
1344 : 2337 : numPortalSnaps++;
1345 : : }
1346 : : /* portal->holdSnapshot will be cleaned up in PreCommit_Portals */
1347 : : }
1348 : :
1349 : : /*
1350 : : * Now, pop all the active snapshots, which should be just those that were
1351 : : * portal snapshots. Ideally we'd drive this directly off the portal
1352 : : * scan, but there's no good way to visit the portals in the correct
1353 : : * order. So just cross-check after the fact.
1354 : : */
1355 [ + + ]: 4674 : while (ActiveSnapshotSet())
1356 : : {
1357 : 2337 : PopActiveSnapshot();
1358 : 2337 : numActiveSnaps++;
1359 : : }
1360 : :
1361 [ - + ]: 2337 : if (numPortalSnaps != numActiveSnaps)
2017 tgl@sss.pgh.pa.us 1362 [ # # ]:UBC 0 : elog(ERROR, "portal snapshots (%d) did not account for all active snapshots (%d)",
1363 : : numPortalSnaps, numActiveSnaps);
2017 tgl@sss.pgh.pa.us 1364 :CBC 2337 : }
|