Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * xact.c
4 : : * top level transaction system support routines
5 : : *
6 : : * See src/backend/access/transam/README for more information.
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : * Portions Copyright (c) 1994, Regents of the University of California
10 : : *
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/access/transam/xact.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : :
18 : : #include "postgres.h"
19 : :
20 : : #include <time.h>
21 : : #include <unistd.h>
22 : :
23 : : #include "access/commit_ts.h"
24 : : #include "access/multixact.h"
25 : : #include "access/parallel.h"
26 : : #include "access/subtrans.h"
27 : : #include "access/transam.h"
28 : : #include "access/twophase.h"
29 : : #include "access/xact.h"
30 : : #include "access/xlog.h"
31 : : #include "access/xloginsert.h"
32 : : #include "access/xlogrecovery.h"
33 : : #include "access/xlogutils.h"
34 : : #include "access/xlogwait.h"
35 : : #include "catalog/index.h"
36 : : #include "catalog/namespace.h"
37 : : #include "catalog/pg_enum.h"
38 : : #include "catalog/storage.h"
39 : : #include "commands/async.h"
40 : : #include "commands/tablecmds.h"
41 : : #include "commands/trigger.h"
42 : : #include "common/pg_prng.h"
43 : : #include "executor/spi.h"
44 : : #include "libpq/be-fsstubs.h"
45 : : #include "libpq/pqsignal.h"
46 : : #include "miscadmin.h"
47 : : #include "pg_trace.h"
48 : : #include "pgstat.h"
49 : : #include "replication/logical.h"
50 : : #include "replication/logicallauncher.h"
51 : : #include "replication/logicalworker.h"
52 : : #include "replication/origin.h"
53 : : #include "replication/snapbuild.h"
54 : : #include "replication/syncrep.h"
55 : : #include "storage/aio_subsys.h"
56 : : #include "storage/condition_variable.h"
57 : : #include "storage/fd.h"
58 : : #include "storage/lmgr.h"
59 : : #include "storage/md.h"
60 : : #include "storage/predicate.h"
61 : : #include "storage/proc.h"
62 : : #include "storage/procarray.h"
63 : : #include "storage/sinvaladt.h"
64 : : #include "storage/smgr.h"
65 : : #include "utils/builtins.h"
66 : : #include "utils/combocid.h"
67 : : #include "utils/guc.h"
68 : : #include "utils/inval.h"
69 : : #include "utils/memutils.h"
70 : : #include "utils/relmapper.h"
71 : : #include "utils/snapmgr.h"
72 : : #include "utils/timeout.h"
73 : : #include "utils/timestamp.h"
74 : : #include "utils/typcache.h"
75 : : #include "utils/wait_event.h"
76 : :
77 : : /*
78 : : * User-tweakable parameters
79 : : */
80 : : int DefaultXactIsoLevel = XACT_READ_COMMITTED;
81 : : int XactIsoLevel = XACT_READ_COMMITTED;
82 : :
83 : : bool DefaultXactReadOnly = false;
84 : : bool XactReadOnly;
85 : :
86 : : bool DefaultXactDeferrable = false;
87 : : bool XactDeferrable;
88 : :
89 : : int synchronous_commit = SYNCHRONOUS_COMMIT_ON;
90 : :
91 : : /*
92 : : * CheckXidAlive is a xid value pointing to a possibly ongoing (sub)
93 : : * transaction. Currently, it is used in logical decoding. It's possible
94 : : * that such transactions can get aborted while the decoding is ongoing in
95 : : * which case we skip decoding that particular transaction. To ensure that we
96 : : * check whether the CheckXidAlive is aborted after fetching the tuple from
97 : : * system tables. We also ensure that during logical decoding we never
98 : : * directly access the tableam or heap APIs because we are checking for the
99 : : * concurrent aborts only in systable_* APIs.
100 : : */
101 : : TransactionId CheckXidAlive = InvalidTransactionId;
102 : : bool bsysscan = false;
103 : :
104 : : /*
105 : : * When running as a parallel worker, we place only a single
106 : : * TransactionStateData on the parallel worker's state stack, and the XID
107 : : * reflected there will be that of the *innermost* currently-active
108 : : * subtransaction in the backend that initiated parallelism. However,
109 : : * GetTopTransactionId() and TransactionIdIsCurrentTransactionId()
110 : : * need to return the same answers in the parallel worker as they would have
111 : : * in the user backend, so we need some additional bookkeeping.
112 : : *
113 : : * XactTopFullTransactionId stores the XID of our toplevel transaction, which
114 : : * will be the same as TopTransactionStateData.fullTransactionId in an
115 : : * ordinary backend; but in a parallel backend, which does not have the entire
116 : : * transaction state, it will instead be copied from the backend that started
117 : : * the parallel operation.
118 : : *
119 : : * nParallelCurrentXids will be 0 and ParallelCurrentXids NULL in an ordinary
120 : : * backend, but in a parallel backend, nParallelCurrentXids will contain the
121 : : * number of XIDs that need to be considered current, and ParallelCurrentXids
122 : : * will contain the XIDs themselves. This includes all XIDs that were current
123 : : * or sub-committed in the parent at the time the parallel operation began.
124 : : * The XIDs are stored sorted in numerical order (not logical order) to make
125 : : * lookups as fast as possible.
126 : : */
127 : : static FullTransactionId XactTopFullTransactionId = {InvalidTransactionId};
128 : : static int nParallelCurrentXids = 0;
129 : : static TransactionId *ParallelCurrentXids;
130 : :
131 : : /*
132 : : * Miscellaneous flag bits to record events which occur on the top level
133 : : * transaction. These flags are only persisted in MyXactFlags and are intended
134 : : * so we remember to do certain things later on in the transaction. This is
135 : : * globally accessible, so can be set from anywhere in the code that requires
136 : : * recording flags.
137 : : */
138 : : int MyXactFlags;
139 : :
140 : : /*
141 : : * transaction states - transaction state from server perspective
142 : : */
143 : : typedef enum TransState
144 : : {
145 : : TRANS_DEFAULT, /* idle */
146 : : TRANS_START, /* transaction starting */
147 : : TRANS_INPROGRESS, /* inside a valid transaction */
148 : : TRANS_COMMIT, /* commit in progress */
149 : : TRANS_ABORT, /* abort in progress */
150 : : TRANS_PREPARE, /* prepare in progress */
151 : : } TransState;
152 : :
153 : : /*
154 : : * transaction block states - transaction state of client queries
155 : : *
156 : : * Note: the subtransaction states are used only for non-topmost
157 : : * transactions; the others appear only in the topmost transaction.
158 : : */
159 : : typedef enum TBlockState
160 : : {
161 : : /* not-in-transaction-block states */
162 : : TBLOCK_DEFAULT, /* idle */
163 : : TBLOCK_STARTED, /* running single-query transaction */
164 : :
165 : : /* transaction block states */
166 : : TBLOCK_BEGIN, /* starting transaction block */
167 : : TBLOCK_INPROGRESS, /* live transaction */
168 : : TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
169 : : TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
170 : : TBLOCK_END, /* COMMIT received */
171 : : TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
172 : : TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
173 : : TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
174 : : TBLOCK_PREPARE, /* live xact, PREPARE received */
175 : :
176 : : /* subtransaction states */
177 : : TBLOCK_SUBBEGIN, /* starting a subtransaction */
178 : : TBLOCK_SUBINPROGRESS, /* live subtransaction */
179 : : TBLOCK_SUBRELEASE, /* RELEASE received */
180 : : TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
181 : : TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
182 : : TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
183 : : TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
184 : : TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
185 : : TBLOCK_SUBABORT_RESTART, /* failed subxact, ROLLBACK TO received */
186 : : } TBlockState;
187 : :
188 : : /*
189 : : * transaction state structure
190 : : *
191 : : * Note: parallelModeLevel counts the number of unmatched EnterParallelMode
192 : : * calls done at this transaction level. parallelChildXact is true if any
193 : : * upper transaction level has nonzero parallelModeLevel.
194 : : */
195 : : typedef struct TransactionStateData
196 : : {
197 : : FullTransactionId fullTransactionId; /* my FullTransactionId */
198 : : SubTransactionId subTransactionId; /* my subxact ID */
199 : : char *name; /* savepoint name, if any */
200 : : int savepointLevel; /* savepoint level */
201 : : TransState state; /* low-level state */
202 : : TBlockState blockState; /* high-level state */
203 : : int nestingLevel; /* transaction nesting depth */
204 : : int gucNestLevel; /* GUC context nesting depth */
205 : : MemoryContext curTransactionContext; /* my xact-lifetime context */
206 : : ResourceOwner curTransactionOwner; /* my query resources */
207 : : MemoryContext priorContext; /* CurrentMemoryContext before xact started */
208 : : TransactionId *childXids; /* subcommitted child XIDs, in XID order */
209 : : int nChildXids; /* # of subcommitted child XIDs */
210 : : int maxChildXids; /* allocated size of childXids[] */
211 : : Oid prevUser; /* previous CurrentUserId setting */
212 : : int prevSecContext; /* previous SecurityRestrictionContext */
213 : : bool prevXactReadOnly; /* entry-time xact r/o state */
214 : : bool startedInRecovery; /* did we start in recovery? */
215 : : bool didLogXid; /* has xid been included in WAL record? */
216 : : int parallelModeLevel; /* Enter/ExitParallelMode counter */
217 : : bool parallelChildXact; /* is any parent transaction parallel? */
218 : : bool chain; /* start a new block after this one */
219 : : bool topXidLogged; /* for a subxact: is top-level XID logged? */
220 : : struct TransactionStateData *parent; /* back link to parent */
221 : : } TransactionStateData;
222 : :
223 : : typedef TransactionStateData *TransactionState;
224 : :
225 : : /*
226 : : * Serialized representation used to transmit transaction state to parallel
227 : : * workers through shared memory.
228 : : */
229 : : typedef struct SerializedTransactionState
230 : : {
231 : : int xactIsoLevel;
232 : : bool xactDeferrable;
233 : : FullTransactionId topFullTransactionId;
234 : : FullTransactionId currentFullTransactionId;
235 : : CommandId currentCommandId;
236 : : int nParallelCurrentXids;
237 : : TransactionId parallelCurrentXids[FLEXIBLE_ARRAY_MEMBER];
238 : : } SerializedTransactionState;
239 : :
240 : : /* The size of SerializedTransactionState, not including the final array. */
241 : : #define SerializedTransactionStateHeaderSize \
242 : : offsetof(SerializedTransactionState, parallelCurrentXids)
243 : :
244 : : /*
245 : : * CurrentTransactionState always points to the current transaction state
246 : : * block. It will point to TopTransactionStateData when not in a
247 : : * transaction at all, or when in a top-level transaction.
248 : : */
249 : : static TransactionStateData TopTransactionStateData = {
250 : : .state = TRANS_DEFAULT,
251 : : .blockState = TBLOCK_DEFAULT,
252 : : .topXidLogged = false,
253 : : };
254 : :
255 : : /*
256 : : * unreportedXids holds XIDs of all subtransactions that have not yet been
257 : : * reported in an XLOG_XACT_ASSIGNMENT record.
258 : : */
259 : : static int nUnreportedXids;
260 : : static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS];
261 : :
262 : : static TransactionState CurrentTransactionState = &TopTransactionStateData;
263 : :
264 : : /*
265 : : * The subtransaction ID and command ID assignment counters are global
266 : : * to a whole transaction, so we do not keep them in the state stack.
267 : : */
268 : : static SubTransactionId currentSubTransactionId;
269 : : static CommandId currentCommandId;
270 : : static bool currentCommandIdUsed;
271 : :
272 : : /*
273 : : * xactStartTimestamp is the value of transaction_timestamp().
274 : : * stmtStartTimestamp is the value of statement_timestamp().
275 : : * xactStopTimestamp is the time at which we log a commit / abort WAL record,
276 : : * or if that was skipped, the time of the first subsequent
277 : : * GetCurrentTransactionStopTimestamp() call.
278 : : *
279 : : * These do not change as we enter and exit subtransactions, so we don't
280 : : * keep them inside the TransactionState stack.
281 : : */
282 : : static TimestampTz xactStartTimestamp;
283 : : static TimestampTz stmtStartTimestamp;
284 : : static TimestampTz xactStopTimestamp;
285 : :
286 : : /*
287 : : * GID to be used for preparing the current transaction. This is also
288 : : * global to a whole transaction, so we don't keep it in the state stack.
289 : : */
290 : : static char *prepareGID;
291 : :
292 : : /*
293 : : * Some commands want to force synchronous commit.
294 : : */
295 : : static bool forceSyncCommit = false;
296 : :
297 : : /* Flag for logging statements in a transaction. */
298 : : bool xact_is_sampled = false;
299 : :
300 : : /*
301 : : * Private context for transaction-abort work --- we reserve space for this
302 : : * at startup to ensure that AbortTransaction and AbortSubTransaction can work
303 : : * when we've run out of memory.
304 : : */
305 : : static MemoryContext TransactionAbortContext = NULL;
306 : :
307 : : /*
308 : : * List of add-on start- and end-of-xact callbacks
309 : : */
310 : : typedef struct XactCallbackItem
311 : : {
312 : : struct XactCallbackItem *next;
313 : : XactCallback callback;
314 : : void *arg;
315 : : } XactCallbackItem;
316 : :
317 : : static XactCallbackItem *Xact_callbacks = NULL;
318 : :
319 : : /*
320 : : * List of add-on start- and end-of-subxact callbacks
321 : : */
322 : : typedef struct SubXactCallbackItem
323 : : {
324 : : struct SubXactCallbackItem *next;
325 : : SubXactCallback callback;
326 : : void *arg;
327 : : } SubXactCallbackItem;
328 : :
329 : : static SubXactCallbackItem *SubXact_callbacks = NULL;
330 : :
331 : :
332 : : /* local function prototypes */
333 : : static void AssignTransactionId(TransactionState s);
334 : : static void AbortTransaction(void);
335 : : static void AtAbort_Memory(void);
336 : : static void AtCleanup_Memory(void);
337 : : static void AtAbort_ResourceOwner(void);
338 : : static void AtCCI_LocalCache(void);
339 : : static void AtCommit_Memory(void);
340 : : static void AtStart_Cache(void);
341 : : static void AtStart_Memory(void);
342 : : static void AtStart_ResourceOwner(void);
343 : : static void CallXactCallbacks(XactEvent event);
344 : : static void CallSubXactCallbacks(SubXactEvent event,
345 : : SubTransactionId mySubid,
346 : : SubTransactionId parentSubid);
347 : : static void CleanupTransaction(void);
348 : : static void CheckTransactionBlock(bool isTopLevel, bool throwError,
349 : : const char *stmtType);
350 : : static void CommitTransaction(void);
351 : : static TransactionId RecordTransactionAbort(bool isSubXact);
352 : : static void StartTransaction(void);
353 : :
354 : : static bool CommitTransactionCommandInternal(void);
355 : : static bool AbortCurrentTransactionInternal(void);
356 : :
357 : : static void StartSubTransaction(void);
358 : : static void CommitSubTransaction(void);
359 : : static void AbortSubTransaction(void);
360 : : static void CleanupSubTransaction(void);
361 : : static void PushTransaction(void);
362 : : static void PopTransaction(void);
363 : :
364 : : static void AtSubAbort_Memory(void);
365 : : static void AtSubCleanup_Memory(void);
366 : : static void AtSubAbort_ResourceOwner(void);
367 : : static void AtSubCommit_Memory(void);
368 : : static void AtSubStart_Memory(void);
369 : : static void AtSubStart_ResourceOwner(void);
370 : :
371 : : static void ShowTransactionState(const char *str);
372 : : static void ShowTransactionStateRec(const char *str, TransactionState s);
373 : : static const char *BlockStateAsString(TBlockState blockState);
374 : : static const char *TransStateAsString(TransState state);
375 : :
376 : :
377 : : /* ----------------------------------------------------------------
378 : : * transaction state accessors
379 : : * ----------------------------------------------------------------
380 : : */
381 : :
382 : : /*
383 : : * IsTransactionState
384 : : *
385 : : * This returns true if we are inside a valid transaction; that is,
386 : : * it is safe to initiate database access, take heavyweight locks, etc.
387 : : */
388 : : bool
389 : 1252472 : IsTransactionState(void)
390 : : {
391 : 1252472 : TransactionState s = CurrentTransactionState;
392 : :
393 : : /*
394 : : * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
395 : : * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
396 : : * TRANS_PREPARE since it might be too soon or too late within those
397 : : * transition states to do anything interesting. Hence, the only "valid"
398 : : * state is TRANS_INPROGRESS.
399 : : */
400 : 1252472 : return (s->state == TRANS_INPROGRESS);
401 : : }
402 : :
403 : : /*
404 : : * IsAbortedTransactionBlockState
405 : : *
406 : : * This returns true if we are within an aborted transaction block.
407 : : */
408 : : bool
409 : 961247 : IsAbortedTransactionBlockState(void)
410 : : {
411 : 961247 : TransactionState s = CurrentTransactionState;
412 : :
413 [ + + ]: 961247 : if (s->blockState == TBLOCK_ABORT ||
414 [ + + ]: 959247 : s->blockState == TBLOCK_SUBABORT)
415 : 2398 : return true;
416 : :
417 : 958849 : return false;
418 : : }
419 : :
420 : :
421 : : /*
422 : : * GetTopTransactionId
423 : : *
424 : : * This will return the XID of the main transaction, assigning one if
425 : : * it's not yet set. Be careful to call this only inside a valid xact.
426 : : */
427 : : TransactionId
428 : 33916 : GetTopTransactionId(void)
429 : : {
430 [ + + ]: 33916 : if (!FullTransactionIdIsValid(XactTopFullTransactionId))
431 : 691 : AssignTransactionId(&TopTransactionStateData);
432 : 33916 : return XidFromFullTransactionId(XactTopFullTransactionId);
433 : : }
434 : :
435 : : /*
436 : : * GetTopTransactionIdIfAny
437 : : *
438 : : * This will return the XID of the main transaction, if one is assigned.
439 : : * It will return InvalidTransactionId if we are not currently inside a
440 : : * transaction, or inside a transaction that hasn't yet been assigned an XID.
441 : : */
442 : : TransactionId
443 : 65580863 : GetTopTransactionIdIfAny(void)
444 : : {
445 : 65580863 : return XidFromFullTransactionId(XactTopFullTransactionId);
446 : : }
447 : :
448 : : /*
449 : : * GetCurrentTransactionId
450 : : *
451 : : * This will return the XID of the current transaction (main or sub
452 : : * transaction), assigning one if it's not yet set. Be careful to call this
453 : : * only inside a valid xact.
454 : : */
455 : : TransactionId
456 : 17289383 : GetCurrentTransactionId(void)
457 : : {
458 : 17289383 : TransactionState s = CurrentTransactionState;
459 : :
460 [ + + ]: 17289383 : if (!FullTransactionIdIsValid(s->fullTransactionId))
461 : 180509 : AssignTransactionId(s);
462 : 17289376 : return XidFromFullTransactionId(s->fullTransactionId);
463 : : }
464 : :
465 : : /*
466 : : * GetCurrentTransactionIdIfAny
467 : : *
468 : : * This will return the XID of the current sub xact, if one is assigned.
469 : : * It will return InvalidTransactionId if we are not currently inside a
470 : : * transaction, or inside a transaction that hasn't been assigned an XID yet.
471 : : */
472 : : TransactionId
473 : 25395757 : GetCurrentTransactionIdIfAny(void)
474 : : {
475 : 25395757 : return XidFromFullTransactionId(CurrentTransactionState->fullTransactionId);
476 : : }
477 : :
478 : : /*
479 : : * GetTopFullTransactionId
480 : : *
481 : : * This will return the FullTransactionId of the main transaction, assigning
482 : : * one if it's not yet set. Be careful to call this only inside a valid xact.
483 : : */
484 : : FullTransactionId
485 : 3196 : GetTopFullTransactionId(void)
486 : : {
487 [ + + ]: 3196 : if (!FullTransactionIdIsValid(XactTopFullTransactionId))
488 : 2107 : AssignTransactionId(&TopTransactionStateData);
489 : 3196 : return XactTopFullTransactionId;
490 : : }
491 : :
492 : : /*
493 : : * GetTopFullTransactionIdIfAny
494 : : *
495 : : * This will return the FullTransactionId of the main transaction, if one is
496 : : * assigned. It will return InvalidFullTransactionId if we are not currently
497 : : * inside a transaction, or inside a transaction that hasn't yet been assigned
498 : : * one.
499 : : */
500 : : FullTransactionId
501 : 16 : GetTopFullTransactionIdIfAny(void)
502 : : {
503 : 16 : return XactTopFullTransactionId;
504 : : }
505 : :
506 : : /*
507 : : * GetCurrentFullTransactionId
508 : : *
509 : : * This will return the FullTransactionId of the current transaction (main or
510 : : * sub transaction), assigning one if it's not yet set. Be careful to call
511 : : * this only inside a valid xact.
512 : : */
513 : : FullTransactionId
514 : 384 : GetCurrentFullTransactionId(void)
515 : : {
516 : 384 : TransactionState s = CurrentTransactionState;
517 : :
518 [ + + ]: 384 : if (!FullTransactionIdIsValid(s->fullTransactionId))
519 : 14 : AssignTransactionId(s);
520 : 384 : return s->fullTransactionId;
521 : : }
522 : :
523 : : /*
524 : : * GetCurrentFullTransactionIdIfAny
525 : : *
526 : : * This will return the FullTransactionId of the current sub xact, if one is
527 : : * assigned. It will return InvalidFullTransactionId if we are not currently
528 : : * inside a transaction, or inside a transaction that hasn't been assigned one
529 : : * yet.
530 : : */
531 : : FullTransactionId
532 : 0 : GetCurrentFullTransactionIdIfAny(void)
533 : : {
534 : 0 : return CurrentTransactionState->fullTransactionId;
535 : : }
536 : :
537 : : /*
538 : : * MarkCurrentTransactionIdLoggedIfAny
539 : : *
540 : : * Remember that the current xid - if it is assigned - now has been wal logged.
541 : : */
542 : : void
543 : 25342097 : MarkCurrentTransactionIdLoggedIfAny(void)
544 : : {
545 [ + + ]: 25342097 : if (FullTransactionIdIsValid(CurrentTransactionState->fullTransactionId))
546 : 24971981 : CurrentTransactionState->didLogXid = true;
547 : 25342097 : }
548 : :
549 : : /*
550 : : * IsSubxactTopXidLogPending
551 : : *
552 : : * This is used to decide whether we need to WAL log the top-level XID for
553 : : * operation in a subtransaction. We require that for logical decoding, see
554 : : * LogicalDecodingProcessRecord.
555 : : *
556 : : * This returns true if effective_wal_level is logical and we are inside
557 : : * a valid subtransaction, for which the assignment was not yet written to
558 : : * any WAL record.
559 : : */
560 : : bool
561 : 25351206 : IsSubxactTopXidLogPending(void)
562 : : {
563 : : /* check whether it is already logged */
564 [ + + ]: 25351206 : if (CurrentTransactionState->topXidLogged)
565 : 102134 : return false;
566 : :
567 : : /* effective_wal_level has to be logical */
568 [ + + + + ]: 25249072 : if (!XLogLogicalInfoActive())
569 : 24652474 : return false;
570 : :
571 : : /* we need to be in a transaction state */
572 [ + + ]: 596598 : if (!IsTransactionState())
573 : 4359 : return false;
574 : :
575 : : /* it has to be a subtransaction */
576 [ + + ]: 592239 : if (!IsSubTransaction())
577 : 592005 : return false;
578 : :
579 : : /* the subtransaction has to have a XID assigned */
580 [ + + ]: 234 : if (!TransactionIdIsValid(GetCurrentTransactionIdIfAny()))
581 : 8 : return false;
582 : :
583 : 226 : return true;
584 : : }
585 : :
586 : : /*
587 : : * MarkSubxactTopXidLogged
588 : : *
589 : : * Remember that the top transaction id for the current subtransaction is WAL
590 : : * logged now.
591 : : */
592 : : void
593 : 224 : MarkSubxactTopXidLogged(void)
594 : : {
595 : : Assert(IsSubxactTopXidLogPending());
596 : :
597 : 224 : CurrentTransactionState->topXidLogged = true;
598 : 224 : }
599 : :
600 : : /*
601 : : * GetStableLatestTransactionId
602 : : *
603 : : * Get the transaction's XID if it has one, else read the next-to-be-assigned
604 : : * XID. Once we have a value, return that same value for the remainder of the
605 : : * current transaction. This is meant to provide the reference point for the
606 : : * age(xid) function, but might be useful for other maintenance tasks as well.
607 : : */
608 : : TransactionId
609 : 163 : GetStableLatestTransactionId(void)
610 : : {
611 : : static LocalTransactionId lxid = InvalidLocalTransactionId;
612 : : static TransactionId stablexid = InvalidTransactionId;
613 : :
614 [ + + ]: 163 : if (lxid != MyProc->vxid.lxid)
615 : : {
616 : 15 : lxid = MyProc->vxid.lxid;
617 : 15 : stablexid = GetTopTransactionIdIfAny();
618 [ + - ]: 15 : if (!TransactionIdIsValid(stablexid))
619 : 15 : stablexid = ReadNextTransactionId();
620 : : }
621 : :
622 : : Assert(TransactionIdIsValid(stablexid));
623 : :
624 : 163 : return stablexid;
625 : : }
626 : :
627 : : /*
628 : : * AssignTransactionId
629 : : *
630 : : * Assigns a new permanent FullTransactionId to the given TransactionState.
631 : : * We do not assign XIDs to transactions until/unless this is called.
632 : : * Also, any parent TransactionStates that don't yet have XIDs are assigned
633 : : * one; this maintains the invariant that a child transaction has an XID
634 : : * following its parent's.
635 : : */
636 : : static void
637 : 184542 : AssignTransactionId(TransactionState s)
638 : : {
639 : 184542 : bool isSubXact = (s->parent != NULL);
640 : : ResourceOwner currentOwner;
641 : 184542 : bool log_unknown_top = false;
642 : :
643 : : /* Assert that caller didn't screw up */
644 : : Assert(!FullTransactionIdIsValid(s->fullTransactionId));
645 : : Assert(s->state == TRANS_INPROGRESS);
646 : :
647 : : /*
648 : : * Workers synchronize transaction state at the beginning of each parallel
649 : : * operation, so we can't account for new XIDs at this point.
650 : : */
651 [ + - - + ]: 184542 : if (IsInParallelMode() || IsParallelWorker())
652 [ # # ]: 0 : ereport(ERROR,
653 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
654 : : errmsg("cannot assign transaction IDs during a parallel operation")));
655 : :
656 : : /*
657 : : * Ensure parent(s) have XIDs, so that a child always has an XID later
658 : : * than its parent. Mustn't recurse here, or we might get a stack
659 : : * overflow if we're at the bottom of a huge stack of subtransactions none
660 : : * of which have XIDs yet.
661 : : */
662 [ + + + + ]: 184542 : if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
663 : : {
664 : 628 : TransactionState p = s->parent;
665 : : TransactionState *parents;
666 : 628 : size_t parentOffset = 0;
667 : :
668 : 628 : parents = palloc_array(TransactionState, s->nestingLevel);
669 [ + + + + ]: 1849 : while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
670 : : {
671 : 1221 : parents[parentOffset++] = p;
672 : 1221 : p = p->parent;
673 : : }
674 : :
675 : : /*
676 : : * This is technically a recursive call, but the recursion will never
677 : : * be more than one layer deep.
678 : : */
679 [ + + ]: 1849 : while (parentOffset != 0)
680 : 1221 : AssignTransactionId(parents[--parentOffset]);
681 : :
682 : 628 : pfree(parents);
683 : : }
684 : :
685 : : /*
686 : : * When effective_wal_level is logical, guarantee that a subtransaction's
687 : : * xid can only be seen in the WAL stream if its toplevel xid has been
688 : : * logged before. If necessary we log an xact_assignment record with fewer
689 : : * than PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't
690 : : * set for a transaction even though it appears in a WAL record, we just
691 : : * might superfluously log something. That can happen when an xid is
692 : : * included somewhere inside a wal record, but not in XLogRecord->xl_xid,
693 : : * like in xl_standby_locks.
694 : : */
695 [ + + + + : 184542 : if (isSubXact && XLogLogicalInfoActive() &&
+ + ]
696 [ + + ]: 305 : !TopTransactionStateData.didLogXid)
697 : 26 : log_unknown_top = true;
698 : :
699 : : /*
700 : : * Generate a new FullTransactionId and record its xid in PGPROC and
701 : : * pg_subtrans.
702 : : *
703 : : * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
704 : : * shared storage other than PGPROC; because if there's no room for it in
705 : : * PGPROC, the subtrans entry is needed to ensure that other backends see
706 : : * the Xid as "running". See GetNewTransactionId.
707 : : */
708 : 184542 : s->fullTransactionId = GetNewTransactionId(isSubXact);
709 [ + + ]: 184535 : if (!isSubXact)
710 : 168195 : XactTopFullTransactionId = s->fullTransactionId;
711 : :
712 [ + + ]: 184535 : if (isSubXact)
713 : 16340 : SubTransSetParent(XidFromFullTransactionId(s->fullTransactionId),
714 : 16340 : XidFromFullTransactionId(s->parent->fullTransactionId));
715 : :
716 : : /*
717 : : * If it's a top-level transaction, the predicate locking system needs to
718 : : * be told about it too.
719 : : */
720 [ + + ]: 184535 : if (!isSubXact)
721 : 168195 : RegisterPredicateLockingXid(XidFromFullTransactionId(s->fullTransactionId));
722 : :
723 : : /*
724 : : * Acquire lock on the transaction XID. (We assume this cannot block.) We
725 : : * have to ensure that the lock is assigned to the transaction's own
726 : : * ResourceOwner.
727 : : */
728 : 184535 : currentOwner = CurrentResourceOwner;
729 : 184535 : CurrentResourceOwner = s->curTransactionOwner;
730 : :
731 : 184535 : XactLockTableInsert(XidFromFullTransactionId(s->fullTransactionId));
732 : :
733 : 184535 : CurrentResourceOwner = currentOwner;
734 : :
735 : : /*
736 : : * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
737 : : * top-level transaction we issue a WAL record for the assignment. We
738 : : * include the top-level xid and all the subxids that have not yet been
739 : : * reported using XLOG_XACT_ASSIGNMENT records.
740 : : *
741 : : * This is required to limit the amount of shared memory required in a hot
742 : : * standby server to keep track of in-progress XIDs. See notes for
743 : : * RecordKnownAssignedTransactionIds().
744 : : *
745 : : * We don't keep track of the immediate parent of each subxid, only the
746 : : * top-level transaction that each subxact belongs to. This is correct in
747 : : * recovery only because aborted subtransactions are separately WAL
748 : : * logged.
749 : : *
750 : : * This is correct even for the case where several levels above us didn't
751 : : * have an xid assigned as we recursed up to them beforehand.
752 : : */
753 [ + + + + ]: 184535 : if (isSubXact && XLogStandbyInfoActive())
754 : : {
755 : 16065 : unreportedXids[nUnreportedXids] = XidFromFullTransactionId(s->fullTransactionId);
756 : 16065 : nUnreportedXids++;
757 : :
758 : : /*
759 : : * ensure this test matches similar one in
760 : : * RecoverPreparedTransactions()
761 : : */
762 [ + + + + ]: 16065 : if (nUnreportedXids >= PGPROC_MAX_CACHED_SUBXIDS ||
763 : : log_unknown_top)
764 : : {
765 : : xl_xact_assignment xlrec;
766 : :
767 : : /*
768 : : * xtop is always set by now because we recurse up transaction
769 : : * stack to the highest unassigned xid and then come back down
770 : : */
771 : 252 : xlrec.xtop = GetTopTransactionId();
772 : : Assert(TransactionIdIsValid(xlrec.xtop));
773 : 252 : xlrec.nsubxacts = nUnreportedXids;
774 : :
775 : 252 : XLogBeginInsert();
776 : 252 : XLogRegisterData(&xlrec, MinSizeOfXactAssignment);
777 : 252 : XLogRegisterData(unreportedXids,
778 : : nUnreportedXids * sizeof(TransactionId));
779 : :
780 : 252 : (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
781 : :
782 : 252 : nUnreportedXids = 0;
783 : : /* mark top, not current xact as having been logged */
784 : 252 : TopTransactionStateData.didLogXid = true;
785 : : }
786 : : }
787 : 184535 : }
788 : :
789 : : /*
790 : : * GetCurrentSubTransactionId
791 : : */
792 : : SubTransactionId
793 : 9391425 : GetCurrentSubTransactionId(void)
794 : : {
795 : 9391425 : TransactionState s = CurrentTransactionState;
796 : :
797 : 9391425 : return s->subTransactionId;
798 : : }
799 : :
800 : : /*
801 : : * SubTransactionIsActive
802 : : *
803 : : * Test if the specified subxact ID is still active. Note caller is
804 : : * responsible for checking whether this ID is relevant to the current xact.
805 : : */
806 : : bool
807 : 0 : SubTransactionIsActive(SubTransactionId subxid)
808 : : {
809 : : TransactionState s;
810 : :
811 [ # # ]: 0 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
812 : : {
813 [ # # ]: 0 : if (s->state == TRANS_ABORT)
814 : 0 : continue;
815 [ # # ]: 0 : if (s->subTransactionId == subxid)
816 : 0 : return true;
817 : : }
818 : 0 : return false;
819 : : }
820 : :
821 : :
822 : : /*
823 : : * GetCurrentCommandId
824 : : *
825 : : * "used" must be true if the caller intends to use the command ID to mark
826 : : * inserted/updated/deleted tuples. false means the ID is being fetched
827 : : * for read-only purposes (ie, as a snapshot validity cutoff). See
828 : : * CommandCounterIncrement() for discussion.
829 : : */
830 : : CommandId
831 : 7897259 : GetCurrentCommandId(bool used)
832 : : {
833 : : /* this is global to a transaction, not subtransaction-local */
834 [ + + ]: 7897259 : if (used)
835 : : {
836 : : /*
837 : : * Forbid setting currentCommandIdUsed in a parallel worker, because
838 : : * we have no provision for communicating this back to the leader. We
839 : : * could relax this restriction when currentCommandIdUsed was already
840 : : * true at the start of the parallel operation.
841 : : */
842 [ - + ]: 4398393 : if (IsParallelWorker())
843 [ # # ]: 0 : ereport(ERROR,
844 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
845 : : errmsg("cannot modify data in a parallel worker")));
846 : :
847 : 4398393 : currentCommandIdUsed = true;
848 : : }
849 : 7897259 : return currentCommandId;
850 : : }
851 : :
852 : : /*
853 : : * SetParallelStartTimestamps
854 : : *
855 : : * In a parallel worker, we should inherit the parent transaction's
856 : : * timestamps rather than setting our own. The parallel worker
857 : : * infrastructure must call this to provide those values before
858 : : * calling StartTransaction() or SetCurrentStatementStartTimestamp().
859 : : */
860 : : void
861 : 2020 : SetParallelStartTimestamps(TimestampTz xact_ts, TimestampTz stmt_ts)
862 : : {
863 : : Assert(IsParallelWorker());
864 : 2020 : xactStartTimestamp = xact_ts;
865 : 2020 : stmtStartTimestamp = stmt_ts;
866 : 2020 : }
867 : :
868 : : /*
869 : : * GetCurrentTransactionStartTimestamp
870 : : */
871 : : TimestampTz
872 : 45382 : GetCurrentTransactionStartTimestamp(void)
873 : : {
874 : 45382 : return xactStartTimestamp;
875 : : }
876 : :
877 : : /*
878 : : * GetCurrentStatementStartTimestamp
879 : : */
880 : : TimestampTz
881 : 1544644 : GetCurrentStatementStartTimestamp(void)
882 : : {
883 : 1544644 : return stmtStartTimestamp;
884 : : }
885 : :
886 : : /*
887 : : * GetCurrentTransactionStopTimestamp
888 : : *
889 : : * If the transaction stop time hasn't already been set, which can happen if
890 : : * we decided we don't need to log an XLOG record, set xactStopTimestamp.
891 : : */
892 : : TimestampTz
893 : 1289423 : GetCurrentTransactionStopTimestamp(void)
894 : : {
895 : 1289423 : TransactionState s PG_USED_FOR_ASSERTS_ONLY = CurrentTransactionState;
896 : :
897 : : /* should only be called after commit / abort processing */
898 : : Assert(s->state == TRANS_DEFAULT ||
899 : : s->state == TRANS_COMMIT ||
900 : : s->state == TRANS_ABORT ||
901 : : s->state == TRANS_PREPARE);
902 : :
903 [ + + ]: 1289423 : if (xactStopTimestamp == 0)
904 : 382485 : xactStopTimestamp = GetCurrentTimestamp();
905 : :
906 : 1289423 : return xactStopTimestamp;
907 : : }
908 : :
909 : : /*
910 : : * SetCurrentStatementStartTimestamp
911 : : *
912 : : * In a parallel worker, this should already have been provided by a call
913 : : * to SetParallelStartTimestamps().
914 : : */
915 : : void
916 : 777721 : SetCurrentStatementStartTimestamp(void)
917 : : {
918 [ + + ]: 777721 : if (!IsParallelWorker())
919 : 775701 : stmtStartTimestamp = GetCurrentTimestamp();
920 : : else
921 : : Assert(stmtStartTimestamp != 0);
922 : 777721 : }
923 : :
924 : : /*
925 : : * GetCurrentTransactionNestLevel
926 : : *
927 : : * Note: this will return zero when not inside any transaction, one when
928 : : * inside a top-level transaction, etc.
929 : : */
930 : : int
931 : 26221216 : GetCurrentTransactionNestLevel(void)
932 : : {
933 : 26221216 : TransactionState s = CurrentTransactionState;
934 : :
935 : 26221216 : return s->nestingLevel;
936 : : }
937 : :
938 : :
939 : : /*
940 : : * TransactionIdIsCurrentTransactionId
941 : : */
942 : : bool
943 : 65510013 : TransactionIdIsCurrentTransactionId(TransactionId xid)
944 : : {
945 : : TransactionState s;
946 : :
947 : : /*
948 : : * We always say that BootstrapTransactionId is "not my transaction ID"
949 : : * even when it is (ie, during bootstrap). Along with the fact that
950 : : * transam.c always treats BootstrapTransactionId as already committed,
951 : : * this causes the heapam_visibility.c routines to see all tuples as
952 : : * committed, which is what we need during bootstrap. (Bootstrap mode
953 : : * only inserts tuples, it never updates or deletes them, so all tuples
954 : : * can be presumed good immediately.)
955 : : *
956 : : * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
957 : : * not my transaction ID, so we can just return "false" immediately for
958 : : * any non-normal XID.
959 : : */
960 [ + + ]: 65510013 : if (!TransactionIdIsNormal(xid))
961 : 727239 : return false;
962 : :
963 [ + + ]: 64782774 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
964 : 37897067 : return true;
965 : :
966 : : /*
967 : : * In parallel workers, the XIDs we must consider as current are stored in
968 : : * ParallelCurrentXids rather than the transaction-state stack. Note that
969 : : * the XIDs in this array are sorted numerically rather than according to
970 : : * transactionIdPrecedes order.
971 : : */
972 [ + + ]: 26885707 : if (nParallelCurrentXids > 0)
973 : : {
974 : : int low,
975 : : high;
976 : :
977 : 2495905 : low = 0;
978 : 2495905 : high = nParallelCurrentXids - 1;
979 [ + + ]: 9778884 : while (low <= high)
980 : : {
981 : : int middle;
982 : : TransactionId probe;
983 : :
984 : 9676574 : middle = low + (high - low) / 2;
985 : 9676574 : probe = ParallelCurrentXids[middle];
986 [ + + ]: 9676574 : if (probe == xid)
987 : 2393595 : return true;
988 [ + + ]: 7282979 : else if (probe < xid)
989 : 7180691 : low = middle + 1;
990 : : else
991 : 102288 : high = middle - 1;
992 : : }
993 : 102310 : return false;
994 : : }
995 : :
996 : : /*
997 : : * We will return true for the Xid of the current subtransaction, any of
998 : : * its subcommitted children, any of its parents, or any of their
999 : : * previously subcommitted children. However, a transaction being aborted
1000 : : * is no longer "current", even though it may still have an entry on the
1001 : : * state stack.
1002 : : */
1003 [ + + ]: 48742033 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
1004 : : {
1005 : : int low,
1006 : : high;
1007 : :
1008 [ - + ]: 24471512 : if (s->state == TRANS_ABORT)
1009 : 0 : continue;
1010 [ + + ]: 24471512 : if (!FullTransactionIdIsValid(s->fullTransactionId))
1011 : 11320903 : continue; /* it can't have any child XIDs either */
1012 [ + + ]: 13150609 : if (TransactionIdEquals(xid, XidFromFullTransactionId(s->fullTransactionId)))
1013 : 117718 : return true;
1014 : : /* As the childXids array is ordered, we can use binary search */
1015 : 13032891 : low = 0;
1016 : 13032891 : high = s->nChildXids - 1;
1017 [ + + ]: 13033774 : while (low <= high)
1018 : : {
1019 : : int middle;
1020 : : TransactionId probe;
1021 : :
1022 : 2446 : middle = low + (high - low) / 2;
1023 : 2446 : probe = s->childXids[middle];
1024 [ + + ]: 2446 : if (TransactionIdEquals(probe, xid))
1025 : 1563 : return true;
1026 [ + + ]: 883 : else if (TransactionIdPrecedes(probe, xid))
1027 : 803 : low = middle + 1;
1028 : : else
1029 : 80 : high = middle - 1;
1030 : : }
1031 : : }
1032 : :
1033 : 24270521 : return false;
1034 : : }
1035 : :
1036 : : /*
1037 : : * TransactionStartedDuringRecovery
1038 : : *
1039 : : * Returns true if the current transaction started while recovery was still
1040 : : * in progress. Recovery might have ended since so RecoveryInProgress() might
1041 : : * return false already.
1042 : : */
1043 : : bool
1044 : 9796029 : TransactionStartedDuringRecovery(void)
1045 : : {
1046 : 9796029 : return CurrentTransactionState->startedInRecovery;
1047 : : }
1048 : :
1049 : : /*
1050 : : * GetTopReadOnlyTransactionNestLevel
1051 : : *
1052 : : * Note: this will return zero when not inside any transaction or when neither
1053 : : * a top-level transaction nor subtransactions are read-only, one when the
1054 : : * top-level transaction is read-only, two when one level of subtransaction is
1055 : : * read-only, etc.
1056 : : *
1057 : : * Note: subtransactions of the topmost read-only transaction are also
1058 : : * read-only, because they inherit read-only mode from the transaction, and
1059 : : * thus can't change to read-write mode (see check_transaction_read_only).
1060 : : */
1061 : : int
1062 : 9 : GetTopReadOnlyTransactionNestLevel(void)
1063 : : {
1064 : 9 : TransactionState s = CurrentTransactionState;
1065 : :
1066 [ - + ]: 9 : if (!XactReadOnly)
1067 : 0 : return 0;
1068 [ + + ]: 10 : while (s->nestingLevel > 1)
1069 : : {
1070 [ + + ]: 4 : if (!s->prevXactReadOnly)
1071 : 3 : return s->nestingLevel;
1072 : 1 : s = s->parent;
1073 : : }
1074 : 6 : return s->nestingLevel;
1075 : : }
1076 : :
1077 : : /*
1078 : : * EnterParallelMode
1079 : : */
1080 : : void
1081 : 4697 : EnterParallelMode(void)
1082 : : {
1083 : 4697 : TransactionState s = CurrentTransactionState;
1084 : :
1085 : : Assert(s->parallelModeLevel >= 0);
1086 : :
1087 : 4697 : ++s->parallelModeLevel;
1088 : 4697 : }
1089 : :
1090 : : /*
1091 : : * ExitParallelMode
1092 : : */
1093 : : void
1094 : 2669 : ExitParallelMode(void)
1095 : : {
1096 : 2669 : TransactionState s = CurrentTransactionState;
1097 : :
1098 : : Assert(s->parallelModeLevel > 0);
1099 : : Assert(s->parallelModeLevel > 1 || s->parallelChildXact ||
1100 : : !ParallelContextActive());
1101 : :
1102 : 2669 : --s->parallelModeLevel;
1103 : 2669 : }
1104 : :
1105 : : /*
1106 : : * IsInParallelMode
1107 : : *
1108 : : * Are we in a parallel operation, as either the leader or a worker? Check
1109 : : * this to prohibit operations that change backend-local state expected to
1110 : : * match across all workers. Mere caches usually don't require such a
1111 : : * restriction. State modified in a strict push/pop fashion, such as the
1112 : : * active snapshot stack, is often fine.
1113 : : *
1114 : : * We say we are in parallel mode if we are in a subxact of a transaction
1115 : : * that's initiated a parallel operation; for most purposes that context
1116 : : * has all the same restrictions.
1117 : : */
1118 : : bool
1119 : 32255691 : IsInParallelMode(void)
1120 : : {
1121 : 32255691 : TransactionState s = CurrentTransactionState;
1122 : :
1123 [ + + + + ]: 32255691 : return s->parallelModeLevel != 0 || s->parallelChildXact;
1124 : : }
1125 : :
1126 : : /*
1127 : : * CommandCounterIncrement
1128 : : */
1129 : : void
1130 : 1377449 : CommandCounterIncrement(void)
1131 : : {
1132 : : /*
1133 : : * If the current value of the command counter hasn't been "used" to mark
1134 : : * tuples, we need not increment it, since there's no need to distinguish
1135 : : * a read-only command from others. This helps postpone command counter
1136 : : * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1137 : : */
1138 [ + + ]: 1377449 : if (currentCommandIdUsed)
1139 : : {
1140 : : /*
1141 : : * Workers synchronize transaction state at the beginning of each
1142 : : * parallel operation, so we can't account for new commands after that
1143 : : * point.
1144 : : */
1145 [ + - - + ]: 729405 : if (IsInParallelMode() || IsParallelWorker())
1146 [ # # ]: 0 : ereport(ERROR,
1147 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1148 : : errmsg("cannot start commands during a parallel operation")));
1149 : :
1150 : 729405 : currentCommandId += 1;
1151 [ - + ]: 729405 : if (currentCommandId == InvalidCommandId)
1152 : : {
1153 : 0 : currentCommandId -= 1;
1154 [ # # ]: 0 : ereport(ERROR,
1155 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1156 : : errmsg("cannot have more than 2^32-2 commands in a transaction")));
1157 : : }
1158 : 729405 : currentCommandIdUsed = false;
1159 : :
1160 : : /* Propagate new command ID into static snapshots */
1161 : 729405 : SnapshotSetCommandId(currentCommandId);
1162 : :
1163 : : /*
1164 : : * Make any catalog changes done by the just-completed command visible
1165 : : * in the local syscache. We obviously don't need to do this after a
1166 : : * read-only command. (But see hacks in inval.c to make real sure we
1167 : : * don't think a command that queued inval messages was read-only.)
1168 : : */
1169 : 729405 : AtCCI_LocalCache();
1170 : : }
1171 : 1377445 : }
1172 : :
1173 : : /*
1174 : : * ForceSyncCommit
1175 : : *
1176 : : * Interface routine to allow commands to force a synchronous commit of the
1177 : : * current top-level transaction. Currently, two-phase commit does not
1178 : : * persist and restore this variable. So long as all callers use
1179 : : * PreventInTransactionBlock(), that omission has no consequences.
1180 : : */
1181 : : void
1182 : 576 : ForceSyncCommit(void)
1183 : : {
1184 : 576 : forceSyncCommit = true;
1185 : 576 : }
1186 : :
1187 : :
1188 : : /* ----------------------------------------------------------------
1189 : : * StartTransaction stuff
1190 : : * ----------------------------------------------------------------
1191 : : */
1192 : :
1193 : : /*
1194 : : * AtStart_Cache
1195 : : */
1196 : : static void
1197 : 666148 : AtStart_Cache(void)
1198 : : {
1199 : 666148 : AcceptInvalidationMessages();
1200 : 666148 : }
1201 : :
1202 : : /*
1203 : : * AtStart_Memory
1204 : : */
1205 : : static void
1206 : 666148 : AtStart_Memory(void)
1207 : : {
1208 : 666148 : TransactionState s = CurrentTransactionState;
1209 : :
1210 : : /*
1211 : : * Remember the memory context that was active prior to transaction start.
1212 : : */
1213 : 666148 : s->priorContext = CurrentMemoryContext;
1214 : :
1215 : : /*
1216 : : * If this is the first time through, create a private context for
1217 : : * AbortTransaction to work in. By reserving some space now, we can
1218 : : * insulate AbortTransaction from out-of-memory scenarios. Like
1219 : : * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1220 : : * size, so that space will be reserved immediately.
1221 : : */
1222 [ + + ]: 666148 : if (TransactionAbortContext == NULL)
1223 : 20830 : TransactionAbortContext =
1224 : 20830 : AllocSetContextCreate(TopMemoryContext,
1225 : : "TransactionAbortContext",
1226 : : 32 * 1024,
1227 : : 32 * 1024,
1228 : : 32 * 1024);
1229 : :
1230 : : /*
1231 : : * Likewise, if this is the first time through, create a top-level context
1232 : : * for transaction-local data. This context will be reset at transaction
1233 : : * end, and then re-used in later transactions.
1234 : : */
1235 [ + + ]: 666148 : if (TopTransactionContext == NULL)
1236 : 20830 : TopTransactionContext =
1237 : 20830 : AllocSetContextCreate(TopMemoryContext,
1238 : : "TopTransactionContext",
1239 : : ALLOCSET_DEFAULT_SIZES);
1240 : :
1241 : : /*
1242 : : * In a top-level transaction, CurTransactionContext is the same as
1243 : : * TopTransactionContext.
1244 : : */
1245 : 666148 : CurTransactionContext = TopTransactionContext;
1246 : 666148 : s->curTransactionContext = CurTransactionContext;
1247 : :
1248 : : /* Make the CurTransactionContext active. */
1249 : 666148 : MemoryContextSwitchTo(CurTransactionContext);
1250 : 666148 : }
1251 : :
1252 : : /*
1253 : : * AtStart_ResourceOwner
1254 : : */
1255 : : static void
1256 : 666148 : AtStart_ResourceOwner(void)
1257 : : {
1258 : 666148 : TransactionState s = CurrentTransactionState;
1259 : :
1260 : : /*
1261 : : * We shouldn't have a transaction resource owner already.
1262 : : */
1263 : : Assert(TopTransactionResourceOwner == NULL);
1264 : :
1265 : : /*
1266 : : * Create a toplevel resource owner for the transaction.
1267 : : */
1268 : 666148 : s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1269 : :
1270 : 666148 : TopTransactionResourceOwner = s->curTransactionOwner;
1271 : 666148 : CurTransactionResourceOwner = s->curTransactionOwner;
1272 : 666148 : CurrentResourceOwner = s->curTransactionOwner;
1273 : 666148 : }
1274 : :
1275 : : /* ----------------------------------------------------------------
1276 : : * StartSubTransaction stuff
1277 : : * ----------------------------------------------------------------
1278 : : */
1279 : :
1280 : : /*
1281 : : * AtSubStart_Memory
1282 : : */
1283 : : static void
1284 : 22875 : AtSubStart_Memory(void)
1285 : : {
1286 : 22875 : TransactionState s = CurrentTransactionState;
1287 : :
1288 : : Assert(CurTransactionContext != NULL);
1289 : :
1290 : : /*
1291 : : * Remember the context that was active prior to subtransaction start.
1292 : : */
1293 : 22875 : s->priorContext = CurrentMemoryContext;
1294 : :
1295 : : /*
1296 : : * Create a CurTransactionContext, which will be used to hold data that
1297 : : * survives subtransaction commit but disappears on subtransaction abort.
1298 : : * We make it a child of the immediate parent's CurTransactionContext.
1299 : : */
1300 : 22875 : CurTransactionContext = AllocSetContextCreate(CurTransactionContext,
1301 : : "CurTransactionContext",
1302 : : ALLOCSET_DEFAULT_SIZES);
1303 : 22875 : s->curTransactionContext = CurTransactionContext;
1304 : :
1305 : : /* Make the CurTransactionContext active. */
1306 : 22875 : MemoryContextSwitchTo(CurTransactionContext);
1307 : 22875 : }
1308 : :
1309 : : /*
1310 : : * AtSubStart_ResourceOwner
1311 : : */
1312 : : static void
1313 : 22875 : AtSubStart_ResourceOwner(void)
1314 : : {
1315 : 22875 : TransactionState s = CurrentTransactionState;
1316 : :
1317 : : Assert(s->parent != NULL);
1318 : :
1319 : : /*
1320 : : * Create a resource owner for the subtransaction. We make it a child of
1321 : : * the immediate parent's resource owner.
1322 : : */
1323 : 22875 : s->curTransactionOwner =
1324 : 22875 : ResourceOwnerCreate(s->parent->curTransactionOwner,
1325 : : "SubTransaction");
1326 : :
1327 : 22875 : CurTransactionResourceOwner = s->curTransactionOwner;
1328 : 22875 : CurrentResourceOwner = s->curTransactionOwner;
1329 : 22875 : }
1330 : :
1331 : : /* ----------------------------------------------------------------
1332 : : * CommitTransaction stuff
1333 : : * ----------------------------------------------------------------
1334 : : */
1335 : :
1336 : : /*
1337 : : * RecordTransactionCommit
1338 : : *
1339 : : * Returns latest XID among xact and its children, or InvalidTransactionId
1340 : : * if the xact has no XID. (We compute that here just because it's easier.)
1341 : : *
1342 : : * If you change this function, see RecordTransactionCommitPrepared also.
1343 : : */
1344 : : static TransactionId
1345 : 627645 : RecordTransactionCommit(void)
1346 : : {
1347 : 627645 : TransactionId xid = GetTopTransactionIdIfAny();
1348 : 627645 : bool markXidCommitted = TransactionIdIsValid(xid);
1349 : 627645 : TransactionId latestXid = InvalidTransactionId;
1350 : : int nrels;
1351 : : RelFileLocator *rels;
1352 : : int nchildren;
1353 : : TransactionId *children;
1354 : 627645 : int ndroppedstats = 0;
1355 : 627645 : xl_xact_stats_item *droppedstats = NULL;
1356 : 627645 : int nmsgs = 0;
1357 : 627645 : SharedInvalidationMessage *invalMessages = NULL;
1358 : 627645 : bool RelcacheInitFileInval = false;
1359 : : bool wrote_xlog;
1360 : :
1361 : : /*
1362 : : * Log pending invalidations for logical decoding of in-progress
1363 : : * transactions. Normally for DDLs, we log this at each command end,
1364 : : * however, for certain cases where we directly update the system table
1365 : : * without a transaction block, the invalidations are not logged till this
1366 : : * time.
1367 : : */
1368 [ + + + + ]: 627645 : if (XLogLogicalInfoActive())
1369 : 14718 : LogLogicalInvalidations();
1370 : :
1371 : : /* Get data needed for commit record */
1372 : 627645 : nrels = smgrGetPendingDeletes(true, &rels);
1373 : 627645 : nchildren = xactGetCommittedChildren(&children);
1374 : 627645 : ndroppedstats = pgstat_get_transactional_drops(true, &droppedstats);
1375 [ + + ]: 627645 : if (XLogStandbyInfoActive())
1376 : 329718 : nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1377 : : &RelcacheInitFileInval);
1378 : 627645 : wrote_xlog = (XactLastRecEnd != 0);
1379 : :
1380 : : /*
1381 : : * If we haven't been assigned an XID yet, we neither can, nor do we want
1382 : : * to write a COMMIT record.
1383 : : */
1384 [ + + ]: 627645 : if (!markXidCommitted)
1385 : : {
1386 : : /*
1387 : : * We expect that every RelationDropStorage is followed by a catalog
1388 : : * update, and hence XID assignment, so we shouldn't get here with any
1389 : : * pending deletes. Same is true for dropping stats.
1390 : : *
1391 : : * Use a real test not just an Assert to check this, since it's a bit
1392 : : * fragile.
1393 : : */
1394 [ + - - + ]: 468295 : if (nrels != 0 || ndroppedstats != 0)
1395 [ # # ]: 0 : elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1396 : :
1397 : : /* Can't have child XIDs either; AssignTransactionId enforces this */
1398 : : Assert(nchildren == 0);
1399 : :
1400 : : /*
1401 : : * Transactions without an assigned xid can contain invalidation
1402 : : * messages. While inplace updates do this, this is not known to be
1403 : : * necessary; see comment at inplace CacheInvalidateHeapTuple().
1404 : : * Extensions might still rely on this capability, and standbys may
1405 : : * need to process those invals. We can't emit a commit record
1406 : : * without an xid, and we don't want to force assigning an xid,
1407 : : * because that'd be problematic for e.g. vacuum. Hence we emit a
1408 : : * bespoke record for the invalidations. We don't want to use that in
1409 : : * case a commit record is emitted, so they happen synchronously with
1410 : : * commits (besides not wanting to emit more WAL records).
1411 : : *
1412 : : * XXX Every known use of this capability is a defect. Since an XID
1413 : : * isn't controlling visibility of the change that prompted invals,
1414 : : * other sessions need the inval even if this transactions aborts.
1415 : : *
1416 : : * ON COMMIT DELETE ROWS does a nontransactional index_build(), which
1417 : : * queues a relcache inval, including in transactions without an xid
1418 : : * that had read the (empty) table. Standbys don't need any ON COMMIT
1419 : : * DELETE ROWS invals, but we've not done the work to withhold them.
1420 : : */
1421 [ + + ]: 468295 : if (nmsgs != 0)
1422 : : {
1423 : 11727 : LogStandbyInvalidations(nmsgs, invalMessages,
1424 : : RelcacheInitFileInval);
1425 : 11727 : wrote_xlog = true; /* not strictly necessary */
1426 : : }
1427 : :
1428 : : /*
1429 : : * If we didn't create XLOG entries, we're done here; otherwise we
1430 : : * should trigger flushing those entries the same as a commit record
1431 : : * would. This will primarily happen for HOT pruning and the like; we
1432 : : * want these to be flushed to disk in due time.
1433 : : */
1434 [ + + ]: 468295 : if (!wrote_xlog)
1435 : 420350 : goto cleanup;
1436 : : }
1437 : : else
1438 : : {
1439 : : bool replorigin;
1440 : :
1441 : : /*
1442 : : * Are we using the replication origins feature? Or, in other words,
1443 : : * are we replaying remote actions?
1444 : : */
1445 [ + + ]: 160446 : replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
1446 [ + - ]: 1096 : replorigin_xact_state.origin != DoNotReplicateId);
1447 : :
1448 : : /*
1449 : : * Mark ourselves as within our "commit critical section". This
1450 : : * forces any concurrent checkpoint to wait until we've updated
1451 : : * pg_xact. Without this, it is possible for the checkpoint to set
1452 : : * REDO after the XLOG record but fail to flush the pg_xact update to
1453 : : * disk, leading to loss of the transaction commit if the system
1454 : : * crashes a little later.
1455 : : *
1456 : : * Note: we could, but don't bother to, set this flag in
1457 : : * RecordTransactionAbort. That's because loss of a transaction abort
1458 : : * is noncritical; the presumption would be that it aborted, anyway.
1459 : : *
1460 : : * It's safe to change the delayChkptFlags flag of our own backend
1461 : : * without holding the ProcArrayLock, since we're the only one
1462 : : * modifying it. This makes checkpoint's determination of which xacts
1463 : : * are delaying the checkpoint a bit fuzzy, but it doesn't matter.
1464 : : *
1465 : : * Note, it is important to get the commit timestamp after marking the
1466 : : * transaction in the commit critical section. See
1467 : : * RecordTransactionCommitPrepared.
1468 : : */
1469 : : Assert((MyProc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0);
1470 : 159350 : START_CRIT_SECTION();
1471 : 159350 : MyProc->delayChkptFlags |= DELAY_CHKPT_IN_COMMIT;
1472 : :
1473 : : Assert(xactStopTimestamp == 0);
1474 : :
1475 : : /*
1476 : : * Ensures the DELAY_CHKPT_IN_COMMIT flag write is globally visible
1477 : : * before commit time is written.
1478 : : */
1479 : 159350 : pg_write_barrier();
1480 : :
1481 : : /*
1482 : : * Insert the commit XLOG record.
1483 : : */
1484 : 159350 : XactLogCommitRecord(GetCurrentTransactionStopTimestamp(),
1485 : : nchildren, children, nrels, rels,
1486 : : ndroppedstats, droppedstats,
1487 : : nmsgs, invalMessages,
1488 : : RelcacheInitFileInval,
1489 : : MyXactFlags,
1490 : : InvalidTransactionId, NULL /* plain commit */ );
1491 : :
1492 [ + + ]: 159350 : if (replorigin)
1493 : : /* Move LSNs forward for this replication origin */
1494 : 1096 : replorigin_session_advance(replorigin_xact_state.origin_lsn,
1495 : : XactLastRecEnd);
1496 : :
1497 : : /*
1498 : : * Record commit timestamp. The value comes from plain commit
1499 : : * timestamp if there's no replication origin; otherwise, the
1500 : : * timestamp was already set in replorigin_xact_state.origin_timestamp
1501 : : * by replication.
1502 : : *
1503 : : * We don't need to WAL-log anything here, as the commit record
1504 : : * written above already contains the data.
1505 : : */
1506 : :
1507 [ + + + + ]: 159350 : if (!replorigin || replorigin_xact_state.origin_timestamp == 0)
1508 : 158368 : replorigin_xact_state.origin_timestamp = GetCurrentTransactionStopTimestamp();
1509 : :
1510 : 159350 : TransactionTreeSetCommitTsData(xid, nchildren, children,
1511 : : replorigin_xact_state.origin_timestamp,
1512 : 159350 : replorigin_xact_state.origin);
1513 : : }
1514 : :
1515 : : /*
1516 : : * Check if we want to commit asynchronously. We can allow the XLOG flush
1517 : : * to happen asynchronously if synchronous_commit=off, or if the current
1518 : : * transaction has not performed any WAL-logged operation or didn't assign
1519 : : * an xid. The transaction can end up not writing any WAL, even if it has
1520 : : * an xid, if it only wrote to temporary and/or unlogged tables. It can
1521 : : * end up having written WAL without an xid if it did HOT pruning. In
1522 : : * case of a crash, the loss of such a transaction will be irrelevant;
1523 : : * temp tables will be lost anyway, unlogged tables will be truncated and
1524 : : * HOT pruning will be done again later. (Given the foregoing, you might
1525 : : * think that it would be unnecessary to emit the XLOG record at all in
1526 : : * this case, but we don't currently try to do that. It would certainly
1527 : : * cause problems at least in Hot Standby mode, where the
1528 : : * KnownAssignedXids machinery requires tracking every XID assignment. It
1529 : : * might be OK to skip it only when wal_level < replica, but for now we
1530 : : * don't.)
1531 : : *
1532 : : * However, if we're doing cleanup of any non-temp rels or committing any
1533 : : * command that wanted to force sync commit, then we must flush XLOG
1534 : : * immediately. (We must not allow asynchronous commit if there are any
1535 : : * non-temp tables to be deleted, because we might delete the files before
1536 : : * the COMMIT record is flushed to disk. We do allow asynchronous commit
1537 : : * if all to-be-deleted tables are temporary though, since they are lost
1538 : : * anyway if we crash.)
1539 : : */
1540 [ + + + + ]: 207295 : if ((wrote_xlog && markXidCommitted &&
1541 [ + + + + ]: 207295 : synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
1542 [ + + ]: 55231 : forceSyncCommit || nrels > 0)
1543 : : {
1544 : 152085 : XLogFlush(XactLastRecEnd);
1545 : :
1546 : : /*
1547 : : * Now we may update the CLOG, if we wrote a COMMIT record above
1548 : : */
1549 [ + - ]: 152085 : if (markXidCommitted)
1550 : 152085 : TransactionIdCommitTree(xid, nchildren, children);
1551 : : }
1552 : : else
1553 : : {
1554 : : /*
1555 : : * Asynchronous commit case:
1556 : : *
1557 : : * This enables possible committed transaction loss in the case of a
1558 : : * postmaster crash because WAL buffers are left unwritten. Ideally we
1559 : : * could issue the WAL write without the fsync, but some
1560 : : * wal_sync_methods do not allow separate write/fsync.
1561 : : *
1562 : : * Report the latest async commit LSN, so that the WAL writer knows to
1563 : : * flush this commit.
1564 : : */
1565 : 55210 : XLogSetAsyncXactLSN(XactLastRecEnd);
1566 : :
1567 : : /*
1568 : : * We must not immediately update the CLOG, since we didn't flush the
1569 : : * XLOG. Instead, we store the LSN up to which the XLOG must be
1570 : : * flushed before the CLOG may be updated.
1571 : : */
1572 [ + + ]: 55210 : if (markXidCommitted)
1573 : 7265 : TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1574 : : }
1575 : :
1576 : : /*
1577 : : * If we entered a commit critical section, leave it now, and let
1578 : : * checkpoints proceed.
1579 : : */
1580 [ + + ]: 207295 : if (markXidCommitted)
1581 : : {
1582 : 159350 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_IN_COMMIT;
1583 : 159350 : END_CRIT_SECTION();
1584 : : }
1585 : :
1586 : : /* Compute latestXid while we have the child XIDs handy */
1587 : 207295 : latestXid = TransactionIdLatest(xid, nchildren, children);
1588 : :
1589 : : /*
1590 : : * Wait for synchronous replication, if required. Similar to the decision
1591 : : * above about using committing asynchronously we only want to wait if
1592 : : * this backend assigned an xid and wrote WAL. No need to wait if an xid
1593 : : * was assigned due to temporary/unlogged tables or due to HOT pruning.
1594 : : *
1595 : : * Note that at this stage we have marked clog, but still show as running
1596 : : * in the procarray and continue to hold locks.
1597 : : */
1598 [ + + + + ]: 207295 : if (wrote_xlog && markXidCommitted)
1599 : 154589 : SyncRepWaitForLSN(XactLastRecEnd, true);
1600 : :
1601 : : /* remember end of last commit record */
1602 : 207295 : XactLastCommitEnd = XactLastRecEnd;
1603 : :
1604 : : /* Reset XactLastRecEnd until the next transaction writes something */
1605 : 207295 : XactLastRecEnd = 0;
1606 : 627645 : cleanup:
1607 : : /* Clean up local data */
1608 [ + + ]: 627645 : if (rels)
1609 : 12553 : pfree(rels);
1610 [ + + ]: 627645 : if (ndroppedstats)
1611 : 14975 : pfree(droppedstats);
1612 : :
1613 : 627645 : return latestXid;
1614 : : }
1615 : :
1616 : :
1617 : : /*
1618 : : * AtCCI_LocalCache
1619 : : */
1620 : : static void
1621 : 729405 : AtCCI_LocalCache(void)
1622 : : {
1623 : : /*
1624 : : * Make any pending relation map changes visible. We must do this before
1625 : : * processing local sinval messages, so that the map changes will get
1626 : : * reflected into the relcache when relcache invals are processed.
1627 : : */
1628 : 729405 : AtCCI_RelationMap();
1629 : :
1630 : : /*
1631 : : * Make catalog changes visible to me for the next command.
1632 : : */
1633 : 729405 : CommandEndInvalidationMessages();
1634 : 729401 : }
1635 : :
1636 : : /*
1637 : : * AtCommit_Memory
1638 : : */
1639 : : static void
1640 : 629975 : AtCommit_Memory(void)
1641 : : {
1642 : 629975 : TransactionState s = CurrentTransactionState;
1643 : :
1644 : : /*
1645 : : * Return to the memory context that was current before we started the
1646 : : * transaction. (In principle, this could not be any of the contexts we
1647 : : * are about to delete. If it somehow is, assertions in mcxt.c will
1648 : : * complain.)
1649 : : */
1650 : 629975 : MemoryContextSwitchTo(s->priorContext);
1651 : :
1652 : : /*
1653 : : * Release all transaction-local memory. TopTransactionContext survives
1654 : : * but becomes empty; any sub-contexts go away.
1655 : : */
1656 : : Assert(TopTransactionContext != NULL);
1657 : 629975 : MemoryContextReset(TopTransactionContext);
1658 : :
1659 : : /*
1660 : : * Clear these pointers as a pro-forma matter. (Notionally, while
1661 : : * TopTransactionContext still exists, it's currently not associated with
1662 : : * this TransactionState struct.)
1663 : : */
1664 : 629975 : CurTransactionContext = NULL;
1665 : 629975 : s->curTransactionContext = NULL;
1666 : 629975 : }
1667 : :
1668 : : /* ----------------------------------------------------------------
1669 : : * CommitSubTransaction stuff
1670 : : * ----------------------------------------------------------------
1671 : : */
1672 : :
1673 : : /*
1674 : : * AtSubCommit_Memory
1675 : : */
1676 : : static void
1677 : 17384 : AtSubCommit_Memory(void)
1678 : : {
1679 : 17384 : TransactionState s = CurrentTransactionState;
1680 : :
1681 : : Assert(s->parent != NULL);
1682 : :
1683 : : /* Return to parent transaction level's memory context. */
1684 : 17384 : CurTransactionContext = s->parent->curTransactionContext;
1685 : 17384 : MemoryContextSwitchTo(CurTransactionContext);
1686 : :
1687 : : /*
1688 : : * Ordinarily we cannot throw away the child's CurTransactionContext,
1689 : : * since the data it contains will be needed at upper commit. However, if
1690 : : * there isn't actually anything in it, we can throw it away. This avoids
1691 : : * a small memory leak in the common case of "trivial" subxacts.
1692 : : */
1693 [ + + ]: 17384 : if (MemoryContextIsEmpty(s->curTransactionContext))
1694 : : {
1695 : 17367 : MemoryContextDelete(s->curTransactionContext);
1696 : 17367 : s->curTransactionContext = NULL;
1697 : : }
1698 : 17384 : }
1699 : :
1700 : : /*
1701 : : * AtSubCommit_childXids
1702 : : *
1703 : : * Pass my own XID and my child XIDs up to my parent as committed children.
1704 : : */
1705 : : static void
1706 : 15475 : AtSubCommit_childXids(void)
1707 : : {
1708 : 15475 : TransactionState s = CurrentTransactionState;
1709 : : int new_nChildXids;
1710 : :
1711 : : Assert(s->parent != NULL);
1712 : :
1713 : : /*
1714 : : * The parent childXids array will need to hold my XID and all my
1715 : : * childXids, in addition to the XIDs already there.
1716 : : */
1717 : 15475 : new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1718 : :
1719 : : /* Allocate or enlarge the parent array if necessary */
1720 [ + + ]: 15475 : if (s->parent->maxChildXids < new_nChildXids)
1721 : : {
1722 : : int new_maxChildXids;
1723 : : TransactionId *new_childXids;
1724 : :
1725 : : /*
1726 : : * Make it 2x what's needed right now, to avoid having to enlarge it
1727 : : * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1728 : : * is what ensures that we don't need to worry about integer overflow
1729 : : * here or in the calculation of new_nChildXids.)
1730 : : */
1731 : 1731 : new_maxChildXids = Min(new_nChildXids * 2,
1732 : : (int) (MaxAllocSize / sizeof(TransactionId)));
1733 : :
1734 [ - + ]: 1731 : if (new_maxChildXids < new_nChildXids)
1735 [ # # ]: 0 : ereport(ERROR,
1736 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1737 : : errmsg("maximum number of committed subtransactions (%d) exceeded",
1738 : : (int) (MaxAllocSize / sizeof(TransactionId)))));
1739 : :
1740 : : /*
1741 : : * We keep the child-XID arrays in TopTransactionContext; this avoids
1742 : : * setting up child-transaction contexts for what might be just a few
1743 : : * bytes of grandchild XIDs.
1744 : : */
1745 [ + + ]: 1731 : if (s->parent->childXids == NULL)
1746 : : new_childXids =
1747 : 1654 : MemoryContextAlloc(TopTransactionContext,
1748 : : new_maxChildXids * sizeof(TransactionId));
1749 : : else
1750 : 77 : new_childXids = repalloc_array(s->parent->childXids, TransactionId, new_maxChildXids);
1751 : :
1752 : 1731 : s->parent->childXids = new_childXids;
1753 : 1731 : s->parent->maxChildXids = new_maxChildXids;
1754 : : }
1755 : :
1756 : : /*
1757 : : * Copy all my XIDs to parent's array.
1758 : : *
1759 : : * Note: We rely on the fact that the XID of a child always follows that
1760 : : * of its parent. By copying the XID of this subtransaction before the
1761 : : * XIDs of its children, we ensure that the array stays ordered. Likewise,
1762 : : * all XIDs already in the array belong to subtransactions started and
1763 : : * subcommitted before us, so their XIDs must precede ours.
1764 : : */
1765 : 15475 : s->parent->childXids[s->parent->nChildXids] = XidFromFullTransactionId(s->fullTransactionId);
1766 : :
1767 [ + + ]: 15475 : if (s->nChildXids > 0)
1768 : 1018 : memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1769 : 1018 : s->childXids,
1770 : 1018 : s->nChildXids * sizeof(TransactionId));
1771 : :
1772 : 15475 : s->parent->nChildXids = new_nChildXids;
1773 : :
1774 : : /* Release child's array to avoid leakage */
1775 [ + + ]: 15475 : if (s->childXids != NULL)
1776 : 1018 : pfree(s->childXids);
1777 : : /* We must reset these to avoid double-free if fail later in commit */
1778 : 15475 : s->childXids = NULL;
1779 : 15475 : s->nChildXids = 0;
1780 : 15475 : s->maxChildXids = 0;
1781 : 15475 : }
1782 : :
1783 : : /* ----------------------------------------------------------------
1784 : : * AbortTransaction stuff
1785 : : * ----------------------------------------------------------------
1786 : : */
1787 : :
1788 : : /*
1789 : : * RecordTransactionAbort
1790 : : *
1791 : : * Returns latest XID among xact and its children, or InvalidTransactionId
1792 : : * if the xact has no XID. (We compute that here just because it's easier.)
1793 : : */
1794 : : static TransactionId
1795 : 41656 : RecordTransactionAbort(bool isSubXact)
1796 : : {
1797 : 41656 : TransactionId xid = GetCurrentTransactionIdIfAny();
1798 : : TransactionId latestXid;
1799 : : int nrels;
1800 : : RelFileLocator *rels;
1801 : 41656 : int ndroppedstats = 0;
1802 : 41656 : xl_xact_stats_item *droppedstats = NULL;
1803 : : int nchildren;
1804 : : TransactionId *children;
1805 : : TimestampTz xact_time;
1806 : : bool replorigin;
1807 : :
1808 : : /*
1809 : : * If we haven't been assigned an XID, nobody will care whether we aborted
1810 : : * or not. Hence, we're done in that case. It does not matter if we have
1811 : : * rels to delete (note that this routine is not responsible for actually
1812 : : * deleting 'em). We cannot have any child XIDs, either.
1813 : : */
1814 [ + + ]: 41656 : if (!TransactionIdIsValid(xid))
1815 : : {
1816 : : /* Reset XactLastRecEnd until the next transaction writes something */
1817 [ + + ]: 32264 : if (!isSubXact)
1818 : 27638 : XactLastRecEnd = 0;
1819 : 32264 : return InvalidTransactionId;
1820 : : }
1821 : :
1822 : : /*
1823 : : * We have a valid XID, so we should write an ABORT record for it.
1824 : : *
1825 : : * We do not flush XLOG to disk here, since the default assumption after a
1826 : : * crash would be that we aborted, anyway. For the same reason, we don't
1827 : : * need to worry about interlocking against checkpoint start.
1828 : : */
1829 : :
1830 : : /*
1831 : : * Check that we haven't aborted halfway through RecordTransactionCommit.
1832 : : */
1833 [ - + ]: 9392 : if (TransactionIdDidCommit(xid))
1834 [ # # ]: 0 : elog(PANIC, "cannot abort transaction %u, it was already committed",
1835 : : xid);
1836 : :
1837 : : /*
1838 : : * Are we using the replication origins feature? Or, in other words, are
1839 : : * we replaying remote actions?
1840 : : */
1841 [ + + ]: 9415 : replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
1842 [ + - ]: 23 : replorigin_xact_state.origin != DoNotReplicateId);
1843 : :
1844 : : /* Fetch the data we need for the abort record */
1845 : 9392 : nrels = smgrGetPendingDeletes(false, &rels);
1846 : 9392 : nchildren = xactGetCommittedChildren(&children);
1847 : 9392 : ndroppedstats = pgstat_get_transactional_drops(false, &droppedstats);
1848 : :
1849 : : /* XXX do we really need a critical section here? */
1850 : 9392 : START_CRIT_SECTION();
1851 : :
1852 : : /* Write the ABORT record */
1853 [ + + ]: 9392 : if (isSubXact)
1854 : 865 : xact_time = GetCurrentTimestamp();
1855 : : else
1856 : : {
1857 : 8527 : xact_time = GetCurrentTransactionStopTimestamp();
1858 : : }
1859 : :
1860 : 9392 : XactLogAbortRecord(xact_time,
1861 : : nchildren, children,
1862 : : nrels, rels,
1863 : : ndroppedstats, droppedstats,
1864 : : MyXactFlags, InvalidTransactionId,
1865 : : NULL);
1866 : :
1867 [ + + ]: 9392 : if (replorigin)
1868 : : /* Move LSNs forward for this replication origin */
1869 : 23 : replorigin_session_advance(replorigin_xact_state.origin_lsn,
1870 : : XactLastRecEnd);
1871 : :
1872 : : /*
1873 : : * Report the latest async abort LSN, so that the WAL writer knows to
1874 : : * flush this abort. There's nothing to be gained by delaying this, since
1875 : : * WALWriter may as well do this when it can. This is important with
1876 : : * streaming replication because if we don't flush WAL regularly we will
1877 : : * find that large aborts leave us with a long backlog for when commits
1878 : : * occur after the abort, increasing our window of data loss should
1879 : : * problems occur at that point.
1880 : : */
1881 [ + + ]: 9392 : if (!isSubXact)
1882 : 8527 : XLogSetAsyncXactLSN(XactLastRecEnd);
1883 : :
1884 : : /*
1885 : : * Mark the transaction aborted in clog. This is not absolutely necessary
1886 : : * but we may as well do it while we are here; also, in the subxact case
1887 : : * it is helpful because XactLockTableWait makes use of it to avoid
1888 : : * waiting for already-aborted subtransactions. It is OK to do it without
1889 : : * having flushed the ABORT record to disk, because in event of a crash
1890 : : * we'd be assumed to have aborted anyway.
1891 : : */
1892 : 9392 : TransactionIdAbortTree(xid, nchildren, children);
1893 : :
1894 : 9392 : END_CRIT_SECTION();
1895 : :
1896 : : /* Compute latestXid while we have the child XIDs handy */
1897 : 9392 : latestXid = TransactionIdLatest(xid, nchildren, children);
1898 : :
1899 : : /*
1900 : : * If we're aborting a subtransaction, we can immediately remove failed
1901 : : * XIDs from PGPROC's cache of running child XIDs. We do that here for
1902 : : * subxacts, because we already have the child XID array at hand. For
1903 : : * main xacts, the equivalent happens just after this function returns.
1904 : : */
1905 [ + + ]: 9392 : if (isSubXact)
1906 : 865 : XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1907 : :
1908 : : /* Reset XactLastRecEnd until the next transaction writes something */
1909 [ + + ]: 9392 : if (!isSubXact)
1910 : 8527 : XactLastRecEnd = 0;
1911 : :
1912 : : /* And clean up local data */
1913 [ + + ]: 9392 : if (rels)
1914 : 1395 : pfree(rels);
1915 [ + + ]: 9392 : if (ndroppedstats)
1916 : 1993 : pfree(droppedstats);
1917 : :
1918 : 9392 : return latestXid;
1919 : : }
1920 : :
1921 : : /*
1922 : : * AtAbort_Memory
1923 : : */
1924 : : static void
1925 : 57583 : AtAbort_Memory(void)
1926 : : {
1927 : : /*
1928 : : * Switch into TransactionAbortContext, which should have some free space
1929 : : * even if nothing else does. We'll work in this context until we've
1930 : : * finished cleaning up.
1931 : : *
1932 : : * It is barely possible to get here when we've not been able to create
1933 : : * TransactionAbortContext yet; if so use TopMemoryContext.
1934 : : */
1935 [ + - ]: 57583 : if (TransactionAbortContext != NULL)
1936 : 57583 : MemoryContextSwitchTo(TransactionAbortContext);
1937 : : else
1938 : 0 : MemoryContextSwitchTo(TopMemoryContext);
1939 : 57583 : }
1940 : :
1941 : : /*
1942 : : * AtSubAbort_Memory
1943 : : */
1944 : : static void
1945 : 5491 : AtSubAbort_Memory(void)
1946 : : {
1947 : : Assert(TransactionAbortContext != NULL);
1948 : :
1949 : 5491 : MemoryContextSwitchTo(TransactionAbortContext);
1950 : 5491 : }
1951 : :
1952 : :
1953 : : /*
1954 : : * AtAbort_ResourceOwner
1955 : : */
1956 : : static void
1957 : 36173 : AtAbort_ResourceOwner(void)
1958 : : {
1959 : : /*
1960 : : * Make sure we have a valid ResourceOwner, if possible (else it will be
1961 : : * NULL, which is OK)
1962 : : */
1963 : 36173 : CurrentResourceOwner = TopTransactionResourceOwner;
1964 : 36173 : }
1965 : :
1966 : : /*
1967 : : * AtSubAbort_ResourceOwner
1968 : : */
1969 : : static void
1970 : 5491 : AtSubAbort_ResourceOwner(void)
1971 : : {
1972 : 5491 : TransactionState s = CurrentTransactionState;
1973 : :
1974 : : /* Make sure we have a valid ResourceOwner */
1975 : 5491 : CurrentResourceOwner = s->curTransactionOwner;
1976 : 5491 : }
1977 : :
1978 : :
1979 : : /*
1980 : : * AtSubAbort_childXids
1981 : : */
1982 : : static void
1983 : 865 : AtSubAbort_childXids(void)
1984 : : {
1985 : 865 : TransactionState s = CurrentTransactionState;
1986 : :
1987 : : /*
1988 : : * We keep the child-XID arrays in TopTransactionContext (see
1989 : : * AtSubCommit_childXids). This means we'd better free the array
1990 : : * explicitly at abort to avoid leakage.
1991 : : */
1992 [ + + ]: 865 : if (s->childXids != NULL)
1993 : 26 : pfree(s->childXids);
1994 : 865 : s->childXids = NULL;
1995 : 865 : s->nChildXids = 0;
1996 : 865 : s->maxChildXids = 0;
1997 : :
1998 : : /*
1999 : : * We could prune the unreportedXids array here. But we don't bother. That
2000 : : * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
2001 : : * would likely introduce more CPU time into the more common paths, so we
2002 : : * choose not to do that.
2003 : : */
2004 : 865 : }
2005 : :
2006 : : /* ----------------------------------------------------------------
2007 : : * CleanupTransaction stuff
2008 : : * ----------------------------------------------------------------
2009 : : */
2010 : :
2011 : : /*
2012 : : * AtCleanup_Memory
2013 : : */
2014 : : static void
2015 : 36173 : AtCleanup_Memory(void)
2016 : : {
2017 : 36173 : TransactionState s = CurrentTransactionState;
2018 : :
2019 : : /* Should be at top level */
2020 : : Assert(s->parent == NULL);
2021 : :
2022 : : /*
2023 : : * Return to the memory context that was current before we started the
2024 : : * transaction. (In principle, this could not be any of the contexts we
2025 : : * are about to delete. If it somehow is, assertions in mcxt.c will
2026 : : * complain.)
2027 : : */
2028 : 36173 : MemoryContextSwitchTo(s->priorContext);
2029 : :
2030 : : /*
2031 : : * Clear the special abort context for next time.
2032 : : */
2033 [ + - ]: 36173 : if (TransactionAbortContext != NULL)
2034 : 36173 : MemoryContextReset(TransactionAbortContext);
2035 : :
2036 : : /*
2037 : : * Release all transaction-local memory, the same as in AtCommit_Memory,
2038 : : * except we must cope with the possibility that we didn't get as far as
2039 : : * creating TopTransactionContext.
2040 : : */
2041 [ + - ]: 36173 : if (TopTransactionContext != NULL)
2042 : 36173 : MemoryContextReset(TopTransactionContext);
2043 : :
2044 : : /*
2045 : : * Clear these pointers as a pro-forma matter. (Notionally, while
2046 : : * TopTransactionContext still exists, it's currently not associated with
2047 : : * this TransactionState struct.)
2048 : : */
2049 : 36173 : CurTransactionContext = NULL;
2050 : 36173 : s->curTransactionContext = NULL;
2051 : 36173 : }
2052 : :
2053 : :
2054 : : /* ----------------------------------------------------------------
2055 : : * CleanupSubTransaction stuff
2056 : : * ----------------------------------------------------------------
2057 : : */
2058 : :
2059 : : /*
2060 : : * AtSubCleanup_Memory
2061 : : */
2062 : : static void
2063 : 5491 : AtSubCleanup_Memory(void)
2064 : : {
2065 : 5491 : TransactionState s = CurrentTransactionState;
2066 : :
2067 : : Assert(s->parent != NULL);
2068 : :
2069 : : /*
2070 : : * Return to the memory context that was current before we started the
2071 : : * subtransaction. (In principle, this could not be any of the contexts
2072 : : * we are about to delete. If it somehow is, assertions in mcxt.c will
2073 : : * complain.)
2074 : : */
2075 : 5491 : MemoryContextSwitchTo(s->priorContext);
2076 : :
2077 : : /* Update CurTransactionContext (might not be same as priorContext) */
2078 : 5491 : CurTransactionContext = s->parent->curTransactionContext;
2079 : :
2080 : : /*
2081 : : * Clear the special abort context for next time.
2082 : : */
2083 [ + - ]: 5491 : if (TransactionAbortContext != NULL)
2084 : 5491 : MemoryContextReset(TransactionAbortContext);
2085 : :
2086 : : /*
2087 : : * Delete the subxact local memory contexts. Its CurTransactionContext can
2088 : : * go too (note this also kills CurTransactionContexts from any children
2089 : : * of the subxact).
2090 : : */
2091 [ + - ]: 5491 : if (s->curTransactionContext)
2092 : 5491 : MemoryContextDelete(s->curTransactionContext);
2093 : 5491 : s->curTransactionContext = NULL;
2094 : 5491 : }
2095 : :
2096 : : /* ----------------------------------------------------------------
2097 : : * interface routines
2098 : : * ----------------------------------------------------------------
2099 : : */
2100 : :
2101 : : /*
2102 : : * StartTransaction
2103 : : */
2104 : : static void
2105 : 666148 : StartTransaction(void)
2106 : : {
2107 : : TransactionState s;
2108 : : VirtualTransactionId vxid;
2109 : :
2110 : : /*
2111 : : * Let's just make sure the state stack is empty
2112 : : */
2113 : 666148 : s = &TopTransactionStateData;
2114 : 666148 : CurrentTransactionState = s;
2115 : :
2116 : : Assert(!FullTransactionIdIsValid(XactTopFullTransactionId));
2117 : :
2118 : : /* check the current transaction state */
2119 : : Assert(s->state == TRANS_DEFAULT);
2120 : :
2121 : : /*
2122 : : * Set the current transaction state information appropriately during
2123 : : * start processing. Note that once the transaction status is switched
2124 : : * this process cannot fail until the user ID and the security context
2125 : : * flags are fetched below.
2126 : : */
2127 : 666148 : s->state = TRANS_START;
2128 : 666148 : s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
2129 : :
2130 : : /* Determine if statements are logged in this transaction */
2131 [ - + ]: 666148 : xact_is_sampled = log_xact_sample_rate != 0 &&
2132 [ # # ]: 0 : (log_xact_sample_rate == 1 ||
2133 [ # # ]: 0 : pg_prng_double(&pg_global_prng_state) <= log_xact_sample_rate);
2134 : :
2135 : : /*
2136 : : * initialize current transaction state fields
2137 : : *
2138 : : * note: prevXactReadOnly is not used at the outermost level
2139 : : */
2140 : 666148 : s->nestingLevel = 1;
2141 : 666148 : s->gucNestLevel = 1;
2142 : 666148 : s->childXids = NULL;
2143 : 666148 : s->nChildXids = 0;
2144 : 666148 : s->maxChildXids = 0;
2145 : :
2146 : : /*
2147 : : * Once the current user ID and the security context flags are fetched,
2148 : : * both will be properly reset even if transaction startup fails.
2149 : : */
2150 : 666148 : GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
2151 : :
2152 : : /* SecurityRestrictionContext should never be set outside a transaction */
2153 : : Assert(s->prevSecContext == 0);
2154 : :
2155 : : /*
2156 : : * Make sure we've reset xact state variables
2157 : : *
2158 : : * If recovery is still in progress, mark this transaction as read-only.
2159 : : * We have lower level defences in XLogInsert and elsewhere to stop us
2160 : : * from modifying data during recovery, but this gives the normal
2161 : : * indication to the user that the transaction is read-only.
2162 : : */
2163 [ + + ]: 666148 : if (RecoveryInProgress())
2164 : : {
2165 : 2511 : s->startedInRecovery = true;
2166 : 2511 : XactReadOnly = true;
2167 : : }
2168 : : else
2169 : : {
2170 : 663637 : s->startedInRecovery = false;
2171 : 663637 : XactReadOnly = DefaultXactReadOnly;
2172 : : }
2173 : 666148 : XactDeferrable = DefaultXactDeferrable;
2174 : 666148 : XactIsoLevel = DefaultXactIsoLevel;
2175 : 666148 : forceSyncCommit = false;
2176 : 666148 : MyXactFlags = 0;
2177 : :
2178 : : /*
2179 : : * reinitialize within-transaction counters
2180 : : */
2181 : 666148 : s->subTransactionId = TopSubTransactionId;
2182 : 666148 : currentSubTransactionId = TopSubTransactionId;
2183 : 666148 : currentCommandId = FirstCommandId;
2184 : 666148 : currentCommandIdUsed = false;
2185 : :
2186 : : /*
2187 : : * initialize reported xid accounting
2188 : : */
2189 : 666148 : nUnreportedXids = 0;
2190 : 666148 : s->didLogXid = false;
2191 : :
2192 : : /*
2193 : : * must initialize resource-management stuff first
2194 : : */
2195 : 666148 : AtStart_Memory();
2196 : 666148 : AtStart_ResourceOwner();
2197 : :
2198 : : /*
2199 : : * Assign a new LocalTransactionId, and combine it with the proc number to
2200 : : * form a virtual transaction id.
2201 : : */
2202 : 666148 : vxid.procNumber = MyProcNumber;
2203 : 666148 : vxid.localTransactionId = GetNextLocalTransactionId();
2204 : :
2205 : : /*
2206 : : * Lock the virtual transaction id before we announce it in the proc array
2207 : : */
2208 : 666148 : VirtualXactLockTableInsert(vxid);
2209 : :
2210 : : /*
2211 : : * Advertise it in the proc array. We assume assignment of
2212 : : * localTransactionId is atomic, and the proc number should be set
2213 : : * already.
2214 : : */
2215 : : Assert(MyProc->vxid.procNumber == vxid.procNumber);
2216 : 666148 : MyProc->vxid.lxid = vxid.localTransactionId;
2217 : :
2218 : : TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
2219 : :
2220 : : /*
2221 : : * set transaction_timestamp() (a/k/a now()). Normally, we want this to
2222 : : * be the same as the first command's statement_timestamp(), so don't do a
2223 : : * fresh GetCurrentTimestamp() call (which'd be expensive anyway). But
2224 : : * for transactions started inside procedures (i.e., nonatomic SPI
2225 : : * contexts), we do need to advance the timestamp. Also, in a parallel
2226 : : * worker, the timestamp should already have been provided by a call to
2227 : : * SetParallelStartTimestamps().
2228 : : */
2229 [ + + ]: 666148 : if (!IsParallelWorker())
2230 : : {
2231 [ + + ]: 660088 : if (!SPI_inside_nonatomic_context())
2232 : 657867 : xactStartTimestamp = stmtStartTimestamp;
2233 : : else
2234 : 2221 : xactStartTimestamp = GetCurrentTimestamp();
2235 : : }
2236 : : else
2237 : : Assert(xactStartTimestamp != 0);
2238 : 666148 : pgstat_report_xact_timestamp(xactStartTimestamp);
2239 : : /* Mark xactStopTimestamp as unset. */
2240 : 666148 : xactStopTimestamp = 0;
2241 : :
2242 : : /*
2243 : : * initialize other subsystems for new transaction
2244 : : */
2245 : 666148 : AtStart_GUC();
2246 : 666148 : AtStart_Cache();
2247 : 666148 : AfterTriggerBeginXact();
2248 : :
2249 : : /*
2250 : : * done with start processing, set current transaction state to "in
2251 : : * progress"
2252 : : */
2253 : 666148 : s->state = TRANS_INPROGRESS;
2254 : :
2255 : : /* Schedule transaction timeout */
2256 [ + + ]: 666148 : if (TransactionTimeout > 0)
2257 : 1 : enable_timeout_after(TRANSACTION_TIMEOUT, TransactionTimeout);
2258 : :
2259 : 666148 : ShowTransactionState("StartTransaction");
2260 : 666148 : }
2261 : :
2262 : :
2263 : : /*
2264 : : * CommitTransaction
2265 : : *
2266 : : * NB: if you change this routine, better look at PrepareTransaction too!
2267 : : */
2268 : : static void
2269 : 629960 : CommitTransaction(void)
2270 : : {
2271 : 629960 : TransactionState s = CurrentTransactionState;
2272 : : TransactionId latestXid;
2273 : : bool is_parallel_worker;
2274 : :
2275 : 629960 : is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2276 : :
2277 : : /* Enforce parallel mode restrictions during parallel worker commit. */
2278 [ + + ]: 629960 : if (is_parallel_worker)
2279 : 2012 : EnterParallelMode();
2280 : :
2281 : 629960 : ShowTransactionState("CommitTransaction");
2282 : :
2283 : : /*
2284 : : * check the current transaction state
2285 : : */
2286 [ - + ]: 629960 : if (s->state != TRANS_INPROGRESS)
2287 [ # # ]: 0 : elog(WARNING, "CommitTransaction while in %s state",
2288 : : TransStateAsString(s->state));
2289 : : Assert(s->parent == NULL);
2290 : :
2291 : : /*
2292 : : * Do pre-commit processing that involves calling user-defined code, such
2293 : : * as triggers. SECURITY_RESTRICTED_OPERATION contexts must not queue an
2294 : : * action that would run here, because that would bypass the sandbox.
2295 : : * Since closing cursors could queue trigger actions, triggers could open
2296 : : * cursors, etc, we have to keep looping until there's nothing left to do.
2297 : : */
2298 : : for (;;)
2299 : : {
2300 : : /*
2301 : : * Fire all currently pending deferred triggers.
2302 : : */
2303 : 635901 : AfterTriggerFireDeferred();
2304 : :
2305 : : /*
2306 : : * Close open portals (converting holdable ones into static portals).
2307 : : * If there weren't any, we are done ... otherwise loop back to check
2308 : : * if they queued deferred triggers. Lather, rinse, repeat.
2309 : : */
2310 [ + + ]: 635757 : if (!PreCommit_Portals(false))
2311 : 629816 : break;
2312 : : }
2313 : :
2314 : : /*
2315 : : * The remaining actions cannot call any user-defined code, so it's safe
2316 : : * to start shutting down within-transaction services. But note that most
2317 : : * of this stuff could still throw an error, which would switch us into
2318 : : * the transaction-abort path.
2319 : : */
2320 : :
2321 [ + + ]: 629816 : CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_PRE_COMMIT
2322 : : : XACT_EVENT_PRE_COMMIT);
2323 : :
2324 : : /*
2325 : : * If this xact has started any unfinished parallel operation, clean up
2326 : : * its workers, warning about leaked resources. (But we don't actually
2327 : : * reset parallelModeLevel till entering TRANS_COMMIT, a bit below. This
2328 : : * keeps parallel mode restrictions active as long as possible in a
2329 : : * parallel worker.)
2330 : : */
2331 : 629816 : AtEOXact_Parallel(true);
2332 [ + + ]: 629816 : if (is_parallel_worker)
2333 : : {
2334 [ - + ]: 2012 : if (s->parallelModeLevel != 1)
2335 [ # # ]: 0 : elog(WARNING, "parallelModeLevel is %d not 1 at end of parallel worker transaction",
2336 : : s->parallelModeLevel);
2337 : : }
2338 : : else
2339 : : {
2340 [ - + ]: 627804 : if (s->parallelModeLevel != 0)
2341 [ # # ]: 0 : elog(WARNING, "parallelModeLevel is %d not 0 at end of transaction",
2342 : : s->parallelModeLevel);
2343 : : }
2344 : :
2345 : : /* Shut down the deferred-trigger manager */
2346 : 629816 : AfterTriggerEndXact(true);
2347 : :
2348 : : /*
2349 : : * Let ON COMMIT management do its thing (must happen after closing
2350 : : * cursors, to avoid dangling-reference problems)
2351 : : */
2352 : 629816 : PreCommit_on_commit_actions();
2353 : :
2354 : : /*
2355 : : * Synchronize files that are created and not WAL-logged during this
2356 : : * transaction. This must happen before AtEOXact_RelationMap(), so that we
2357 : : * don't see committed-but-broken files after a crash.
2358 : : */
2359 : 629812 : smgrDoPendingSyncs(true, is_parallel_worker);
2360 : :
2361 : : /* close large objects before lower-level cleanup */
2362 : 629812 : AtEOXact_LargeObject(true);
2363 : :
2364 : : /*
2365 : : * Insert notifications sent by NOTIFY commands into the queue. This
2366 : : * should be late in the pre-commit sequence to minimize time spent
2367 : : * holding the notify-insertion lock. However, this could result in
2368 : : * creating a snapshot, so we must do it before serializable cleanup.
2369 : : */
2370 : 629812 : PreCommit_Notify();
2371 : :
2372 : : /*
2373 : : * Mark serializable transaction as complete for predicate locking
2374 : : * purposes. This should be done as late as we can put it and still allow
2375 : : * errors to be raised for failure patterns found at commit. This is not
2376 : : * appropriate in a parallel worker however, because we aren't committing
2377 : : * the leader's transaction and its serializable state will live on.
2378 : : */
2379 [ + + ]: 629812 : if (!is_parallel_worker)
2380 : 627800 : PreCommit_CheckForSerializationFailure();
2381 : :
2382 : : /* Prevent cancel/die interrupt while cleaning up */
2383 : 629657 : HOLD_INTERRUPTS();
2384 : :
2385 : : /* Commit updates to the relation map --- do this as late as possible */
2386 : 629657 : AtEOXact_RelationMap(true, is_parallel_worker);
2387 : :
2388 : : /*
2389 : : * set the current transaction state information appropriately during
2390 : : * commit processing
2391 : : */
2392 : 629657 : s->state = TRANS_COMMIT;
2393 : 629657 : s->parallelModeLevel = 0;
2394 : 629657 : s->parallelChildXact = false; /* should be false already */
2395 : :
2396 : : /* Disable transaction timeout */
2397 [ + + ]: 629657 : if (TransactionTimeout > 0)
2398 : 1 : disable_timeout(TRANSACTION_TIMEOUT, false);
2399 : :
2400 [ + + ]: 629657 : if (!is_parallel_worker)
2401 : : {
2402 : : /*
2403 : : * We need to mark our XIDs as committed in pg_xact. This is where we
2404 : : * durably commit.
2405 : : */
2406 : 627645 : latestXid = RecordTransactionCommit();
2407 : : }
2408 : : else
2409 : : {
2410 : : /*
2411 : : * We must not mark our XID committed; the parallel leader is
2412 : : * responsible for that.
2413 : : */
2414 : 2012 : latestXid = InvalidTransactionId;
2415 : :
2416 : : /*
2417 : : * Make sure the leader will know about any WAL we wrote before it
2418 : : * commits.
2419 : : */
2420 : 2012 : ParallelWorkerReportLastRecEnd(XactLastRecEnd);
2421 : : }
2422 : :
2423 : : TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->vxid.lxid);
2424 : :
2425 : : /*
2426 : : * Let others know about no transaction in progress by me. Note that this
2427 : : * must be done _before_ releasing locks we hold and _after_
2428 : : * RecordTransactionCommit.
2429 : : */
2430 : 629657 : ProcArrayEndTransaction(MyProc, latestXid);
2431 : :
2432 : : /*
2433 : : * This is all post-commit cleanup. Note that if an error is raised here,
2434 : : * it's too late to abort the transaction. This should be just
2435 : : * noncritical resource releasing.
2436 : : *
2437 : : * The ordering of operations is not entirely random. The idea is:
2438 : : * release resources visible to other backends (eg, files, buffer pins);
2439 : : * then release locks; then release backend-local resources. We want to
2440 : : * release locks at the point where any backend waiting for us will see
2441 : : * our transaction as being fully cleaned up.
2442 : : *
2443 : : * Resources that can be associated with individual queries are handled by
2444 : : * the ResourceOwner mechanism. The other calls here are for backend-wide
2445 : : * state.
2446 : : */
2447 : :
2448 : 629657 : CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2449 : : : XACT_EVENT_COMMIT);
2450 : :
2451 : 629657 : CurrentResourceOwner = NULL;
2452 : 629657 : ResourceOwnerRelease(TopTransactionResourceOwner,
2453 : : RESOURCE_RELEASE_BEFORE_LOCKS,
2454 : : true, true);
2455 : :
2456 : 629657 : AtEOXact_Aio(true);
2457 : :
2458 : : /* Check we've released all buffer pins */
2459 : 629657 : AtEOXact_Buffers(true);
2460 : :
2461 : : /* Clean up the relation cache */
2462 : 629657 : AtEOXact_RelationCache(true);
2463 : :
2464 : : /* Clean up the type cache */
2465 : 629657 : AtEOXact_TypeCache();
2466 : :
2467 : : /*
2468 : : * Make catalog changes visible to all backends. This has to happen after
2469 : : * relcache references are dropped (see comments for
2470 : : * AtEOXact_RelationCache), but before locks are released (if anyone is
2471 : : * waiting for lock on a relation we've modified, we want them to know
2472 : : * about the catalog change before they start using the relation).
2473 : : */
2474 : 629657 : AtEOXact_Inval(true);
2475 : :
2476 : 629657 : AtEOXact_MultiXact();
2477 : :
2478 : 629657 : ResourceOwnerRelease(TopTransactionResourceOwner,
2479 : : RESOURCE_RELEASE_LOCKS,
2480 : : true, true);
2481 : 629657 : ResourceOwnerRelease(TopTransactionResourceOwner,
2482 : : RESOURCE_RELEASE_AFTER_LOCKS,
2483 : : true, true);
2484 : :
2485 : : /*
2486 : : * Likewise, dropping of files deleted during the transaction is best done
2487 : : * after releasing relcache and buffer pins. (This is not strictly
2488 : : * necessary during commit, since such pins should have been released
2489 : : * already, but this ordering is definitely critical during abort.) Since
2490 : : * this may take many seconds, also delay until after releasing locks.
2491 : : * Other backends will observe the attendant catalog changes and not
2492 : : * attempt to access affected files.
2493 : : */
2494 : 629657 : smgrDoPendingDeletes(true);
2495 : :
2496 : : /*
2497 : : * Send out notification signals to other backends (and do other
2498 : : * post-commit NOTIFY cleanup). This must not happen until after our
2499 : : * transaction is fully done from the viewpoint of other backends.
2500 : : */
2501 : 629657 : AtCommit_Notify();
2502 : :
2503 : : /*
2504 : : * Everything after this should be purely internal-to-this-backend
2505 : : * cleanup.
2506 : : */
2507 : 629657 : AtEOXact_GUC(true, 1);
2508 : 629657 : AtEOXact_SPI(true);
2509 : 629657 : AtEOXact_Enum();
2510 : 629657 : AtEOXact_on_commit_actions(true);
2511 : 629657 : AtEOXact_Namespace(true, is_parallel_worker);
2512 : 629657 : AtEOXact_SMgr();
2513 : 629657 : AtEOXact_Files(true);
2514 : 629657 : AtEOXact_ComboCid();
2515 : 629657 : AtEOXact_HashTables(true);
2516 : 629657 : AtEOXact_RI(true);
2517 : 629657 : AtEOXact_PgStat(true, is_parallel_worker);
2518 : 629657 : AtEOXact_Snapshot(true, false);
2519 : 629657 : AtEOXact_ApplyLauncher(true);
2520 : 629657 : AtEOXact_LogicalRepWorkers(true);
2521 : 629657 : AtEOXact_LogicalCtl();
2522 : 629657 : pgstat_report_xact_timestamp(0);
2523 : :
2524 : 629657 : ResourceOwnerDelete(TopTransactionResourceOwner);
2525 : 629657 : s->curTransactionOwner = NULL;
2526 : 629657 : CurTransactionResourceOwner = NULL;
2527 : 629657 : TopTransactionResourceOwner = NULL;
2528 : :
2529 : 629657 : AtCommit_Memory();
2530 : :
2531 : 629657 : s->fullTransactionId = InvalidFullTransactionId;
2532 : 629657 : s->subTransactionId = InvalidSubTransactionId;
2533 : 629657 : s->nestingLevel = 0;
2534 : 629657 : s->gucNestLevel = 0;
2535 : 629657 : s->childXids = NULL;
2536 : 629657 : s->nChildXids = 0;
2537 : 629657 : s->maxChildXids = 0;
2538 : :
2539 : 629657 : XactTopFullTransactionId = InvalidFullTransactionId;
2540 : 629657 : nParallelCurrentXids = 0;
2541 : :
2542 : : /*
2543 : : * done with commit processing, set current transaction state back to
2544 : : * default
2545 : : */
2546 : 629657 : s->state = TRANS_DEFAULT;
2547 : :
2548 : 629657 : RESUME_INTERRUPTS();
2549 : 629657 : }
2550 : :
2551 : :
2552 : : /*
2553 : : * PrepareTransaction
2554 : : *
2555 : : * NB: if you change this routine, better look at CommitTransaction too!
2556 : : */
2557 : : static void
2558 : 384 : PrepareTransaction(void)
2559 : : {
2560 : 384 : TransactionState s = CurrentTransactionState;
2561 : 384 : FullTransactionId fxid = GetCurrentFullTransactionId();
2562 : : GlobalTransaction gxact;
2563 : : TimestampTz prepared_at;
2564 : :
2565 : : Assert(!IsInParallelMode());
2566 : :
2567 : 384 : ShowTransactionState("PrepareTransaction");
2568 : :
2569 : : /*
2570 : : * check the current transaction state
2571 : : */
2572 [ - + ]: 384 : if (s->state != TRANS_INPROGRESS)
2573 [ # # ]: 0 : elog(WARNING, "PrepareTransaction while in %s state",
2574 : : TransStateAsString(s->state));
2575 : : Assert(s->parent == NULL);
2576 : :
2577 : : /*
2578 : : * Do pre-commit processing that involves calling user-defined code, such
2579 : : * as triggers. Since closing cursors could queue trigger actions,
2580 : : * triggers could open cursors, etc, we have to keep looping until there's
2581 : : * nothing left to do.
2582 : : */
2583 : : for (;;)
2584 : : {
2585 : : /*
2586 : : * Fire all currently pending deferred triggers.
2587 : : */
2588 : 386 : AfterTriggerFireDeferred();
2589 : :
2590 : : /*
2591 : : * Close open portals (converting holdable ones into static portals).
2592 : : * If there weren't any, we are done ... otherwise loop back to check
2593 : : * if they queued deferred triggers. Lather, rinse, repeat.
2594 : : */
2595 [ + + ]: 386 : if (!PreCommit_Portals(true))
2596 : 384 : break;
2597 : : }
2598 : :
2599 : 384 : CallXactCallbacks(XACT_EVENT_PRE_PREPARE);
2600 : :
2601 : : /*
2602 : : * The remaining actions cannot call any user-defined code, so it's safe
2603 : : * to start shutting down within-transaction services. But note that most
2604 : : * of this stuff could still throw an error, which would switch us into
2605 : : * the transaction-abort path.
2606 : : */
2607 : :
2608 : : /* Shut down the deferred-trigger manager */
2609 : 383 : AfterTriggerEndXact(true);
2610 : :
2611 : : /*
2612 : : * Let ON COMMIT management do its thing (must happen after closing
2613 : : * cursors, to avoid dangling-reference problems)
2614 : : */
2615 : 383 : PreCommit_on_commit_actions();
2616 : :
2617 : : /*
2618 : : * Synchronize files that are created and not WAL-logged during this
2619 : : * transaction. This must happen before EndPrepare(), so that we don't see
2620 : : * committed-but-broken files after a crash and COMMIT PREPARED.
2621 : : */
2622 : 383 : smgrDoPendingSyncs(true, false);
2623 : :
2624 : : /* close large objects before lower-level cleanup */
2625 : 383 : AtEOXact_LargeObject(true);
2626 : :
2627 : : /* NOTIFY requires no work at this point */
2628 : :
2629 : : /*
2630 : : * Mark serializable transaction as complete for predicate locking
2631 : : * purposes. This should be done as late as we can put it and still allow
2632 : : * errors to be raised for failure patterns found at commit.
2633 : : */
2634 : 383 : PreCommit_CheckForSerializationFailure();
2635 : :
2636 : : /*
2637 : : * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2638 : : * this transaction. Having the prepared xact hold locks on another
2639 : : * backend's temp table seems a bad idea --- for instance it would prevent
2640 : : * the backend from exiting. There are other problems too, such as how to
2641 : : * clean up the source backend's local buffers and ON COMMIT state if the
2642 : : * prepared xact includes a DROP of a temp table.
2643 : : *
2644 : : * Other objects types, like functions, operators or extensions, share the
2645 : : * same restriction as they should not be created, locked or dropped as
2646 : : * this can mess up with this session or even a follow-up session trying
2647 : : * to use the same temporary namespace.
2648 : : *
2649 : : * We must check this after executing any ON COMMIT actions, because they
2650 : : * might still access a temp relation.
2651 : : *
2652 : : * XXX In principle this could be relaxed to allow some useful special
2653 : : * cases, such as a temp table created and dropped all within the
2654 : : * transaction. That seems to require much more bookkeeping though.
2655 : : */
2656 [ + + ]: 383 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
2657 [ + - ]: 45 : ereport(ERROR,
2658 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2659 : : errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2660 : :
2661 : : /*
2662 : : * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2663 : : * supported if we added cleanup logic to twophase.c, but for now it
2664 : : * doesn't seem worth the trouble.
2665 : : */
2666 [ - + ]: 338 : if (XactHasExportedSnapshots())
2667 [ # # ]: 0 : ereport(ERROR,
2668 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2669 : : errmsg("cannot PREPARE a transaction that has exported snapshots")));
2670 : :
2671 : : /* Prevent cancel/die interrupt while cleaning up */
2672 : 338 : HOLD_INTERRUPTS();
2673 : :
2674 : : /*
2675 : : * set the current transaction state information appropriately during
2676 : : * prepare processing
2677 : : */
2678 : 338 : s->state = TRANS_PREPARE;
2679 : :
2680 : : /* Disable transaction timeout */
2681 [ - + ]: 338 : if (TransactionTimeout > 0)
2682 : 0 : disable_timeout(TRANSACTION_TIMEOUT, false);
2683 : :
2684 : 338 : prepared_at = GetCurrentTimestamp();
2685 : :
2686 : : /*
2687 : : * Reserve the GID for this transaction. This could fail if the requested
2688 : : * GID is invalid or already in use.
2689 : : */
2690 : 338 : gxact = MarkAsPreparing(fxid, prepareGID, prepared_at,
2691 : : GetUserId(), MyDatabaseId);
2692 : 320 : prepareGID = NULL;
2693 : :
2694 : : /*
2695 : : * Collect data for the 2PC state file. Note that in general, no actual
2696 : : * state change should happen in the called modules during this step,
2697 : : * since it's still possible to fail before commit, and in that case we
2698 : : * want transaction abort to be able to clean up. (In particular, the
2699 : : * AtPrepare routines may error out if they find cases they cannot
2700 : : * handle.) State cleanup should happen in the PostPrepare routines
2701 : : * below. However, some modules can go ahead and clear state here because
2702 : : * they wouldn't do anything with it during abort anyway.
2703 : : *
2704 : : * Note: because the 2PC state file records will be replayed in the same
2705 : : * order they are made, the order of these calls has to match the order in
2706 : : * which we want things to happen during COMMIT PREPARED or ROLLBACK
2707 : : * PREPARED; in particular, pay attention to whether things should happen
2708 : : * before or after releasing the transaction's locks.
2709 : : */
2710 : 320 : StartPrepare(gxact);
2711 : :
2712 : 320 : AtPrepare_Notify();
2713 : 320 : AtPrepare_Locks();
2714 : 318 : AtPrepare_PredicateLocks();
2715 : 318 : AtPrepare_PgStat();
2716 : 318 : AtPrepare_MultiXact();
2717 : 318 : AtPrepare_RelationMap();
2718 : :
2719 : : /*
2720 : : * Here is where we really truly prepare.
2721 : : *
2722 : : * We have to record transaction prepares even if we didn't make any
2723 : : * updates, because the transaction manager might get confused if we lose
2724 : : * a global transaction.
2725 : : */
2726 : 318 : EndPrepare(gxact);
2727 : :
2728 : : /*
2729 : : * Now we clean up backend-internal state and release internal resources.
2730 : : */
2731 : :
2732 : : /* Reset XactLastRecEnd until the next transaction writes something */
2733 : 318 : XactLastRecEnd = 0;
2734 : :
2735 : : /*
2736 : : * Transfer our locks to a dummy PGPROC. This has to be done before
2737 : : * ProcArrayClearTransaction(). Otherwise, a GetLockConflicts() would
2738 : : * conclude "xact already committed or aborted" for our locks.
2739 : : */
2740 : 318 : PostPrepare_Locks(fxid);
2741 : :
2742 : : /*
2743 : : * Let others know about no transaction in progress by me. This has to be
2744 : : * done *after* the prepared transaction has been marked valid, else
2745 : : * someone may think it is unlocked and recyclable.
2746 : : */
2747 : 318 : ProcArrayClearTransaction(MyProc);
2748 : :
2749 : : /*
2750 : : * In normal commit-processing, this is all non-critical post-transaction
2751 : : * cleanup. When the transaction is prepared, however, it's important
2752 : : * that the locks and other per-backend resources are transferred to the
2753 : : * prepared transaction's PGPROC entry. Note that if an error is raised
2754 : : * here, it's too late to abort the transaction. XXX: This probably should
2755 : : * be in a critical section, to force a PANIC if any of this fails, but
2756 : : * that cure could be worse than the disease.
2757 : : */
2758 : :
2759 : 318 : CallXactCallbacks(XACT_EVENT_PREPARE);
2760 : :
2761 : 318 : ResourceOwnerRelease(TopTransactionResourceOwner,
2762 : : RESOURCE_RELEASE_BEFORE_LOCKS,
2763 : : true, true);
2764 : :
2765 : 318 : AtEOXact_Aio(true);
2766 : :
2767 : : /* Check we've released all buffer pins */
2768 : 318 : AtEOXact_Buffers(true);
2769 : :
2770 : : /* Clean up the relation cache */
2771 : 318 : AtEOXact_RelationCache(true);
2772 : :
2773 : : /* Clean up the type cache */
2774 : 318 : AtEOXact_TypeCache();
2775 : :
2776 : : /* notify doesn't need a postprepare call */
2777 : :
2778 : 318 : PostPrepare_PgStat();
2779 : :
2780 : 318 : PostPrepare_Inval();
2781 : :
2782 : 318 : PostPrepare_smgr();
2783 : :
2784 : 318 : PostPrepare_MultiXact(fxid);
2785 : :
2786 : 318 : PostPrepare_PredicateLocks(fxid);
2787 : :
2788 : 318 : ResourceOwnerRelease(TopTransactionResourceOwner,
2789 : : RESOURCE_RELEASE_LOCKS,
2790 : : true, true);
2791 : 318 : ResourceOwnerRelease(TopTransactionResourceOwner,
2792 : : RESOURCE_RELEASE_AFTER_LOCKS,
2793 : : true, true);
2794 : :
2795 : : /*
2796 : : * Allow another backend to finish the transaction. After
2797 : : * PostPrepare_Twophase(), the transaction is completely detached from our
2798 : : * backend. The rest is just non-critical cleanup of backend-local state.
2799 : : */
2800 : 318 : PostPrepare_Twophase();
2801 : :
2802 : : /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2803 : 318 : AtEOXact_GUC(true, 1);
2804 : 318 : AtEOXact_SPI(true);
2805 : 318 : AtEOXact_Enum();
2806 : 318 : AtEOXact_on_commit_actions(true);
2807 : 318 : AtEOXact_Namespace(true, false);
2808 : 318 : AtEOXact_SMgr();
2809 : 318 : AtEOXact_Files(true);
2810 : 318 : AtEOXact_ComboCid();
2811 : 318 : AtEOXact_HashTables(true);
2812 : 318 : AtEOXact_RI(true);
2813 : : /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2814 : 318 : AtEOXact_Snapshot(true, true);
2815 : : /* we treat PREPARE as ROLLBACK so far as waking workers goes */
2816 : 318 : AtEOXact_ApplyLauncher(false);
2817 : 318 : AtEOXact_LogicalRepWorkers(false);
2818 : 318 : AtEOXact_LogicalCtl();
2819 : 318 : pgstat_report_xact_timestamp(0);
2820 : :
2821 : 318 : CurrentResourceOwner = NULL;
2822 : 318 : ResourceOwnerDelete(TopTransactionResourceOwner);
2823 : 318 : s->curTransactionOwner = NULL;
2824 : 318 : CurTransactionResourceOwner = NULL;
2825 : 318 : TopTransactionResourceOwner = NULL;
2826 : :
2827 : 318 : AtCommit_Memory();
2828 : :
2829 : 318 : s->fullTransactionId = InvalidFullTransactionId;
2830 : 318 : s->subTransactionId = InvalidSubTransactionId;
2831 : 318 : s->nestingLevel = 0;
2832 : 318 : s->gucNestLevel = 0;
2833 : 318 : s->childXids = NULL;
2834 : 318 : s->nChildXids = 0;
2835 : 318 : s->maxChildXids = 0;
2836 : :
2837 : 318 : XactTopFullTransactionId = InvalidFullTransactionId;
2838 : 318 : nParallelCurrentXids = 0;
2839 : :
2840 : : /*
2841 : : * done with 1st phase commit processing, set current transaction state
2842 : : * back to default
2843 : : */
2844 : 318 : s->state = TRANS_DEFAULT;
2845 : :
2846 : 318 : RESUME_INTERRUPTS();
2847 : 318 : }
2848 : :
2849 : :
2850 : : /*
2851 : : * AbortTransaction
2852 : : */
2853 : : static void
2854 : 36173 : AbortTransaction(void)
2855 : : {
2856 : 36173 : TransactionState s = CurrentTransactionState;
2857 : : TransactionId latestXid;
2858 : : bool is_parallel_worker;
2859 : :
2860 : : /* Prevent cancel/die interrupt while cleaning up */
2861 : 36173 : HOLD_INTERRUPTS();
2862 : :
2863 : : /* Disable transaction timeout */
2864 [ + + ]: 36173 : if (TransactionTimeout > 0)
2865 : 1 : disable_timeout(TRANSACTION_TIMEOUT, false);
2866 : :
2867 : : /* Make sure we have a valid memory context and resource owner */
2868 : 36173 : AtAbort_Memory();
2869 : 36173 : AtAbort_ResourceOwner();
2870 : :
2871 : : /*
2872 : : * Release any LW locks we might be holding as quickly as possible.
2873 : : * (Regular locks, however, must be held till we finish aborting.)
2874 : : * Releasing LW locks is critical since we might try to grab them again
2875 : : * while cleaning up!
2876 : : */
2877 : 36173 : LWLockReleaseAll();
2878 : :
2879 : : /*
2880 : : * Cleanup waiting for LSN if any.
2881 : : */
2882 : 36173 : WaitLSNCleanup();
2883 : :
2884 : : /* Clear wait information and command progress indicator */
2885 : 36173 : pgstat_report_wait_end();
2886 : 36173 : pgstat_progress_end_command();
2887 : :
2888 : 36173 : pgaio_error_cleanup();
2889 : :
2890 : : /* Clean up buffer content locks, too */
2891 : 36173 : UnlockBuffers();
2892 : :
2893 : : /* Reset WAL record construction state */
2894 : 36173 : XLogResetInsertion();
2895 : :
2896 : : /* Cancel condition variable sleep */
2897 : 36173 : ConditionVariableCancelSleep();
2898 : :
2899 : : /*
2900 : : * Also clean up any open wait for lock, since the lock manager will choke
2901 : : * if we try to wait for another lock before doing this.
2902 : : */
2903 : 36173 : LockErrorCleanup();
2904 : :
2905 : : /*
2906 : : * If any timeout events are still active, make sure the timeout interrupt
2907 : : * is scheduled. This covers possible loss of a timeout interrupt due to
2908 : : * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2909 : : * We delay this till after LockErrorCleanup so that we don't uselessly
2910 : : * reschedule lock or deadlock check timeouts.
2911 : : */
2912 : 36173 : reschedule_timeouts();
2913 : :
2914 : : /*
2915 : : * Re-enable signals, in case we got here by longjmp'ing out of a signal
2916 : : * handler. We do this fairly early in the sequence so that the timeout
2917 : : * infrastructure will be functional if needed while aborting.
2918 : : */
2919 : 36173 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
2920 : :
2921 : : /*
2922 : : * check the current transaction state
2923 : : */
2924 : 36173 : is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2925 [ + + - + ]: 36173 : if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2926 [ # # ]: 0 : elog(WARNING, "AbortTransaction while in %s state",
2927 : : TransStateAsString(s->state));
2928 : : Assert(s->parent == NULL);
2929 : :
2930 : : /*
2931 : : * set the current transaction state information appropriately during the
2932 : : * abort processing
2933 : : */
2934 : 36173 : s->state = TRANS_ABORT;
2935 : :
2936 : : /*
2937 : : * Reset user ID which might have been changed transiently. We need this
2938 : : * to clean up in case control escaped out of a SECURITY DEFINER function
2939 : : * or other local change of CurrentUserId; therefore, the prior value of
2940 : : * SecurityRestrictionContext also needs to be restored.
2941 : : *
2942 : : * (Note: it is not necessary to restore session authorization or role
2943 : : * settings here because those can only be changed via GUC, and GUC will
2944 : : * take care of rolling them back if need be.)
2945 : : */
2946 : 36173 : SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
2947 : :
2948 : : /* Forget about any active REINDEX. */
2949 : 36173 : ResetReindexState(s->nestingLevel);
2950 : :
2951 : : /* Reset logical streaming state. */
2952 : 36173 : ResetLogicalStreamingState();
2953 : :
2954 : : /* Reset snapshot export state. */
2955 : 36173 : SnapBuildResetExportedSnapshotState();
2956 : :
2957 : : /*
2958 : : * If this xact has started any unfinished parallel operation, clean up
2959 : : * its workers and exit parallel mode. Don't warn about leaked resources.
2960 : : */
2961 : 36173 : AtEOXact_Parallel(false);
2962 : 36173 : s->parallelModeLevel = 0;
2963 : 36173 : s->parallelChildXact = false; /* should be false already */
2964 : :
2965 : : /*
2966 : : * do abort processing
2967 : : */
2968 : 36173 : AfterTriggerEndXact(false); /* 'false' means it's abort */
2969 : 36173 : AtAbort_Portals();
2970 : 36173 : smgrDoPendingSyncs(false, is_parallel_worker);
2971 : 36173 : AtEOXact_LargeObject(false);
2972 : 36173 : AtAbort_Notify();
2973 : 36173 : AtEOXact_RelationMap(false, is_parallel_worker);
2974 : 36173 : AtAbort_Twophase();
2975 : :
2976 : : /*
2977 : : * Advertise the fact that we aborted in pg_xact (assuming that we got as
2978 : : * far as assigning an XID to advertise). But if we're inside a parallel
2979 : : * worker, skip this; the user backend must be the one to write the abort
2980 : : * record.
2981 : : */
2982 [ + + ]: 36173 : if (!is_parallel_worker)
2983 : 36165 : latestXid = RecordTransactionAbort(false);
2984 : : else
2985 : : {
2986 : 8 : latestXid = InvalidTransactionId;
2987 : :
2988 : : /*
2989 : : * Since the parallel leader won't get our value of XactLastRecEnd in
2990 : : * this case, we nudge WAL-writer ourselves in this case. See related
2991 : : * comments in RecordTransactionAbort for why this matters.
2992 : : */
2993 : 8 : XLogSetAsyncXactLSN(XactLastRecEnd);
2994 : : }
2995 : :
2996 : : TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->vxid.lxid);
2997 : :
2998 : : /*
2999 : : * Let others know about no transaction in progress by me. Note that this
3000 : : * must be done _before_ releasing locks we hold and _after_
3001 : : * RecordTransactionAbort.
3002 : : */
3003 : 36173 : ProcArrayEndTransaction(MyProc, latestXid);
3004 : :
3005 : : /*
3006 : : * Post-abort cleanup. See notes in CommitTransaction() concerning
3007 : : * ordering. We can skip all of it if the transaction failed before
3008 : : * creating a resource owner.
3009 : : */
3010 [ + - ]: 36173 : if (TopTransactionResourceOwner != NULL)
3011 : : {
3012 [ + + ]: 36173 : if (is_parallel_worker)
3013 : 8 : CallXactCallbacks(XACT_EVENT_PARALLEL_ABORT);
3014 : : else
3015 : 36165 : CallXactCallbacks(XACT_EVENT_ABORT);
3016 : :
3017 : 36173 : ResourceOwnerRelease(TopTransactionResourceOwner,
3018 : : RESOURCE_RELEASE_BEFORE_LOCKS,
3019 : : false, true);
3020 : 36173 : AtEOXact_Aio(false);
3021 : 36173 : AtEOXact_Buffers(false);
3022 : 36173 : AtEOXact_RelationCache(false);
3023 : 36173 : AtEOXact_TypeCache();
3024 : 36173 : AtEOXact_Inval(false);
3025 : 36173 : AtEOXact_MultiXact();
3026 : 36173 : ResourceOwnerRelease(TopTransactionResourceOwner,
3027 : : RESOURCE_RELEASE_LOCKS,
3028 : : false, true);
3029 : 36173 : ResourceOwnerRelease(TopTransactionResourceOwner,
3030 : : RESOURCE_RELEASE_AFTER_LOCKS,
3031 : : false, true);
3032 : 36173 : smgrDoPendingDeletes(false);
3033 : :
3034 : 36173 : AtEOXact_GUC(false, 1);
3035 : 36173 : AtEOXact_SPI(false);
3036 : 36173 : AtEOXact_Enum();
3037 : 36173 : AtEOXact_on_commit_actions(false);
3038 : 36173 : AtEOXact_Namespace(false, is_parallel_worker);
3039 : 36173 : AtEOXact_SMgr();
3040 : 36173 : AtEOXact_Files(false);
3041 : 36173 : AtEOXact_ComboCid();
3042 : 36173 : AtEOXact_HashTables(false);
3043 : 36173 : AtEOXact_RI(false);
3044 : 36173 : AtEOXact_PgStat(false, is_parallel_worker);
3045 : 36173 : AtEOXact_ApplyLauncher(false);
3046 : 36173 : AtEOXact_LogicalRepWorkers(false);
3047 : 36173 : AtEOXact_LogicalCtl();
3048 : 36173 : pgstat_report_xact_timestamp(0);
3049 : : }
3050 : :
3051 : : /*
3052 : : * State remains TRANS_ABORT until CleanupTransaction().
3053 : : */
3054 : 36173 : RESUME_INTERRUPTS();
3055 : 36173 : }
3056 : :
3057 : : /*
3058 : : * CleanupTransaction
3059 : : */
3060 : : static void
3061 : 36173 : CleanupTransaction(void)
3062 : : {
3063 : 36173 : TransactionState s = CurrentTransactionState;
3064 : :
3065 : : /*
3066 : : * State should still be TRANS_ABORT from AbortTransaction().
3067 : : */
3068 [ - + ]: 36173 : if (s->state != TRANS_ABORT)
3069 [ # # ]: 0 : elog(FATAL, "CleanupTransaction: unexpected state %s",
3070 : : TransStateAsString(s->state));
3071 : :
3072 : : /*
3073 : : * do abort cleanup processing
3074 : : */
3075 : 36173 : AtCleanup_Portals(); /* now safe to release portal memory */
3076 : 36173 : AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
3077 : :
3078 : 36173 : CurrentResourceOwner = NULL; /* and resource owner */
3079 [ + - ]: 36173 : if (TopTransactionResourceOwner)
3080 : 36173 : ResourceOwnerDelete(TopTransactionResourceOwner);
3081 : 36173 : s->curTransactionOwner = NULL;
3082 : 36173 : CurTransactionResourceOwner = NULL;
3083 : 36173 : TopTransactionResourceOwner = NULL;
3084 : :
3085 : 36173 : AtCleanup_Memory(); /* and transaction memory */
3086 : :
3087 : 36173 : s->fullTransactionId = InvalidFullTransactionId;
3088 : 36173 : s->subTransactionId = InvalidSubTransactionId;
3089 : 36173 : s->nestingLevel = 0;
3090 : 36173 : s->gucNestLevel = 0;
3091 : 36173 : s->childXids = NULL;
3092 : 36173 : s->nChildXids = 0;
3093 : 36173 : s->maxChildXids = 0;
3094 : 36173 : s->parallelModeLevel = 0;
3095 : 36173 : s->parallelChildXact = false;
3096 : :
3097 : 36173 : XactTopFullTransactionId = InvalidFullTransactionId;
3098 : 36173 : nParallelCurrentXids = 0;
3099 : :
3100 : : /*
3101 : : * done with abort processing, set current transaction state back to
3102 : : * default
3103 : : */
3104 : 36173 : s->state = TRANS_DEFAULT;
3105 : 36173 : }
3106 : :
3107 : : /*
3108 : : * StartTransactionCommand
3109 : : */
3110 : : void
3111 : 779608 : StartTransactionCommand(void)
3112 : : {
3113 : 779608 : TransactionState s = CurrentTransactionState;
3114 : :
3115 [ + + + - : 779608 : switch (s->blockState)
- ]
3116 : : {
3117 : : /*
3118 : : * if we aren't in a transaction block, we just do our usual start
3119 : : * transaction.
3120 : : */
3121 : 664088 : case TBLOCK_DEFAULT:
3122 : 664088 : StartTransaction();
3123 : 664088 : s->blockState = TBLOCK_STARTED;
3124 : 664088 : break;
3125 : :
3126 : : /*
3127 : : * We are somewhere in a transaction block or subtransaction and
3128 : : * about to start a new command. For now we do nothing, but
3129 : : * someday we may do command-local resource initialization. (Note
3130 : : * that any needed CommandCounterIncrement was done by the
3131 : : * previous CommitTransactionCommand.)
3132 : : */
3133 : 114325 : case TBLOCK_INPROGRESS:
3134 : : case TBLOCK_IMPLICIT_INPROGRESS:
3135 : : case TBLOCK_SUBINPROGRESS:
3136 : 114325 : break;
3137 : :
3138 : : /*
3139 : : * Here we are in a failed transaction block (one of the commands
3140 : : * caused an abort) so we do nothing but remain in the abort
3141 : : * state. Eventually we will get a ROLLBACK command which will
3142 : : * get us out of this state. (It is up to other code to ensure
3143 : : * that no commands other than ROLLBACK will be processed in these
3144 : : * states.)
3145 : : */
3146 : 1195 : case TBLOCK_ABORT:
3147 : : case TBLOCK_SUBABORT:
3148 : 1195 : break;
3149 : :
3150 : : /* These cases are invalid. */
3151 : 0 : case TBLOCK_STARTED:
3152 : : case TBLOCK_BEGIN:
3153 : : case TBLOCK_PARALLEL_INPROGRESS:
3154 : : case TBLOCK_SUBBEGIN:
3155 : : case TBLOCK_END:
3156 : : case TBLOCK_SUBRELEASE:
3157 : : case TBLOCK_SUBCOMMIT:
3158 : : case TBLOCK_ABORT_END:
3159 : : case TBLOCK_SUBABORT_END:
3160 : : case TBLOCK_ABORT_PENDING:
3161 : : case TBLOCK_SUBABORT_PENDING:
3162 : : case TBLOCK_SUBRESTART:
3163 : : case TBLOCK_SUBABORT_RESTART:
3164 : : case TBLOCK_PREPARE:
3165 [ # # ]: 0 : elog(ERROR, "StartTransactionCommand: unexpected state %s",
3166 : : BlockStateAsString(s->blockState));
3167 : : break;
3168 : : }
3169 : :
3170 : : /*
3171 : : * We must switch to CurTransactionContext before returning. This is
3172 : : * already done if we called StartTransaction, otherwise not.
3173 : : */
3174 : : Assert(CurTransactionContext != NULL);
3175 : 779608 : MemoryContextSwitchTo(CurTransactionContext);
3176 : 779608 : }
3177 : :
3178 : :
3179 : : /*
3180 : : * Simple system for saving and restoring transaction characteristics
3181 : : * (isolation level, read only, deferrable). We need this for transaction
3182 : : * chaining, so that we can set the characteristics of the new transaction to
3183 : : * be the same as the previous one. (We need something like this because the
3184 : : * GUC system resets the characteristics at transaction end, so for example
3185 : : * just skipping the reset in StartTransaction() won't work.)
3186 : : */
3187 : : void
3188 : 746052 : SaveTransactionCharacteristics(SavedTransactionCharacteristics *s)
3189 : : {
3190 : 746052 : s->save_XactIsoLevel = XactIsoLevel;
3191 : 746052 : s->save_XactReadOnly = XactReadOnly;
3192 : 746052 : s->save_XactDeferrable = XactDeferrable;
3193 : 746052 : }
3194 : :
3195 : : void
3196 : 44 : RestoreTransactionCharacteristics(const SavedTransactionCharacteristics *s)
3197 : : {
3198 : 44 : XactIsoLevel = s->save_XactIsoLevel;
3199 : 44 : XactReadOnly = s->save_XactReadOnly;
3200 : 44 : XactDeferrable = s->save_XactDeferrable;
3201 : 44 : }
3202 : :
3203 : : /*
3204 : : * CommitTransactionCommand -- a wrapper function handling the
3205 : : * loop over subtransactions to avoid a potentially dangerous recursion
3206 : : * in CommitTransactionCommandInternal().
3207 : : */
3208 : : void
3209 : 745761 : CommitTransactionCommand(void)
3210 : : {
3211 : : /*
3212 : : * Repeatedly call CommitTransactionCommandInternal() until all the work
3213 : : * is done.
3214 : : */
3215 [ + + ]: 746048 : while (!CommitTransactionCommandInternal())
3216 : : {
3217 : : }
3218 : 745392 : }
3219 : :
3220 : : /*
3221 : : * CommitTransactionCommandInternal - a function doing an iteration of work
3222 : : * regarding handling the commit transaction command. In the case of
3223 : : * subtransactions more than one iterations could be required. Returns
3224 : : * true when no more iterations required, false otherwise.
3225 : : */
3226 : : static bool
3227 : 746048 : CommitTransactionCommandInternal(void)
3228 : : {
3229 : 746048 : TransactionState s = CurrentTransactionState;
3230 : : SavedTransactionCharacteristics savetc;
3231 : :
3232 : : /* Must save in case we need to restore below */
3233 : 746048 : SaveTransactionCharacteristics(&savetc);
3234 : :
3235 [ - + + + : 746048 : switch (s->blockState)
+ + + + +
+ + + + +
+ + - ]
3236 : : {
3237 : : /*
3238 : : * These shouldn't happen. TBLOCK_DEFAULT means the previous
3239 : : * StartTransactionCommand didn't set the STARTED state
3240 : : * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
3241 : : * by EndParallelWorkerTransaction(), not this function.
3242 : : */
3243 : 0 : case TBLOCK_DEFAULT:
3244 : : case TBLOCK_PARALLEL_INPROGRESS:
3245 [ # # ]: 0 : elog(FATAL, "CommitTransactionCommand: unexpected state %s",
3246 : : BlockStateAsString(s->blockState));
3247 : : break;
3248 : :
3249 : : /*
3250 : : * If we aren't in a transaction block, just do our usual
3251 : : * transaction commit, and return to the idle state.
3252 : : */
3253 : 618588 : case TBLOCK_STARTED:
3254 : 618588 : CommitTransaction();
3255 : 618545 : s->blockState = TBLOCK_DEFAULT;
3256 : 618545 : break;
3257 : :
3258 : : /*
3259 : : * We are completing a "BEGIN TRANSACTION" command, so we change
3260 : : * to the "transaction block in progress" state and return. (We
3261 : : * assume the BEGIN did nothing to the database, so we need no
3262 : : * CommandCounterIncrement.)
3263 : : */
3264 : 12742 : case TBLOCK_BEGIN:
3265 : 12742 : s->blockState = TBLOCK_INPROGRESS;
3266 : 12742 : break;
3267 : :
3268 : : /*
3269 : : * This is the case when we have finished executing a command
3270 : : * someplace within a transaction block. We increment the command
3271 : : * counter and return.
3272 : : */
3273 : 78868 : case TBLOCK_INPROGRESS:
3274 : : case TBLOCK_IMPLICIT_INPROGRESS:
3275 : : case TBLOCK_SUBINPROGRESS:
3276 : 78868 : CommandCounterIncrement();
3277 : 78868 : break;
3278 : :
3279 : : /*
3280 : : * We are completing a "COMMIT" command. Do it and return to the
3281 : : * idle state.
3282 : : */
3283 : 8959 : case TBLOCK_END:
3284 : 8959 : CommitTransaction();
3285 : 8716 : s->blockState = TBLOCK_DEFAULT;
3286 [ + + ]: 8716 : if (s->chain)
3287 : : {
3288 : 8 : StartTransaction();
3289 : 8 : s->blockState = TBLOCK_INPROGRESS;
3290 : 8 : s->chain = false;
3291 : 8 : RestoreTransactionCharacteristics(&savetc);
3292 : : }
3293 : 8716 : break;
3294 : :
3295 : : /*
3296 : : * Here we are in the middle of a transaction block but one of the
3297 : : * commands caused an abort so we do nothing but remain in the
3298 : : * abort state. Eventually we will get a ROLLBACK command.
3299 : : */
3300 : 12 : case TBLOCK_ABORT:
3301 : : case TBLOCK_SUBABORT:
3302 : 12 : break;
3303 : :
3304 : : /*
3305 : : * Here we were in an aborted transaction block and we just got
3306 : : * the ROLLBACK command from the user, so clean up the
3307 : : * already-aborted transaction and return to the idle state.
3308 : : */
3309 : 930 : case TBLOCK_ABORT_END:
3310 : 930 : CleanupTransaction();
3311 : 930 : s->blockState = TBLOCK_DEFAULT;
3312 [ + + ]: 930 : if (s->chain)
3313 : : {
3314 : 8 : StartTransaction();
3315 : 8 : s->blockState = TBLOCK_INPROGRESS;
3316 : 8 : s->chain = false;
3317 : 8 : RestoreTransactionCharacteristics(&savetc);
3318 : : }
3319 : 930 : break;
3320 : :
3321 : : /*
3322 : : * Here we were in a perfectly good transaction block but the user
3323 : : * told us to ROLLBACK anyway. We have to abort the transaction
3324 : : * and then clean up.
3325 : : */
3326 : 1821 : case TBLOCK_ABORT_PENDING:
3327 : 1821 : AbortTransaction();
3328 : 1821 : CleanupTransaction();
3329 : 1821 : s->blockState = TBLOCK_DEFAULT;
3330 [ + + ]: 1821 : if (s->chain)
3331 : : {
3332 : 12 : StartTransaction();
3333 : 12 : s->blockState = TBLOCK_INPROGRESS;
3334 : 12 : s->chain = false;
3335 : 12 : RestoreTransactionCharacteristics(&savetc);
3336 : : }
3337 : 1821 : break;
3338 : :
3339 : : /*
3340 : : * We are completing a "PREPARE TRANSACTION" command. Do it and
3341 : : * return to the idle state.
3342 : : */
3343 : 274 : case TBLOCK_PREPARE:
3344 : 274 : PrepareTransaction();
3345 : 210 : s->blockState = TBLOCK_DEFAULT;
3346 : 210 : break;
3347 : :
3348 : : /*
3349 : : * The user issued a SAVEPOINT inside a transaction block. Start a
3350 : : * subtransaction. (DefineSavepoint already did PushTransaction,
3351 : : * so as to have someplace to put the SUBBEGIN state.)
3352 : : */
3353 : 22396 : case TBLOCK_SUBBEGIN:
3354 : 22396 : StartSubTransaction();
3355 : 22396 : s->blockState = TBLOCK_SUBINPROGRESS;
3356 : 22396 : break;
3357 : :
3358 : : /*
3359 : : * The user issued a RELEASE command, so we end the current
3360 : : * subtransaction and return to the parent transaction. The parent
3361 : : * might be ended too, so repeat till we find an INPROGRESS
3362 : : * transaction or subtransaction.
3363 : : */
3364 : 268 : case TBLOCK_SUBRELEASE:
3365 : : do
3366 : : {
3367 : 268 : CommitSubTransaction();
3368 : 268 : s = CurrentTransactionState; /* changed by pop */
3369 [ + + ]: 268 : } while (s->blockState == TBLOCK_SUBRELEASE);
3370 : :
3371 : : Assert(s->blockState == TBLOCK_INPROGRESS ||
3372 : : s->blockState == TBLOCK_SUBINPROGRESS);
3373 : 181 : break;
3374 : :
3375 : : /*
3376 : : * The user issued a COMMIT, so we end the current subtransaction
3377 : : * hierarchy and perform final commit. We do this by rolling up
3378 : : * any subtransactions into their parent, which leads to O(N^2)
3379 : : * operations with respect to resource owners - this isn't that
3380 : : * bad until we approach a thousands of savepoints but is
3381 : : * necessary for correctness should after triggers create new
3382 : : * resource owners.
3383 : : */
3384 : 600 : case TBLOCK_SUBCOMMIT:
3385 : : do
3386 : : {
3387 : 600 : CommitSubTransaction();
3388 : 600 : s = CurrentTransactionState; /* changed by pop */
3389 [ + + ]: 600 : } while (s->blockState == TBLOCK_SUBCOMMIT);
3390 : : /* If we had a COMMIT command, finish off the main xact too */
3391 [ + + ]: 511 : if (s->blockState == TBLOCK_END)
3392 : : {
3393 : : Assert(s->parent == NULL);
3394 : 401 : CommitTransaction();
3395 : 384 : s->blockState = TBLOCK_DEFAULT;
3396 [ + + ]: 384 : if (s->chain)
3397 : : {
3398 : 12 : StartTransaction();
3399 : 12 : s->blockState = TBLOCK_INPROGRESS;
3400 : 12 : s->chain = false;
3401 : 12 : RestoreTransactionCharacteristics(&savetc);
3402 : : }
3403 : : }
3404 [ + - ]: 110 : else if (s->blockState == TBLOCK_PREPARE)
3405 : : {
3406 : : Assert(s->parent == NULL);
3407 : 110 : PrepareTransaction();
3408 : 108 : s->blockState = TBLOCK_DEFAULT;
3409 : : }
3410 : : else
3411 [ # # ]: 0 : elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3412 : : BlockStateAsString(s->blockState));
3413 : 492 : break;
3414 : :
3415 : : /*
3416 : : * The current already-failed subtransaction is ending due to a
3417 : : * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3418 : : * examine the parent (which could be in any of several states).
3419 : : * As we need to examine the parent, return false to request the
3420 : : * caller to do the next iteration.
3421 : : */
3422 : 51 : case TBLOCK_SUBABORT_END:
3423 : 51 : CleanupSubTransaction();
3424 : 51 : return false;
3425 : :
3426 : : /*
3427 : : * As above, but it's not dead yet, so abort first.
3428 : : */
3429 : 236 : case TBLOCK_SUBABORT_PENDING:
3430 : 236 : AbortSubTransaction();
3431 : 236 : CleanupSubTransaction();
3432 : 236 : return false;
3433 : :
3434 : : /*
3435 : : * The current subtransaction is the target of a ROLLBACK TO
3436 : : * command. Abort and pop it, then start a new subtransaction
3437 : : * with the same name.
3438 : : */
3439 : 338 : case TBLOCK_SUBRESTART:
3440 : : {
3441 : : char *name;
3442 : : int savepointLevel;
3443 : :
3444 : : /* save name and keep Cleanup from freeing it */
3445 : 338 : name = s->name;
3446 : 338 : s->name = NULL;
3447 : 338 : savepointLevel = s->savepointLevel;
3448 : :
3449 : 338 : AbortSubTransaction();
3450 : 338 : CleanupSubTransaction();
3451 : :
3452 : 338 : DefineSavepoint(NULL);
3453 : 338 : s = CurrentTransactionState; /* changed by push */
3454 : 338 : s->name = name;
3455 : 338 : s->savepointLevel = savepointLevel;
3456 : :
3457 : : /* This is the same as TBLOCK_SUBBEGIN case */
3458 : : Assert(s->blockState == TBLOCK_SUBBEGIN);
3459 : 338 : StartSubTransaction();
3460 : 338 : s->blockState = TBLOCK_SUBINPROGRESS;
3461 : : }
3462 : 338 : break;
3463 : :
3464 : : /*
3465 : : * Same as above, but the subtransaction had already failed, so we
3466 : : * don't need AbortSubTransaction.
3467 : : */
3468 : 141 : case TBLOCK_SUBABORT_RESTART:
3469 : : {
3470 : : char *name;
3471 : : int savepointLevel;
3472 : :
3473 : : /* save name and keep Cleanup from freeing it */
3474 : 141 : name = s->name;
3475 : 141 : s->name = NULL;
3476 : 141 : savepointLevel = s->savepointLevel;
3477 : :
3478 : 141 : CleanupSubTransaction();
3479 : :
3480 : 141 : DefineSavepoint(NULL);
3481 : 141 : s = CurrentTransactionState; /* changed by push */
3482 : 141 : s->name = name;
3483 : 141 : s->savepointLevel = savepointLevel;
3484 : :
3485 : : /* This is the same as TBLOCK_SUBBEGIN case */
3486 : : Assert(s->blockState == TBLOCK_SUBBEGIN);
3487 : 141 : StartSubTransaction();
3488 : 141 : s->blockState = TBLOCK_SUBINPROGRESS;
3489 : : }
3490 : 141 : break;
3491 : : }
3492 : :
3493 : : /* Done, no more iterations required */
3494 : 745392 : return true;
3495 : : }
3496 : :
3497 : : /*
3498 : : * AbortCurrentTransaction -- a wrapper function handling the
3499 : : * loop over subtransactions to avoid potentially dangerous recursion in
3500 : : * AbortCurrentTransactionInternal().
3501 : : */
3502 : : void
3503 : 35021 : AbortCurrentTransaction(void)
3504 : : {
3505 : : /*
3506 : : * Repeatedly call AbortCurrentTransactionInternal() until all the work is
3507 : : * done.
3508 : : */
3509 [ - + ]: 35021 : while (!AbortCurrentTransactionInternal())
3510 : : {
3511 : : }
3512 : 35021 : }
3513 : :
3514 : : /*
3515 : : * AbortCurrentTransactionInternal - a function doing an iteration of work
3516 : : * regarding handling the current transaction abort. In the case of
3517 : : * subtransactions more than one iterations could be required. Returns
3518 : : * true when no more iterations required, false otherwise.
3519 : : */
3520 : : static bool
3521 : 35021 : AbortCurrentTransactionInternal(void)
3522 : : {
3523 : 35021 : TransactionState s = CurrentTransactionState;
3524 : :
3525 [ + + - + : 35021 : switch (s->blockState)
+ + - - +
+ - - - ]
3526 : : {
3527 : 51 : case TBLOCK_DEFAULT:
3528 [ - + ]: 51 : if (s->state == TRANS_DEFAULT)
3529 : : {
3530 : : /* we are idle, so nothing to do */
3531 : : }
3532 : : else
3533 : : {
3534 : : /*
3535 : : * We can get here after an error during transaction start
3536 : : * (state will be TRANS_START). Need to clean up the
3537 : : * incompletely started transaction. First, adjust the
3538 : : * low-level state to suppress warning message from
3539 : : * AbortTransaction.
3540 : : */
3541 [ # # ]: 0 : if (s->state == TRANS_START)
3542 : 0 : s->state = TRANS_INPROGRESS;
3543 : 0 : AbortTransaction();
3544 : 0 : CleanupTransaction();
3545 : : }
3546 : 51 : break;
3547 : :
3548 : : /*
3549 : : * If we aren't in a transaction block, we just do the basic abort
3550 : : * & cleanup transaction. For this purpose, we treat an implicit
3551 : : * transaction block as if it were a simple statement.
3552 : : */
3553 : 32400 : case TBLOCK_STARTED:
3554 : : case TBLOCK_IMPLICIT_INPROGRESS:
3555 : 32400 : AbortTransaction();
3556 : 32400 : CleanupTransaction();
3557 : 32400 : s->blockState = TBLOCK_DEFAULT;
3558 : 32400 : break;
3559 : :
3560 : : /*
3561 : : * If we are in TBLOCK_BEGIN it means something screwed up right
3562 : : * after reading "BEGIN TRANSACTION". We assume that the user
3563 : : * will interpret the error as meaning the BEGIN failed to get him
3564 : : * into a transaction block, so we should abort and return to idle
3565 : : * state.
3566 : : */
3567 : 0 : case TBLOCK_BEGIN:
3568 : 0 : AbortTransaction();
3569 : 0 : CleanupTransaction();
3570 : 0 : s->blockState = TBLOCK_DEFAULT;
3571 : 0 : break;
3572 : :
3573 : : /*
3574 : : * We are somewhere in a transaction block and we've gotten a
3575 : : * failure, so we abort the transaction and set up the persistent
3576 : : * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3577 : : */
3578 : 944 : case TBLOCK_INPROGRESS:
3579 : : case TBLOCK_PARALLEL_INPROGRESS:
3580 : 944 : AbortTransaction();
3581 : 944 : s->blockState = TBLOCK_ABORT;
3582 : : /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3583 : 944 : break;
3584 : :
3585 : : /*
3586 : : * Here, we failed while trying to COMMIT. Clean up the
3587 : : * transaction and return to idle state (we do not want to stay in
3588 : : * the transaction).
3589 : : */
3590 : 260 : case TBLOCK_END:
3591 : 260 : AbortTransaction();
3592 : 260 : CleanupTransaction();
3593 : 260 : s->blockState = TBLOCK_DEFAULT;
3594 : 260 : break;
3595 : :
3596 : : /*
3597 : : * Here, we are already in an aborted transaction state and are
3598 : : * waiting for a ROLLBACK, but for some reason we failed again! So
3599 : : * we just remain in the abort state.
3600 : : */
3601 : 62 : case TBLOCK_ABORT:
3602 : : case TBLOCK_SUBABORT:
3603 : 62 : break;
3604 : :
3605 : : /*
3606 : : * We are in a failed transaction and we got the ROLLBACK command.
3607 : : * We have already aborted, we just need to cleanup and go to idle
3608 : : * state.
3609 : : */
3610 : 0 : case TBLOCK_ABORT_END:
3611 : 0 : CleanupTransaction();
3612 : 0 : s->blockState = TBLOCK_DEFAULT;
3613 : 0 : break;
3614 : :
3615 : : /*
3616 : : * We are in a live transaction and we got a ROLLBACK command.
3617 : : * Abort, cleanup, go to idle state.
3618 : : */
3619 : 0 : case TBLOCK_ABORT_PENDING:
3620 : 0 : AbortTransaction();
3621 : 0 : CleanupTransaction();
3622 : 0 : s->blockState = TBLOCK_DEFAULT;
3623 : 0 : break;
3624 : :
3625 : : /*
3626 : : * Here, we failed while trying to PREPARE. Clean up the
3627 : : * transaction and return to idle state (we do not want to stay in
3628 : : * the transaction).
3629 : : */
3630 : 64 : case TBLOCK_PREPARE:
3631 : 64 : AbortTransaction();
3632 : 64 : CleanupTransaction();
3633 : 64 : s->blockState = TBLOCK_DEFAULT;
3634 : 64 : break;
3635 : :
3636 : : /*
3637 : : * We got an error inside a subtransaction. Abort just the
3638 : : * subtransaction, and go to the persistent SUBABORT state until
3639 : : * we get ROLLBACK.
3640 : : */
3641 : 1240 : case TBLOCK_SUBINPROGRESS:
3642 : 1240 : AbortSubTransaction();
3643 : 1240 : s->blockState = TBLOCK_SUBABORT;
3644 : 1240 : break;
3645 : :
3646 : : /*
3647 : : * If we failed while trying to create a subtransaction, clean up
3648 : : * the broken subtransaction and abort the parent. The same
3649 : : * applies if we get a failure while ending a subtransaction. As
3650 : : * we need to abort the parent, return false to request the caller
3651 : : * to do the next iteration.
3652 : : */
3653 : 0 : case TBLOCK_SUBBEGIN:
3654 : : case TBLOCK_SUBRELEASE:
3655 : : case TBLOCK_SUBCOMMIT:
3656 : : case TBLOCK_SUBABORT_PENDING:
3657 : : case TBLOCK_SUBRESTART:
3658 : 0 : AbortSubTransaction();
3659 : 0 : CleanupSubTransaction();
3660 : 0 : return false;
3661 : :
3662 : : /*
3663 : : * Same as above, except the Abort() was already done.
3664 : : */
3665 : 0 : case TBLOCK_SUBABORT_END:
3666 : : case TBLOCK_SUBABORT_RESTART:
3667 : 0 : CleanupSubTransaction();
3668 : 0 : return false;
3669 : : }
3670 : :
3671 : : /* Done, no more iterations required */
3672 : 35021 : return true;
3673 : : }
3674 : :
3675 : : /*
3676 : : * PreventInTransactionBlock
3677 : : *
3678 : : * This routine is to be called by statements that must not run inside
3679 : : * a transaction block, typically because they have non-rollback-able
3680 : : * side effects or do internal commits.
3681 : : *
3682 : : * If this routine completes successfully, then the calling statement is
3683 : : * guaranteed that if it completes without error, its results will be
3684 : : * committed immediately.
3685 : : *
3686 : : * If we have already started a transaction block, issue an error; also issue
3687 : : * an error if we appear to be running inside a user-defined function (which
3688 : : * could issue more commands and possibly cause a failure after the statement
3689 : : * completes). Subtransactions are verboten too.
3690 : : *
3691 : : * We must also set XACT_FLAGS_NEEDIMMEDIATECOMMIT in MyXactFlags, to ensure
3692 : : * that postgres.c follows through by committing after the statement is done.
3693 : : *
3694 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3695 : : * inside a function. (We will always fail if this is false, but it's
3696 : : * convenient to centralize the check here instead of making callers do it.)
3697 : : * stmtType: statement type name, for error messages.
3698 : : */
3699 : : void
3700 : 122512 : PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3701 : : {
3702 : : /*
3703 : : * xact block already started?
3704 : : */
3705 [ + + ]: 122512 : if (IsTransactionBlock())
3706 [ + - ]: 78 : ereport(ERROR,
3707 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3708 : : /* translator: %s represents an SQL statement name */
3709 : : errmsg("%s cannot run inside a transaction block",
3710 : : stmtType)));
3711 : :
3712 : : /*
3713 : : * subtransaction?
3714 : : */
3715 [ - + ]: 122434 : if (IsSubTransaction())
3716 [ # # ]: 0 : ereport(ERROR,
3717 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3718 : : /* translator: %s represents an SQL statement name */
3719 : : errmsg("%s cannot run inside a subtransaction",
3720 : : stmtType)));
3721 : :
3722 : : /*
3723 : : * inside a function call?
3724 : : */
3725 [ + + ]: 122434 : if (!isTopLevel)
3726 [ + - ]: 4 : ereport(ERROR,
3727 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3728 : : /* translator: %s represents an SQL statement name */
3729 : : errmsg("%s cannot be executed from a function or procedure",
3730 : : stmtType)));
3731 : :
3732 : : /* If we got past IsTransactionBlock test, should be in default state */
3733 [ + + ]: 122430 : if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3734 [ - + ]: 121384 : CurrentTransactionState->blockState != TBLOCK_STARTED)
3735 [ # # ]: 0 : elog(FATAL, "cannot prevent transaction chain");
3736 : :
3737 : : /* All okay. Set the flag to make sure the right thing happens later. */
3738 : 122430 : MyXactFlags |= XACT_FLAGS_NEEDIMMEDIATECOMMIT;
3739 : 122430 : }
3740 : :
3741 : : /*
3742 : : * WarnNoTransactionBlock
3743 : : * RequireTransactionBlock
3744 : : *
3745 : : * These two functions allow for warnings or errors if a command is executed
3746 : : * outside of a transaction block. This is useful for commands that have no
3747 : : * effects that persist past transaction end (and so calling them outside a
3748 : : * transaction block is presumably an error). DECLARE CURSOR is an example.
3749 : : * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3750 : : * that have no effect issue warnings, all other no-effect commands generate
3751 : : * errors.
3752 : : *
3753 : : * If we appear to be running inside a user-defined function, we do not
3754 : : * issue anything, since the function could issue more commands that make
3755 : : * use of the current statement's results. Likewise subtransactions.
3756 : : * Thus these are inverses for PreventInTransactionBlock.
3757 : : *
3758 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3759 : : * inside a function.
3760 : : * stmtType: statement type name, for warning or error messages.
3761 : : */
3762 : : void
3763 : 1428 : WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3764 : : {
3765 : 1428 : CheckTransactionBlock(isTopLevel, false, stmtType);
3766 : 1428 : }
3767 : :
3768 : : void
3769 : 5118 : RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3770 : : {
3771 : 5118 : CheckTransactionBlock(isTopLevel, true, stmtType);
3772 : 5095 : }
3773 : :
3774 : : /*
3775 : : * This is the implementation of the above two.
3776 : : */
3777 : : static void
3778 : 6546 : CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3779 : : {
3780 : : /*
3781 : : * xact block already started?
3782 : : */
3783 [ + + ]: 6546 : if (IsTransactionBlock())
3784 : 6427 : return;
3785 : :
3786 : : /*
3787 : : * subtransaction?
3788 : : */
3789 [ - + ]: 119 : if (IsSubTransaction())
3790 : 0 : return;
3791 : :
3792 : : /*
3793 : : * inside a function call?
3794 : : */
3795 [ + + ]: 119 : if (!isTopLevel)
3796 : 82 : return;
3797 : :
3798 [ + + + - ]: 37 : ereport(throwError ? ERROR : WARNING,
3799 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3800 : : /* translator: %s represents an SQL statement name */
3801 : : errmsg("%s can only be used in transaction blocks",
3802 : : stmtType)));
3803 : : }
3804 : :
3805 : : /*
3806 : : * IsInTransactionBlock
3807 : : *
3808 : : * This routine is for statements that need to behave differently inside
3809 : : * a transaction block than when running as single commands. ANALYZE is
3810 : : * currently the only example.
3811 : : *
3812 : : * If this routine returns "false", then the calling statement is allowed
3813 : : * to perform internal transaction-commit-and-start cycles; there is not a
3814 : : * risk of messing up any transaction already in progress. (Note that this
3815 : : * is not the identical guarantee provided by PreventInTransactionBlock,
3816 : : * since we will not force a post-statement commit.)
3817 : : *
3818 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3819 : : * inside a function.
3820 : : */
3821 : : bool
3822 : 3412 : IsInTransactionBlock(bool isTopLevel)
3823 : : {
3824 : : /*
3825 : : * Return true on same conditions that would make
3826 : : * PreventInTransactionBlock error out
3827 : : */
3828 [ + + ]: 3412 : if (IsTransactionBlock())
3829 : 102 : return true;
3830 : :
3831 [ - + ]: 3310 : if (IsSubTransaction())
3832 : 0 : return true;
3833 : :
3834 [ + + ]: 3310 : if (!isTopLevel)
3835 : 74 : return true;
3836 : :
3837 [ + - ]: 3236 : if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3838 [ - + ]: 3236 : CurrentTransactionState->blockState != TBLOCK_STARTED)
3839 : 0 : return true;
3840 : :
3841 : 3236 : return false;
3842 : : }
3843 : :
3844 : :
3845 : : /*
3846 : : * Register or deregister callback functions for start- and end-of-xact
3847 : : * operations.
3848 : : *
3849 : : * These functions are intended for use by dynamically loaded modules.
3850 : : * For built-in modules we generally just hardwire the appropriate calls
3851 : : * (mainly because it's easier to control the order that way, where needed).
3852 : : *
3853 : : * At transaction end, the callback occurs post-commit or post-abort, so the
3854 : : * callback functions can only do noncritical cleanup.
3855 : : */
3856 : : void
3857 : 2348 : RegisterXactCallback(XactCallback callback, void *arg)
3858 : : {
3859 : : XactCallbackItem *item;
3860 : :
3861 : : item = (XactCallbackItem *)
3862 : 2348 : MemoryContextAlloc(TopMemoryContext, sizeof(XactCallbackItem));
3863 : 2348 : item->callback = callback;
3864 : 2348 : item->arg = arg;
3865 : 2348 : item->next = Xact_callbacks;
3866 : 2348 : Xact_callbacks = item;
3867 : 2348 : }
3868 : :
3869 : : void
3870 : 0 : UnregisterXactCallback(XactCallback callback, void *arg)
3871 : : {
3872 : : XactCallbackItem *item;
3873 : : XactCallbackItem *prev;
3874 : :
3875 : 0 : prev = NULL;
3876 [ # # ]: 0 : for (item = Xact_callbacks; item; prev = item, item = item->next)
3877 : : {
3878 [ # # # # ]: 0 : if (item->callback == callback && item->arg == arg)
3879 : : {
3880 [ # # ]: 0 : if (prev)
3881 : 0 : prev->next = item->next;
3882 : : else
3883 : 0 : Xact_callbacks = item->next;
3884 : 0 : pfree(item);
3885 : 0 : break;
3886 : : }
3887 : : }
3888 : 0 : }
3889 : :
3890 : : static void
3891 : 1296348 : CallXactCallbacks(XactEvent event)
3892 : : {
3893 : : XactCallbackItem *item;
3894 : : XactCallbackItem *next;
3895 : :
3896 [ + + ]: 1506705 : for (item = Xact_callbacks; item; item = next)
3897 : : {
3898 : : /* allow callbacks to unregister themselves when called */
3899 : 210358 : next = item->next;
3900 : 210358 : item->callback(event, item->arg);
3901 : : }
3902 : 1296347 : }
3903 : :
3904 : :
3905 : : /*
3906 : : * Register or deregister callback functions for start- and end-of-subxact
3907 : : * operations.
3908 : : *
3909 : : * Pretty much same as above, but for subtransaction events.
3910 : : *
3911 : : * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3912 : : * so the callback functions can only do noncritical cleanup. At
3913 : : * subtransaction start, the callback is called when the subtransaction has
3914 : : * finished initializing.
3915 : : */
3916 : : void
3917 : 2348 : RegisterSubXactCallback(SubXactCallback callback, void *arg)
3918 : : {
3919 : : SubXactCallbackItem *item;
3920 : :
3921 : : item = (SubXactCallbackItem *)
3922 : 2348 : MemoryContextAlloc(TopMemoryContext, sizeof(SubXactCallbackItem));
3923 : 2348 : item->callback = callback;
3924 : 2348 : item->arg = arg;
3925 : 2348 : item->next = SubXact_callbacks;
3926 : 2348 : SubXact_callbacks = item;
3927 : 2348 : }
3928 : :
3929 : : void
3930 : 0 : UnregisterSubXactCallback(SubXactCallback callback, void *arg)
3931 : : {
3932 : : SubXactCallbackItem *item;
3933 : : SubXactCallbackItem *prev;
3934 : :
3935 : 0 : prev = NULL;
3936 [ # # ]: 0 : for (item = SubXact_callbacks; item; prev = item, item = item->next)
3937 : : {
3938 [ # # # # ]: 0 : if (item->callback == callback && item->arg == arg)
3939 : : {
3940 [ # # ]: 0 : if (prev)
3941 : 0 : prev->next = item->next;
3942 : : else
3943 : 0 : SubXact_callbacks = item->next;
3944 : 0 : pfree(item);
3945 : 0 : break;
3946 : : }
3947 : : }
3948 : 0 : }
3949 : :
3950 : : static void
3951 : 63134 : CallSubXactCallbacks(SubXactEvent event,
3952 : : SubTransactionId mySubid,
3953 : : SubTransactionId parentSubid)
3954 : : {
3955 : : SubXactCallbackItem *item;
3956 : : SubXactCallbackItem *next;
3957 : :
3958 [ + + ]: 120197 : for (item = SubXact_callbacks; item; item = next)
3959 : : {
3960 : : /* allow callbacks to unregister themselves when called */
3961 : 57063 : next = item->next;
3962 : 57063 : item->callback(event, mySubid, parentSubid, item->arg);
3963 : : }
3964 : 63134 : }
3965 : :
3966 : :
3967 : : /* ----------------------------------------------------------------
3968 : : * transaction block support
3969 : : * ----------------------------------------------------------------
3970 : : */
3971 : :
3972 : : /*
3973 : : * BeginTransactionBlock
3974 : : * This executes a BEGIN command.
3975 : : */
3976 : : void
3977 : 12742 : BeginTransactionBlock(void)
3978 : : {
3979 : 12742 : TransactionState s = CurrentTransactionState;
3980 : :
3981 [ + + - - : 12742 : switch (s->blockState)
- ]
3982 : : {
3983 : : /*
3984 : : * We are not inside a transaction block, so allow one to begin.
3985 : : */
3986 : 12238 : case TBLOCK_STARTED:
3987 : 12238 : s->blockState = TBLOCK_BEGIN;
3988 : 12238 : break;
3989 : :
3990 : : /*
3991 : : * BEGIN converts an implicit transaction block to a regular one.
3992 : : * (Note that we allow this even if we've already done some
3993 : : * commands, which is a bit odd but matches historical practice.)
3994 : : */
3995 : 504 : case TBLOCK_IMPLICIT_INPROGRESS:
3996 : 504 : s->blockState = TBLOCK_BEGIN;
3997 : 504 : break;
3998 : :
3999 : : /*
4000 : : * Already a transaction block in progress.
4001 : : */
4002 : 0 : case TBLOCK_INPROGRESS:
4003 : : case TBLOCK_PARALLEL_INPROGRESS:
4004 : : case TBLOCK_SUBINPROGRESS:
4005 : : case TBLOCK_ABORT:
4006 : : case TBLOCK_SUBABORT:
4007 [ # # ]: 0 : ereport(WARNING,
4008 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
4009 : : errmsg("there is already a transaction in progress")));
4010 : 0 : break;
4011 : :
4012 : : /* These cases are invalid. */
4013 : 0 : case TBLOCK_DEFAULT:
4014 : : case TBLOCK_BEGIN:
4015 : : case TBLOCK_SUBBEGIN:
4016 : : case TBLOCK_END:
4017 : : case TBLOCK_SUBRELEASE:
4018 : : case TBLOCK_SUBCOMMIT:
4019 : : case TBLOCK_ABORT_END:
4020 : : case TBLOCK_SUBABORT_END:
4021 : : case TBLOCK_ABORT_PENDING:
4022 : : case TBLOCK_SUBABORT_PENDING:
4023 : : case TBLOCK_SUBRESTART:
4024 : : case TBLOCK_SUBABORT_RESTART:
4025 : : case TBLOCK_PREPARE:
4026 [ # # ]: 0 : elog(FATAL, "BeginTransactionBlock: unexpected state %s",
4027 : : BlockStateAsString(s->blockState));
4028 : : break;
4029 : : }
4030 : 12742 : }
4031 : :
4032 : : /*
4033 : : * PrepareTransactionBlock
4034 : : * This executes a PREPARE command.
4035 : : *
4036 : : * Since PREPARE may actually do a ROLLBACK, the result indicates what
4037 : : * happened: true for PREPARE, false for ROLLBACK.
4038 : : *
4039 : : * Note that we don't actually do anything here except change blockState.
4040 : : * The real work will be done in the upcoming PrepareTransaction().
4041 : : * We do it this way because it's not convenient to change memory context,
4042 : : * resource owner, etc while executing inside a Portal.
4043 : : */
4044 : : bool
4045 : 386 : PrepareTransactionBlock(const char *gid)
4046 : : {
4047 : : TransactionState s;
4048 : : bool result;
4049 : :
4050 : : /* Set up to commit the current transaction */
4051 : 386 : result = EndTransactionBlock(false);
4052 : :
4053 : : /* If successful, change outer tblock state to PREPARE */
4054 [ + + ]: 386 : if (result)
4055 : : {
4056 : 384 : s = CurrentTransactionState;
4057 : :
4058 [ + + ]: 504 : while (s->parent != NULL)
4059 : 120 : s = s->parent;
4060 : :
4061 [ + - ]: 384 : if (s->blockState == TBLOCK_END)
4062 : : {
4063 : : /* Save GID where PrepareTransaction can find it again */
4064 : 384 : prepareGID = MemoryContextStrdup(TopTransactionContext, gid);
4065 : :
4066 : 384 : s->blockState = TBLOCK_PREPARE;
4067 : : }
4068 : : else
4069 : : {
4070 : : /*
4071 : : * ignore case where we are not in a transaction;
4072 : : * EndTransactionBlock already issued a warning.
4073 : : */
4074 : : Assert(s->blockState == TBLOCK_STARTED ||
4075 : : s->blockState == TBLOCK_IMPLICIT_INPROGRESS);
4076 : : /* Don't send back a PREPARE result tag... */
4077 : 0 : result = false;
4078 : : }
4079 : : }
4080 : :
4081 : 386 : return result;
4082 : : }
4083 : :
4084 : : /*
4085 : : * EndTransactionBlock
4086 : : * This executes a COMMIT command.
4087 : : *
4088 : : * Since COMMIT may actually do a ROLLBACK, the result indicates what
4089 : : * happened: true for COMMIT, false for ROLLBACK.
4090 : : *
4091 : : * Note that we don't actually do anything here except change blockState.
4092 : : * The real work will be done in the upcoming CommitTransactionCommand().
4093 : : * We do it this way because it's not convenient to change memory context,
4094 : : * resource owner, etc while executing inside a Portal.
4095 : : */
4096 : : bool
4097 : 10287 : EndTransactionBlock(bool chain)
4098 : : {
4099 : 10287 : TransactionState s = CurrentTransactionState;
4100 : 10287 : bool result = false;
4101 : :
4102 [ + + + + : 10287 : switch (s->blockState)
+ + - -
- ]
4103 : : {
4104 : : /*
4105 : : * We are in a transaction block, so tell CommitTransactionCommand
4106 : : * to COMMIT.
4107 : : */
4108 : 9217 : case TBLOCK_INPROGRESS:
4109 : 9217 : s->blockState = TBLOCK_END;
4110 : 9217 : result = true;
4111 : 9217 : break;
4112 : :
4113 : : /*
4114 : : * We are in an implicit transaction block. If AND CHAIN was
4115 : : * specified, error. Otherwise commit, but issue a warning
4116 : : * because there was no explicit BEGIN before this.
4117 : : */
4118 : 32 : case TBLOCK_IMPLICIT_INPROGRESS:
4119 [ + + ]: 32 : if (chain)
4120 [ + - ]: 16 : ereport(ERROR,
4121 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4122 : : /* translator: %s represents an SQL statement name */
4123 : : errmsg("%s can only be used in transaction blocks",
4124 : : "COMMIT AND CHAIN")));
4125 : : else
4126 [ + - ]: 16 : ereport(WARNING,
4127 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4128 : : errmsg("there is no transaction in progress")));
4129 : 16 : s->blockState = TBLOCK_END;
4130 : 16 : result = true;
4131 : 16 : break;
4132 : :
4133 : : /*
4134 : : * We are in a failed transaction block. Tell
4135 : : * CommitTransactionCommand it's time to exit the block.
4136 : : */
4137 : 473 : case TBLOCK_ABORT:
4138 : 473 : s->blockState = TBLOCK_ABORT_END;
4139 : 473 : break;
4140 : :
4141 : : /*
4142 : : * We are in a live subtransaction block. Set up to subcommit all
4143 : : * open subtransactions and then commit the main transaction.
4144 : : */
4145 : 511 : case TBLOCK_SUBINPROGRESS:
4146 [ + + ]: 1111 : while (s->parent != NULL)
4147 : : {
4148 [ + - ]: 600 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4149 : 600 : s->blockState = TBLOCK_SUBCOMMIT;
4150 : : else
4151 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4152 : : BlockStateAsString(s->blockState));
4153 : 600 : s = s->parent;
4154 : : }
4155 [ + - ]: 511 : if (s->blockState == TBLOCK_INPROGRESS)
4156 : 511 : s->blockState = TBLOCK_END;
4157 : : else
4158 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4159 : : BlockStateAsString(s->blockState));
4160 : 511 : result = true;
4161 : 511 : break;
4162 : :
4163 : : /*
4164 : : * Here we are inside an aborted subtransaction. Treat the COMMIT
4165 : : * as ROLLBACK: set up to abort everything and exit the main
4166 : : * transaction.
4167 : : */
4168 : 38 : case TBLOCK_SUBABORT:
4169 [ + + ]: 76 : while (s->parent != NULL)
4170 : : {
4171 [ - + ]: 38 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4172 : 0 : s->blockState = TBLOCK_SUBABORT_PENDING;
4173 [ + - ]: 38 : else if (s->blockState == TBLOCK_SUBABORT)
4174 : 38 : s->blockState = TBLOCK_SUBABORT_END;
4175 : : else
4176 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4177 : : BlockStateAsString(s->blockState));
4178 : 38 : s = s->parent;
4179 : : }
4180 [ + - ]: 38 : if (s->blockState == TBLOCK_INPROGRESS)
4181 : 38 : s->blockState = TBLOCK_ABORT_PENDING;
4182 [ # # ]: 0 : else if (s->blockState == TBLOCK_ABORT)
4183 : 0 : s->blockState = TBLOCK_ABORT_END;
4184 : : else
4185 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4186 : : BlockStateAsString(s->blockState));
4187 : 38 : break;
4188 : :
4189 : : /*
4190 : : * The user issued COMMIT when not inside a transaction. For
4191 : : * COMMIT without CHAIN, issue a WARNING, staying in
4192 : : * TBLOCK_STARTED state. The upcoming call to
4193 : : * CommitTransactionCommand() will then close the transaction and
4194 : : * put us back into the default state. For COMMIT AND CHAIN,
4195 : : * error.
4196 : : */
4197 : 16 : case TBLOCK_STARTED:
4198 [ + + ]: 16 : if (chain)
4199 [ + - ]: 4 : ereport(ERROR,
4200 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4201 : : /* translator: %s represents an SQL statement name */
4202 : : errmsg("%s can only be used in transaction blocks",
4203 : : "COMMIT AND CHAIN")));
4204 : : else
4205 [ + - ]: 12 : ereport(WARNING,
4206 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4207 : : errmsg("there is no transaction in progress")));
4208 : 12 : result = true;
4209 : 12 : break;
4210 : :
4211 : : /*
4212 : : * The user issued a COMMIT that somehow ran inside a parallel
4213 : : * worker. We can't cope with that.
4214 : : */
4215 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
4216 [ # # ]: 0 : ereport(FATAL,
4217 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4218 : : errmsg("cannot commit during a parallel operation")));
4219 : : break;
4220 : :
4221 : : /* These cases are invalid. */
4222 : 0 : case TBLOCK_DEFAULT:
4223 : : case TBLOCK_BEGIN:
4224 : : case TBLOCK_SUBBEGIN:
4225 : : case TBLOCK_END:
4226 : : case TBLOCK_SUBRELEASE:
4227 : : case TBLOCK_SUBCOMMIT:
4228 : : case TBLOCK_ABORT_END:
4229 : : case TBLOCK_SUBABORT_END:
4230 : : case TBLOCK_ABORT_PENDING:
4231 : : case TBLOCK_SUBABORT_PENDING:
4232 : : case TBLOCK_SUBRESTART:
4233 : : case TBLOCK_SUBABORT_RESTART:
4234 : : case TBLOCK_PREPARE:
4235 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4236 : : BlockStateAsString(s->blockState));
4237 : : break;
4238 : : }
4239 : :
4240 : : Assert(s->blockState == TBLOCK_STARTED ||
4241 : : s->blockState == TBLOCK_END ||
4242 : : s->blockState == TBLOCK_ABORT_END ||
4243 : : s->blockState == TBLOCK_ABORT_PENDING);
4244 : :
4245 : 10267 : s->chain = chain;
4246 : :
4247 : 10267 : return result;
4248 : : }
4249 : :
4250 : : /*
4251 : : * UserAbortTransactionBlock
4252 : : * This executes a ROLLBACK command.
4253 : : *
4254 : : * As above, we don't actually do anything here except change blockState.
4255 : : */
4256 : : void
4257 : 2260 : UserAbortTransactionBlock(bool chain)
4258 : : {
4259 : 2260 : TransactionState s = CurrentTransactionState;
4260 : :
4261 [ + + + + : 2260 : switch (s->blockState)
- - - ]
4262 : : {
4263 : : /*
4264 : : * We are inside a transaction block and we got a ROLLBACK command
4265 : : * from the user, so tell CommitTransactionCommand to abort and
4266 : : * exit the transaction block.
4267 : : */
4268 : 1681 : case TBLOCK_INPROGRESS:
4269 : 1681 : s->blockState = TBLOCK_ABORT_PENDING;
4270 : 1681 : break;
4271 : :
4272 : : /*
4273 : : * We are inside a failed transaction block and we got a ROLLBACK
4274 : : * command from the user. Abort processing is already done, so
4275 : : * CommitTransactionCommand just has to cleanup and go back to
4276 : : * idle state.
4277 : : */
4278 : 457 : case TBLOCK_ABORT:
4279 : 457 : s->blockState = TBLOCK_ABORT_END;
4280 : 457 : break;
4281 : :
4282 : : /*
4283 : : * We are inside a subtransaction. Mark everything up to top
4284 : : * level as exitable.
4285 : : */
4286 : 71 : case TBLOCK_SUBINPROGRESS:
4287 : : case TBLOCK_SUBABORT:
4288 [ + + ]: 282 : while (s->parent != NULL)
4289 : : {
4290 [ + + ]: 211 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4291 : 198 : s->blockState = TBLOCK_SUBABORT_PENDING;
4292 [ + - ]: 13 : else if (s->blockState == TBLOCK_SUBABORT)
4293 : 13 : s->blockState = TBLOCK_SUBABORT_END;
4294 : : else
4295 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4296 : : BlockStateAsString(s->blockState));
4297 : 211 : s = s->parent;
4298 : : }
4299 [ + - ]: 71 : if (s->blockState == TBLOCK_INPROGRESS)
4300 : 71 : s->blockState = TBLOCK_ABORT_PENDING;
4301 [ # # ]: 0 : else if (s->blockState == TBLOCK_ABORT)
4302 : 0 : s->blockState = TBLOCK_ABORT_END;
4303 : : else
4304 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4305 : : BlockStateAsString(s->blockState));
4306 : 71 : break;
4307 : :
4308 : : /*
4309 : : * The user issued ABORT when not inside a transaction. For
4310 : : * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
4311 : : * The upcoming call to CommitTransactionCommand() will then put
4312 : : * us back into the default state. For ROLLBACK AND CHAIN, error.
4313 : : *
4314 : : * We do the same thing with ABORT inside an implicit transaction,
4315 : : * although in this case we might be rolling back actual database
4316 : : * state changes. (It's debatable whether we should issue a
4317 : : * WARNING in this case, but we have done so historically.)
4318 : : */
4319 : 51 : case TBLOCK_STARTED:
4320 : : case TBLOCK_IMPLICIT_INPROGRESS:
4321 [ + + ]: 51 : if (chain)
4322 [ + - ]: 20 : ereport(ERROR,
4323 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4324 : : /* translator: %s represents an SQL statement name */
4325 : : errmsg("%s can only be used in transaction blocks",
4326 : : "ROLLBACK AND CHAIN")));
4327 : : else
4328 [ + - ]: 31 : ereport(WARNING,
4329 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4330 : : errmsg("there is no transaction in progress")));
4331 : 31 : s->blockState = TBLOCK_ABORT_PENDING;
4332 : 31 : break;
4333 : :
4334 : : /*
4335 : : * The user issued an ABORT that somehow ran inside a parallel
4336 : : * worker. We can't cope with that.
4337 : : */
4338 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
4339 [ # # ]: 0 : ereport(FATAL,
4340 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4341 : : errmsg("cannot abort during a parallel operation")));
4342 : : break;
4343 : :
4344 : : /* These cases are invalid. */
4345 : 0 : case TBLOCK_DEFAULT:
4346 : : case TBLOCK_BEGIN:
4347 : : case TBLOCK_SUBBEGIN:
4348 : : case TBLOCK_END:
4349 : : case TBLOCK_SUBRELEASE:
4350 : : case TBLOCK_SUBCOMMIT:
4351 : : case TBLOCK_ABORT_END:
4352 : : case TBLOCK_SUBABORT_END:
4353 : : case TBLOCK_ABORT_PENDING:
4354 : : case TBLOCK_SUBABORT_PENDING:
4355 : : case TBLOCK_SUBRESTART:
4356 : : case TBLOCK_SUBABORT_RESTART:
4357 : : case TBLOCK_PREPARE:
4358 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4359 : : BlockStateAsString(s->blockState));
4360 : : break;
4361 : : }
4362 : :
4363 : : Assert(s->blockState == TBLOCK_ABORT_END ||
4364 : : s->blockState == TBLOCK_ABORT_PENDING);
4365 : :
4366 : 2240 : s->chain = chain;
4367 : 2240 : }
4368 : :
4369 : : /*
4370 : : * BeginImplicitTransactionBlock
4371 : : * Start an implicit transaction block if we're not already in one.
4372 : : *
4373 : : * Unlike BeginTransactionBlock, this is called directly from the main loop
4374 : : * in postgres.c, not within a Portal. So we can just change blockState
4375 : : * without a lot of ceremony. We do not expect caller to do
4376 : : * CommitTransactionCommand/StartTransactionCommand.
4377 : : */
4378 : : void
4379 : 48940 : BeginImplicitTransactionBlock(void)
4380 : : {
4381 : 48940 : TransactionState s = CurrentTransactionState;
4382 : :
4383 : : /*
4384 : : * If we are in STARTED state (that is, no transaction block is open),
4385 : : * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4386 : : * block.
4387 : : *
4388 : : * For caller convenience, we consider all other transaction states as
4389 : : * legal here; otherwise the caller would need its own state check, which
4390 : : * seems rather pointless.
4391 : : */
4392 [ + + ]: 48940 : if (s->blockState == TBLOCK_STARTED)
4393 : 6110 : s->blockState = TBLOCK_IMPLICIT_INPROGRESS;
4394 : 48940 : }
4395 : :
4396 : : /*
4397 : : * EndImplicitTransactionBlock
4398 : : * End an implicit transaction block, if we're in one.
4399 : : *
4400 : : * Like EndTransactionBlock, we just make any needed blockState change here.
4401 : : * The real work will be done in the upcoming CommitTransactionCommand().
4402 : : */
4403 : : void
4404 : 19578 : EndImplicitTransactionBlock(void)
4405 : : {
4406 : 19578 : TransactionState s = CurrentTransactionState;
4407 : :
4408 : : /*
4409 : : * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4410 : : * allowing CommitTransactionCommand to commit whatever happened during
4411 : : * the implicit transaction block as though it were a single statement.
4412 : : *
4413 : : * For caller convenience, we consider all other transaction states as
4414 : : * legal here; otherwise the caller would need its own state check, which
4415 : : * seems rather pointless.
4416 : : */
4417 [ + + ]: 19578 : if (s->blockState == TBLOCK_IMPLICIT_INPROGRESS)
4418 : 5494 : s->blockState = TBLOCK_STARTED;
4419 : 19578 : }
4420 : :
4421 : : /*
4422 : : * DefineSavepoint
4423 : : * This executes a SAVEPOINT command.
4424 : : */
4425 : : void
4426 : 1644 : DefineSavepoint(const char *name)
4427 : : {
4428 : 1644 : TransactionState s = CurrentTransactionState;
4429 : :
4430 : : /*
4431 : : * Workers synchronize transaction state at the beginning of each parallel
4432 : : * operation, so we can't account for new subtransactions after that
4433 : : * point. (Note that this check will certainly error out if s->blockState
4434 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4435 : : * below.)
4436 : : */
4437 [ + - - + ]: 1644 : if (IsInParallelMode() || IsParallelWorker())
4438 [ # # ]: 0 : ereport(ERROR,
4439 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4440 : : errmsg("cannot define savepoints during a parallel operation")));
4441 : :
4442 [ + + - - ]: 1644 : switch (s->blockState)
4443 : : {
4444 : 1636 : case TBLOCK_INPROGRESS:
4445 : : case TBLOCK_SUBINPROGRESS:
4446 : : /* Normal subtransaction start */
4447 : 1636 : PushTransaction();
4448 : 1636 : s = CurrentTransactionState; /* changed by push */
4449 : :
4450 : : /*
4451 : : * Savepoint names, like the TransactionState block itself, live
4452 : : * in TopTransactionContext.
4453 : : */
4454 [ + + ]: 1636 : if (name)
4455 : 1157 : s->name = MemoryContextStrdup(TopTransactionContext, name);
4456 : 1636 : break;
4457 : :
4458 : : /*
4459 : : * We disallow savepoint commands in implicit transaction blocks.
4460 : : * There would be no great difficulty in allowing them so far as
4461 : : * this module is concerned, but a savepoint seems inconsistent
4462 : : * with exec_simple_query's behavior of abandoning the whole query
4463 : : * string upon error. Also, the point of an implicit transaction
4464 : : * block (as opposed to a regular one) is to automatically close
4465 : : * after an error, so it's hard to see how a savepoint would fit
4466 : : * into that.
4467 : : *
4468 : : * The error messages for this are phrased as if there were no
4469 : : * active transaction block at all, which is historical but
4470 : : * perhaps could be improved.
4471 : : */
4472 : 8 : case TBLOCK_IMPLICIT_INPROGRESS:
4473 [ + - ]: 8 : ereport(ERROR,
4474 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4475 : : /* translator: %s represents an SQL statement name */
4476 : : errmsg("%s can only be used in transaction blocks",
4477 : : "SAVEPOINT")));
4478 : : break;
4479 : :
4480 : : /* These cases are invalid. */
4481 : 0 : case TBLOCK_DEFAULT:
4482 : : case TBLOCK_STARTED:
4483 : : case TBLOCK_BEGIN:
4484 : : case TBLOCK_PARALLEL_INPROGRESS:
4485 : : case TBLOCK_SUBBEGIN:
4486 : : case TBLOCK_END:
4487 : : case TBLOCK_SUBRELEASE:
4488 : : case TBLOCK_SUBCOMMIT:
4489 : : case TBLOCK_ABORT:
4490 : : case TBLOCK_SUBABORT:
4491 : : case TBLOCK_ABORT_END:
4492 : : case TBLOCK_SUBABORT_END:
4493 : : case TBLOCK_ABORT_PENDING:
4494 : : case TBLOCK_SUBABORT_PENDING:
4495 : : case TBLOCK_SUBRESTART:
4496 : : case TBLOCK_SUBABORT_RESTART:
4497 : : case TBLOCK_PREPARE:
4498 [ # # ]: 0 : elog(FATAL, "DefineSavepoint: unexpected state %s",
4499 : : BlockStateAsString(s->blockState));
4500 : : break;
4501 : : }
4502 : 1636 : }
4503 : :
4504 : : /*
4505 : : * ReleaseSavepoint
4506 : : * This executes a RELEASE command.
4507 : : *
4508 : : * As above, we don't actually do anything here except change blockState.
4509 : : */
4510 : : void
4511 : 185 : ReleaseSavepoint(const char *name)
4512 : : {
4513 : 185 : TransactionState s = CurrentTransactionState;
4514 : : TransactionState target,
4515 : : xact;
4516 : :
4517 : : /*
4518 : : * Workers synchronize transaction state at the beginning of each parallel
4519 : : * operation, so we can't account for transaction state change after that
4520 : : * point. (Note that this check will certainly error out if s->blockState
4521 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4522 : : * below.)
4523 : : */
4524 [ + - - + ]: 185 : if (IsInParallelMode() || IsParallelWorker())
4525 [ # # ]: 0 : ereport(ERROR,
4526 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4527 : : errmsg("cannot release savepoints during a parallel operation")));
4528 : :
4529 [ - + + - : 185 : switch (s->blockState)
- ]
4530 : : {
4531 : : /*
4532 : : * We can't release a savepoint if there is no savepoint defined.
4533 : : */
4534 : 0 : case TBLOCK_INPROGRESS:
4535 [ # # ]: 0 : ereport(ERROR,
4536 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4537 : : errmsg("savepoint \"%s\" does not exist", name)));
4538 : : break;
4539 : :
4540 : 4 : case TBLOCK_IMPLICIT_INPROGRESS:
4541 : : /* See comment about implicit transactions in DefineSavepoint */
4542 [ + - ]: 4 : ereport(ERROR,
4543 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4544 : : /* translator: %s represents an SQL statement name */
4545 : : errmsg("%s can only be used in transaction blocks",
4546 : : "RELEASE SAVEPOINT")));
4547 : : break;
4548 : :
4549 : : /*
4550 : : * We are in a non-aborted subtransaction. This is the only valid
4551 : : * case.
4552 : : */
4553 : 181 : case TBLOCK_SUBINPROGRESS:
4554 : 181 : break;
4555 : :
4556 : : /* These cases are invalid. */
4557 : 0 : case TBLOCK_DEFAULT:
4558 : : case TBLOCK_STARTED:
4559 : : case TBLOCK_BEGIN:
4560 : : case TBLOCK_PARALLEL_INPROGRESS:
4561 : : case TBLOCK_SUBBEGIN:
4562 : : case TBLOCK_END:
4563 : : case TBLOCK_SUBRELEASE:
4564 : : case TBLOCK_SUBCOMMIT:
4565 : : case TBLOCK_ABORT:
4566 : : case TBLOCK_SUBABORT:
4567 : : case TBLOCK_ABORT_END:
4568 : : case TBLOCK_SUBABORT_END:
4569 : : case TBLOCK_ABORT_PENDING:
4570 : : case TBLOCK_SUBABORT_PENDING:
4571 : : case TBLOCK_SUBRESTART:
4572 : : case TBLOCK_SUBABORT_RESTART:
4573 : : case TBLOCK_PREPARE:
4574 [ # # ]: 0 : elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4575 : : BlockStateAsString(s->blockState));
4576 : : break;
4577 : : }
4578 : :
4579 [ + - ]: 268 : for (target = s; target; target = target->parent)
4580 : : {
4581 [ + - + + ]: 268 : if (target->name && strcmp(target->name, name) == 0)
4582 : 181 : break;
4583 : : }
4584 : :
4585 [ - + ]: 181 : if (!target)
4586 [ # # ]: 0 : ereport(ERROR,
4587 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4588 : : errmsg("savepoint \"%s\" does not exist", name)));
4589 : :
4590 : : /* disallow crossing savepoint level boundaries */
4591 [ - + ]: 181 : if (target->savepointLevel != s->savepointLevel)
4592 [ # # ]: 0 : ereport(ERROR,
4593 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4594 : : errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4595 : :
4596 : : /*
4597 : : * Mark "commit pending" all subtransactions up to the target
4598 : : * subtransaction. The actual commits will happen when control gets to
4599 : : * CommitTransactionCommand.
4600 : : */
4601 : 181 : xact = CurrentTransactionState;
4602 : : for (;;)
4603 : : {
4604 : 87 : Assert(xact->blockState == TBLOCK_SUBINPROGRESS);
4605 : 268 : xact->blockState = TBLOCK_SUBRELEASE;
4606 [ + + ]: 268 : if (xact == target)
4607 : 181 : break;
4608 : 87 : xact = xact->parent;
4609 : : Assert(xact);
4610 : : }
4611 : 181 : }
4612 : :
4613 : : /*
4614 : : * RollbackToSavepoint
4615 : : * This executes a ROLLBACK TO <savepoint> command.
4616 : : *
4617 : : * As above, we don't actually do anything here except change blockState.
4618 : : */
4619 : : void
4620 : 487 : RollbackToSavepoint(const char *name)
4621 : : {
4622 : 487 : TransactionState s = CurrentTransactionState;
4623 : : TransactionState target,
4624 : : xact;
4625 : :
4626 : : /*
4627 : : * Workers synchronize transaction state at the beginning of each parallel
4628 : : * operation, so we can't account for transaction state change after that
4629 : : * point. (Note that this check will certainly error out if s->blockState
4630 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4631 : : * below.)
4632 : : */
4633 [ + - - + ]: 487 : if (IsInParallelMode() || IsParallelWorker())
4634 [ # # ]: 0 : ereport(ERROR,
4635 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4636 : : errmsg("cannot rollback to savepoints during a parallel operation")));
4637 : :
4638 [ + + + - : 487 : switch (s->blockState)
- ]
4639 : : {
4640 : : /*
4641 : : * We can't rollback to a savepoint if there is no savepoint
4642 : : * defined.
4643 : : */
4644 : 4 : case TBLOCK_INPROGRESS:
4645 : : case TBLOCK_ABORT:
4646 [ + - ]: 4 : ereport(ERROR,
4647 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4648 : : errmsg("savepoint \"%s\" does not exist", name)));
4649 : : break;
4650 : :
4651 : 4 : case TBLOCK_IMPLICIT_INPROGRESS:
4652 : : /* See comment about implicit transactions in DefineSavepoint */
4653 [ + - ]: 4 : ereport(ERROR,
4654 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4655 : : /* translator: %s represents an SQL statement name */
4656 : : errmsg("%s can only be used in transaction blocks",
4657 : : "ROLLBACK TO SAVEPOINT")));
4658 : : break;
4659 : :
4660 : : /*
4661 : : * There is at least one savepoint, so proceed.
4662 : : */
4663 : 479 : case TBLOCK_SUBINPROGRESS:
4664 : : case TBLOCK_SUBABORT:
4665 : 479 : break;
4666 : :
4667 : : /* These cases are invalid. */
4668 : 0 : case TBLOCK_DEFAULT:
4669 : : case TBLOCK_STARTED:
4670 : : case TBLOCK_BEGIN:
4671 : : case TBLOCK_PARALLEL_INPROGRESS:
4672 : : case TBLOCK_SUBBEGIN:
4673 : : case TBLOCK_END:
4674 : : case TBLOCK_SUBRELEASE:
4675 : : case TBLOCK_SUBCOMMIT:
4676 : : case TBLOCK_ABORT_END:
4677 : : case TBLOCK_SUBABORT_END:
4678 : : case TBLOCK_ABORT_PENDING:
4679 : : case TBLOCK_SUBABORT_PENDING:
4680 : : case TBLOCK_SUBRESTART:
4681 : : case TBLOCK_SUBABORT_RESTART:
4682 : : case TBLOCK_PREPARE:
4683 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4684 : : BlockStateAsString(s->blockState));
4685 : : break;
4686 : : }
4687 : :
4688 [ + - ]: 517 : for (target = s; target; target = target->parent)
4689 : : {
4690 [ + - + + ]: 517 : if (target->name && strcmp(target->name, name) == 0)
4691 : 479 : break;
4692 : : }
4693 : :
4694 [ - + ]: 479 : if (!target)
4695 [ # # ]: 0 : ereport(ERROR,
4696 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4697 : : errmsg("savepoint \"%s\" does not exist", name)));
4698 : :
4699 : : /* disallow crossing savepoint level boundaries */
4700 [ - + ]: 479 : if (target->savepointLevel != s->savepointLevel)
4701 [ # # ]: 0 : ereport(ERROR,
4702 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4703 : : errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4704 : :
4705 : : /*
4706 : : * Mark "abort pending" all subtransactions up to the target
4707 : : * subtransaction. The actual aborts will happen when control gets to
4708 : : * CommitTransactionCommand.
4709 : : */
4710 : 479 : xact = CurrentTransactionState;
4711 : : for (;;)
4712 : : {
4713 [ + + ]: 517 : if (xact == target)
4714 : 479 : break;
4715 [ + - ]: 38 : if (xact->blockState == TBLOCK_SUBINPROGRESS)
4716 : 38 : xact->blockState = TBLOCK_SUBABORT_PENDING;
4717 [ # # ]: 0 : else if (xact->blockState == TBLOCK_SUBABORT)
4718 : 0 : xact->blockState = TBLOCK_SUBABORT_END;
4719 : : else
4720 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4721 : : BlockStateAsString(xact->blockState));
4722 : 38 : xact = xact->parent;
4723 : : Assert(xact);
4724 : : }
4725 : :
4726 : : /* And mark the target as "restart pending" */
4727 [ + + ]: 479 : if (xact->blockState == TBLOCK_SUBINPROGRESS)
4728 : 338 : xact->blockState = TBLOCK_SUBRESTART;
4729 [ + - ]: 141 : else if (xact->blockState == TBLOCK_SUBABORT)
4730 : 141 : xact->blockState = TBLOCK_SUBABORT_RESTART;
4731 : : else
4732 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4733 : : BlockStateAsString(xact->blockState));
4734 : 479 : }
4735 : :
4736 : : /*
4737 : : * BeginInternalSubTransaction
4738 : : * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4739 : : * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_END,
4740 : : * and TBLOCK_PREPARE states, and therefore it can safely be used in
4741 : : * functions that might be called when not inside a BEGIN block or when
4742 : : * running deferred triggers at COMMIT/PREPARE time. Also, it
4743 : : * automatically does CommitTransactionCommand/StartTransactionCommand
4744 : : * instead of expecting the caller to do it.
4745 : : */
4746 : : void
4747 : 21239 : BeginInternalSubTransaction(const char *name)
4748 : : {
4749 : 21239 : TransactionState s = CurrentTransactionState;
4750 : 21239 : bool save_ExitOnAnyError = ExitOnAnyError;
4751 : :
4752 : : /*
4753 : : * Errors within this function are improbable, but if one does happen we
4754 : : * force a FATAL exit. Callers generally aren't prepared to handle losing
4755 : : * control, and moreover our transaction state is probably corrupted if we
4756 : : * fail partway through; so an ordinary ERROR longjmp isn't okay.
4757 : : */
4758 : 21239 : ExitOnAnyError = true;
4759 : :
4760 : : /*
4761 : : * We do not check for parallel mode here. It's permissible to start and
4762 : : * end "internal" subtransactions while in parallel mode, so long as no
4763 : : * new XIDs or command IDs are assigned. Enforcement of that occurs in
4764 : : * AssignTransactionId() and CommandCounterIncrement().
4765 : : */
4766 : :
4767 [ + - - ]: 21239 : switch (s->blockState)
4768 : : {
4769 : 21239 : case TBLOCK_STARTED:
4770 : : case TBLOCK_INPROGRESS:
4771 : : case TBLOCK_IMPLICIT_INPROGRESS:
4772 : : case TBLOCK_PARALLEL_INPROGRESS:
4773 : : case TBLOCK_END:
4774 : : case TBLOCK_PREPARE:
4775 : : case TBLOCK_SUBINPROGRESS:
4776 : : /* Normal subtransaction start */
4777 : 21239 : PushTransaction();
4778 : 21239 : s = CurrentTransactionState; /* changed by push */
4779 : :
4780 : : /*
4781 : : * Savepoint names, like the TransactionState block itself, live
4782 : : * in TopTransactionContext.
4783 : : */
4784 [ + + ]: 21239 : if (name)
4785 : 1048 : s->name = MemoryContextStrdup(TopTransactionContext, name);
4786 : 21239 : break;
4787 : :
4788 : : /* These cases are invalid. */
4789 : 0 : case TBLOCK_DEFAULT:
4790 : : case TBLOCK_BEGIN:
4791 : : case TBLOCK_SUBBEGIN:
4792 : : case TBLOCK_SUBRELEASE:
4793 : : case TBLOCK_SUBCOMMIT:
4794 : : case TBLOCK_ABORT:
4795 : : case TBLOCK_SUBABORT:
4796 : : case TBLOCK_ABORT_END:
4797 : : case TBLOCK_SUBABORT_END:
4798 : : case TBLOCK_ABORT_PENDING:
4799 : : case TBLOCK_SUBABORT_PENDING:
4800 : : case TBLOCK_SUBRESTART:
4801 : : case TBLOCK_SUBABORT_RESTART:
4802 [ # # ]: 0 : elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4803 : : BlockStateAsString(s->blockState));
4804 : : break;
4805 : : }
4806 : :
4807 : 21239 : CommitTransactionCommand();
4808 : 21239 : StartTransactionCommand();
4809 : :
4810 : 21239 : ExitOnAnyError = save_ExitOnAnyError;
4811 : 21239 : }
4812 : :
4813 : : /*
4814 : : * ReleaseCurrentSubTransaction
4815 : : *
4816 : : * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4817 : : * savepoint name (if any).
4818 : : * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4819 : : */
4820 : : void
4821 : 16516 : ReleaseCurrentSubTransaction(void)
4822 : : {
4823 : 16516 : TransactionState s = CurrentTransactionState;
4824 : :
4825 : : /*
4826 : : * We do not check for parallel mode here. It's permissible to start and
4827 : : * end "internal" subtransactions while in parallel mode, so long as no
4828 : : * new XIDs or command IDs are assigned.
4829 : : */
4830 : :
4831 [ - + ]: 16516 : if (s->blockState != TBLOCK_SUBINPROGRESS)
4832 [ # # ]: 0 : elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4833 : : BlockStateAsString(s->blockState));
4834 : : Assert(s->state == TRANS_INPROGRESS);
4835 : 16516 : MemoryContextSwitchTo(CurTransactionContext);
4836 : 16516 : CommitSubTransaction();
4837 : 16516 : s = CurrentTransactionState; /* changed by pop */
4838 : : Assert(s->state == TRANS_INPROGRESS);
4839 : 16516 : }
4840 : :
4841 : : /*
4842 : : * RollbackAndReleaseCurrentSubTransaction
4843 : : *
4844 : : * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4845 : : * of its savepoint name (if any).
4846 : : * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4847 : : */
4848 : : void
4849 : 4723 : RollbackAndReleaseCurrentSubTransaction(void)
4850 : : {
4851 : 4723 : TransactionState s = CurrentTransactionState;
4852 : :
4853 : : /*
4854 : : * We do not check for parallel mode here. It's permissible to start and
4855 : : * end "internal" subtransactions while in parallel mode, so long as no
4856 : : * new XIDs or command IDs are assigned.
4857 : : */
4858 : :
4859 [ + - - ]: 4723 : switch (s->blockState)
4860 : : {
4861 : : /* Must be in a subtransaction */
4862 : 4723 : case TBLOCK_SUBINPROGRESS:
4863 : : case TBLOCK_SUBABORT:
4864 : 4723 : break;
4865 : :
4866 : : /* These cases are invalid. */
4867 : 0 : case TBLOCK_DEFAULT:
4868 : : case TBLOCK_STARTED:
4869 : : case TBLOCK_BEGIN:
4870 : : case TBLOCK_IMPLICIT_INPROGRESS:
4871 : : case TBLOCK_PARALLEL_INPROGRESS:
4872 : : case TBLOCK_SUBBEGIN:
4873 : : case TBLOCK_INPROGRESS:
4874 : : case TBLOCK_END:
4875 : : case TBLOCK_SUBRELEASE:
4876 : : case TBLOCK_SUBCOMMIT:
4877 : : case TBLOCK_ABORT:
4878 : : case TBLOCK_ABORT_END:
4879 : : case TBLOCK_SUBABORT_END:
4880 : : case TBLOCK_ABORT_PENDING:
4881 : : case TBLOCK_SUBABORT_PENDING:
4882 : : case TBLOCK_SUBRESTART:
4883 : : case TBLOCK_SUBABORT_RESTART:
4884 : : case TBLOCK_PREPARE:
4885 [ # # ]: 0 : elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4886 : : BlockStateAsString(s->blockState));
4887 : : break;
4888 : : }
4889 : :
4890 : : /*
4891 : : * Abort the current subtransaction, if needed.
4892 : : */
4893 [ + + ]: 4723 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4894 : 3675 : AbortSubTransaction();
4895 : :
4896 : : /* And clean it up, too */
4897 : 4723 : CleanupSubTransaction();
4898 : :
4899 : 4723 : s = CurrentTransactionState; /* changed by pop */
4900 : : Assert(s->blockState == TBLOCK_SUBINPROGRESS ||
4901 : : s->blockState == TBLOCK_INPROGRESS ||
4902 : : s->blockState == TBLOCK_IMPLICIT_INPROGRESS ||
4903 : : s->blockState == TBLOCK_PARALLEL_INPROGRESS ||
4904 : : s->blockState == TBLOCK_STARTED);
4905 : 4723 : }
4906 : :
4907 : : /*
4908 : : * AbortOutOfAnyTransaction
4909 : : *
4910 : : * This routine is provided for error recovery purposes. It aborts any
4911 : : * active transaction or transaction block, leaving the system in a known
4912 : : * idle state.
4913 : : */
4914 : : void
4915 : 21410 : AbortOutOfAnyTransaction(void)
4916 : : {
4917 : 21410 : TransactionState s = CurrentTransactionState;
4918 : :
4919 : : /* Ensure we're not running in a doomed memory context */
4920 : 21410 : AtAbort_Memory();
4921 : :
4922 : : /*
4923 : : * Get out of any transaction or nested transaction
4924 : : */
4925 : : do
4926 : : {
4927 [ + + + + : 21412 : switch (s->blockState)
- - ]
4928 : : {
4929 : 20712 : case TBLOCK_DEFAULT:
4930 [ - + ]: 20712 : if (s->state == TRANS_DEFAULT)
4931 : : {
4932 : : /* Not in a transaction, do nothing */
4933 : : }
4934 : : else
4935 : : {
4936 : : /*
4937 : : * We can get here after an error during transaction start
4938 : : * (state will be TRANS_START). Need to clean up the
4939 : : * incompletely started transaction. First, adjust the
4940 : : * low-level state to suppress warning message from
4941 : : * AbortTransaction.
4942 : : */
4943 [ # # ]: 0 : if (s->state == TRANS_START)
4944 : 0 : s->state = TRANS_INPROGRESS;
4945 : 0 : AbortTransaction();
4946 : 0 : CleanupTransaction();
4947 : : }
4948 : 20712 : break;
4949 : 684 : case TBLOCK_STARTED:
4950 : : case TBLOCK_BEGIN:
4951 : : case TBLOCK_INPROGRESS:
4952 : : case TBLOCK_IMPLICIT_INPROGRESS:
4953 : : case TBLOCK_PARALLEL_INPROGRESS:
4954 : : case TBLOCK_END:
4955 : : case TBLOCK_ABORT_PENDING:
4956 : : case TBLOCK_PREPARE:
4957 : : /* In a transaction, so clean up */
4958 : 684 : AbortTransaction();
4959 : 684 : CleanupTransaction();
4960 : 684 : s->blockState = TBLOCK_DEFAULT;
4961 : 684 : break;
4962 : 14 : case TBLOCK_ABORT:
4963 : : case TBLOCK_ABORT_END:
4964 : :
4965 : : /*
4966 : : * AbortTransaction is already done, still need Cleanup.
4967 : : * However, if we failed partway through running ROLLBACK,
4968 : : * there will be an active portal running that command, which
4969 : : * we need to shut down before doing CleanupTransaction.
4970 : : */
4971 : 14 : AtAbort_Portals();
4972 : 14 : CleanupTransaction();
4973 : 14 : s->blockState = TBLOCK_DEFAULT;
4974 : 14 : break;
4975 : :
4976 : : /*
4977 : : * In a subtransaction, so clean it up and abort parent too
4978 : : */
4979 : 2 : case TBLOCK_SUBBEGIN:
4980 : : case TBLOCK_SUBINPROGRESS:
4981 : : case TBLOCK_SUBRELEASE:
4982 : : case TBLOCK_SUBCOMMIT:
4983 : : case TBLOCK_SUBABORT_PENDING:
4984 : : case TBLOCK_SUBRESTART:
4985 : 2 : AbortSubTransaction();
4986 : 2 : CleanupSubTransaction();
4987 : 2 : s = CurrentTransactionState; /* changed by pop */
4988 : 2 : break;
4989 : :
4990 : 0 : case TBLOCK_SUBABORT:
4991 : : case TBLOCK_SUBABORT_END:
4992 : : case TBLOCK_SUBABORT_RESTART:
4993 : : /* As above, but AbortSubTransaction already done */
4994 [ # # ]: 0 : if (s->curTransactionOwner)
4995 : : {
4996 : : /* As in TBLOCK_ABORT, might have a live portal to zap */
4997 : 0 : AtSubAbort_Portals(s->subTransactionId,
4998 : 0 : s->parent->subTransactionId,
4999 : : s->curTransactionOwner,
5000 : 0 : s->parent->curTransactionOwner);
5001 : : }
5002 : 0 : CleanupSubTransaction();
5003 : 0 : s = CurrentTransactionState; /* changed by pop */
5004 : 0 : break;
5005 : : }
5006 [ + + ]: 21412 : } while (s->blockState != TBLOCK_DEFAULT);
5007 : :
5008 : : /* Should be out of all subxacts now */
5009 : : Assert(s->parent == NULL);
5010 : :
5011 : : /*
5012 : : * Revert to TopMemoryContext, to ensure we exit in a well-defined state
5013 : : * whether there were any transactions to close or not. (Callers that
5014 : : * don't intend to exit soon should switch to some other context to avoid
5015 : : * long-term memory leaks.)
5016 : : */
5017 : 21410 : MemoryContextSwitchTo(TopMemoryContext);
5018 : 21410 : }
5019 : :
5020 : : /*
5021 : : * IsTransactionBlock --- are we within a transaction block?
5022 : : */
5023 : : bool
5024 : 359269 : IsTransactionBlock(void)
5025 : : {
5026 : 359269 : TransactionState s = CurrentTransactionState;
5027 : :
5028 [ + + + + ]: 359269 : if (s->blockState == TBLOCK_DEFAULT || s->blockState == TBLOCK_STARTED)
5029 : 289904 : return false;
5030 : :
5031 : 69365 : return true;
5032 : : }
5033 : :
5034 : : /*
5035 : : * IsTransactionOrTransactionBlock --- are we within either a transaction
5036 : : * or a transaction block? (The backend is only really "idle" when this
5037 : : * returns false.)
5038 : : *
5039 : : * This should match up with IsTransactionBlock and IsTransactionState.
5040 : : */
5041 : : bool
5042 : 467238 : IsTransactionOrTransactionBlock(void)
5043 : : {
5044 : 467238 : TransactionState s = CurrentTransactionState;
5045 : :
5046 [ + + ]: 467238 : if (s->blockState == TBLOCK_DEFAULT)
5047 : 372246 : return false;
5048 : :
5049 : 94992 : return true;
5050 : : }
5051 : :
5052 : : /*
5053 : : * TransactionBlockStatusCode - return status code to send in ReadyForQuery
5054 : : */
5055 : : char
5056 : 425364 : TransactionBlockStatusCode(void)
5057 : : {
5058 : 425364 : TransactionState s = CurrentTransactionState;
5059 : :
5060 [ + + + - ]: 425364 : switch (s->blockState)
5061 : : {
5062 : 331129 : case TBLOCK_DEFAULT:
5063 : : case TBLOCK_STARTED:
5064 : 331129 : return 'I'; /* idle --- not in transaction */
5065 : 93026 : case TBLOCK_BEGIN:
5066 : : case TBLOCK_SUBBEGIN:
5067 : : case TBLOCK_INPROGRESS:
5068 : : case TBLOCK_IMPLICIT_INPROGRESS:
5069 : : case TBLOCK_PARALLEL_INPROGRESS:
5070 : : case TBLOCK_SUBINPROGRESS:
5071 : : case TBLOCK_END:
5072 : : case TBLOCK_SUBRELEASE:
5073 : : case TBLOCK_SUBCOMMIT:
5074 : : case TBLOCK_PREPARE:
5075 : 93026 : return 'T'; /* in transaction */
5076 : 1209 : case TBLOCK_ABORT:
5077 : : case TBLOCK_SUBABORT:
5078 : : case TBLOCK_ABORT_END:
5079 : : case TBLOCK_SUBABORT_END:
5080 : : case TBLOCK_ABORT_PENDING:
5081 : : case TBLOCK_SUBABORT_PENDING:
5082 : : case TBLOCK_SUBRESTART:
5083 : : case TBLOCK_SUBABORT_RESTART:
5084 : 1209 : return 'E'; /* in failed transaction */
5085 : : }
5086 : :
5087 : : /* should never get here */
5088 [ # # ]: 0 : elog(FATAL, "invalid transaction block state: %s",
5089 : : BlockStateAsString(s->blockState));
5090 : : return 0; /* keep compiler quiet */
5091 : : }
5092 : :
5093 : : /*
5094 : : * IsSubTransaction
5095 : : */
5096 : : bool
5097 : 730438 : IsSubTransaction(void)
5098 : : {
5099 : 730438 : TransactionState s = CurrentTransactionState;
5100 : :
5101 [ + + ]: 730438 : if (s->nestingLevel >= 2)
5102 : 251 : return true;
5103 : :
5104 : 730187 : return false;
5105 : : }
5106 : :
5107 : : /*
5108 : : * StartSubTransaction
5109 : : *
5110 : : * If you're wondering why this is separate from PushTransaction: it's because
5111 : : * we can't conveniently do this stuff right inside DefineSavepoint. The
5112 : : * SAVEPOINT utility command will be executed inside a Portal, and if we
5113 : : * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
5114 : : * the Portal will undo those settings. So we make DefineSavepoint just
5115 : : * push a dummy transaction block, and when control returns to the main
5116 : : * idle loop, CommitTransactionCommand will be called, and we'll come here
5117 : : * to finish starting the subtransaction.
5118 : : */
5119 : : static void
5120 : 22875 : StartSubTransaction(void)
5121 : : {
5122 : 22875 : TransactionState s = CurrentTransactionState;
5123 : :
5124 [ - + ]: 22875 : if (s->state != TRANS_DEFAULT)
5125 [ # # ]: 0 : elog(WARNING, "StartSubTransaction while in %s state",
5126 : : TransStateAsString(s->state));
5127 : :
5128 : 22875 : s->state = TRANS_START;
5129 : :
5130 : : /*
5131 : : * Initialize subsystems for new subtransaction
5132 : : *
5133 : : * must initialize resource-management stuff first
5134 : : */
5135 : 22875 : AtSubStart_Memory();
5136 : 22875 : AtSubStart_ResourceOwner();
5137 : 22875 : AfterTriggerBeginSubXact();
5138 : :
5139 : 22875 : s->state = TRANS_INPROGRESS;
5140 : :
5141 : : /*
5142 : : * Call start-of-subxact callbacks
5143 : : */
5144 : 22875 : CallSubXactCallbacks(SUBXACT_EVENT_START_SUB, s->subTransactionId,
5145 : 22875 : s->parent->subTransactionId);
5146 : :
5147 : 22875 : ShowTransactionState("StartSubTransaction");
5148 : 22875 : }
5149 : :
5150 : : /*
5151 : : * CommitSubTransaction
5152 : : *
5153 : : * The caller has to make sure to always reassign CurrentTransactionState
5154 : : * if it has a local pointer to it after calling this function.
5155 : : */
5156 : : static void
5157 : 17384 : CommitSubTransaction(void)
5158 : : {
5159 : 17384 : TransactionState s = CurrentTransactionState;
5160 : :
5161 : 17384 : ShowTransactionState("CommitSubTransaction");
5162 : :
5163 [ - + ]: 17384 : if (s->state != TRANS_INPROGRESS)
5164 [ # # ]: 0 : elog(WARNING, "CommitSubTransaction while in %s state",
5165 : : TransStateAsString(s->state));
5166 : :
5167 : : /* Pre-commit processing goes here */
5168 : :
5169 : 17384 : CallSubXactCallbacks(SUBXACT_EVENT_PRE_COMMIT_SUB, s->subTransactionId,
5170 : 17384 : s->parent->subTransactionId);
5171 : :
5172 : : /*
5173 : : * If this subxact has started any unfinished parallel operation, clean up
5174 : : * its workers and exit parallel mode. Warn about leaked resources.
5175 : : */
5176 : 17384 : AtEOSubXact_Parallel(true, s->subTransactionId);
5177 [ - + ]: 17384 : if (s->parallelModeLevel != 0)
5178 : : {
5179 [ # # ]: 0 : elog(WARNING, "parallelModeLevel is %d not 0 at end of subtransaction",
5180 : : s->parallelModeLevel);
5181 : 0 : s->parallelModeLevel = 0;
5182 : : }
5183 : :
5184 : : /* Do the actual "commit", such as it is */
5185 : 17384 : s->state = TRANS_COMMIT;
5186 : :
5187 : : /* Must CCI to ensure commands of subtransaction are seen as done */
5188 : 17384 : CommandCounterIncrement();
5189 : :
5190 : : /*
5191 : : * Prior to 8.4 we marked subcommit in clog at this point. We now only
5192 : : * perform that step, if required, as part of the atomic update of the
5193 : : * whole transaction tree at top level commit or abort.
5194 : : */
5195 : :
5196 : : /* Post-commit cleanup */
5197 [ + + ]: 17384 : if (FullTransactionIdIsValid(s->fullTransactionId))
5198 : 15475 : AtSubCommit_childXids();
5199 : 17384 : AfterTriggerEndSubXact(true);
5200 : 17384 : AtSubCommit_Portals(s->subTransactionId,
5201 : 17384 : s->parent->subTransactionId,
5202 : 17384 : s->parent->nestingLevel,
5203 : 17384 : s->parent->curTransactionOwner);
5204 : 17384 : AtEOSubXact_LargeObject(true, s->subTransactionId,
5205 : 17384 : s->parent->subTransactionId);
5206 : 17384 : AtSubCommit_Notify();
5207 : :
5208 : 17384 : CallSubXactCallbacks(SUBXACT_EVENT_COMMIT_SUB, s->subTransactionId,
5209 : 17384 : s->parent->subTransactionId);
5210 : :
5211 : 17384 : ResourceOwnerRelease(s->curTransactionOwner,
5212 : : RESOURCE_RELEASE_BEFORE_LOCKS,
5213 : : true, false);
5214 : 17384 : AtEOSubXact_RelationCache(true, s->subTransactionId,
5215 : 17384 : s->parent->subTransactionId);
5216 : 17384 : AtEOSubXact_TypeCache();
5217 : 17384 : AtEOSubXact_Inval(true);
5218 : 17384 : AtSubCommit_smgr();
5219 : :
5220 : : /*
5221 : : * The only lock we actually release here is the subtransaction XID lock.
5222 : : */
5223 : 17384 : CurrentResourceOwner = s->curTransactionOwner;
5224 [ + + ]: 17384 : if (FullTransactionIdIsValid(s->fullTransactionId))
5225 : 15475 : XactLockTableDelete(XidFromFullTransactionId(s->fullTransactionId));
5226 : :
5227 : : /*
5228 : : * Other locks should get transferred to their parent resource owner.
5229 : : */
5230 : 17384 : ResourceOwnerRelease(s->curTransactionOwner,
5231 : : RESOURCE_RELEASE_LOCKS,
5232 : : true, false);
5233 : 17384 : ResourceOwnerRelease(s->curTransactionOwner,
5234 : : RESOURCE_RELEASE_AFTER_LOCKS,
5235 : : true, false);
5236 : :
5237 : 17384 : AtEOXact_GUC(true, s->gucNestLevel);
5238 : 17384 : AtEOSubXact_SPI(true, s->subTransactionId);
5239 : 17384 : AtEOSubXact_on_commit_actions(true, s->subTransactionId,
5240 : 17384 : s->parent->subTransactionId);
5241 : 17384 : AtEOSubXact_Namespace(true, s->subTransactionId,
5242 : 17384 : s->parent->subTransactionId);
5243 : 17384 : AtEOSubXact_Files(true, s->subTransactionId,
5244 : 17384 : s->parent->subTransactionId);
5245 : 17384 : AtEOSubXact_HashTables(true, s->nestingLevel);
5246 : 17384 : AtEOSubXact_PgStat(true, s->nestingLevel);
5247 : 17384 : AtEOSubXact_RI(true, s->subTransactionId, s->parent->subTransactionId);
5248 : 17384 : AtSubCommit_Snapshot(s->nestingLevel);
5249 : :
5250 : : /*
5251 : : * We need to restore the upper transaction's read-only state, in case the
5252 : : * upper is read-write while the child is read-only; GUC will incorrectly
5253 : : * think it should leave the child state in place.
5254 : : */
5255 : 17384 : XactReadOnly = s->prevXactReadOnly;
5256 : :
5257 : 17384 : CurrentResourceOwner = s->parent->curTransactionOwner;
5258 : 17384 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5259 : 17384 : ResourceOwnerDelete(s->curTransactionOwner);
5260 : 17384 : s->curTransactionOwner = NULL;
5261 : :
5262 : 17384 : AtSubCommit_Memory();
5263 : :
5264 : 17384 : s->state = TRANS_DEFAULT;
5265 : :
5266 : 17384 : PopTransaction();
5267 : 17384 : }
5268 : :
5269 : : /*
5270 : : * AbortSubTransaction
5271 : : */
5272 : : static void
5273 : 5491 : AbortSubTransaction(void)
5274 : : {
5275 : 5491 : TransactionState s = CurrentTransactionState;
5276 : :
5277 : : /* Prevent cancel/die interrupt while cleaning up */
5278 : 5491 : HOLD_INTERRUPTS();
5279 : :
5280 : : /* Make sure we have a valid memory context and resource owner */
5281 : 5491 : AtSubAbort_Memory();
5282 : 5491 : AtSubAbort_ResourceOwner();
5283 : :
5284 : : /*
5285 : : * Release any LW locks we might be holding as quickly as possible.
5286 : : * (Regular locks, however, must be held till we finish aborting.)
5287 : : * Releasing LW locks is critical since we might try to grab them again
5288 : : * while cleaning up!
5289 : : *
5290 : : * FIXME This may be incorrect --- Are there some locks we should keep?
5291 : : * Buffer locks, for example? I don't think so but I'm not sure.
5292 : : */
5293 : 5491 : LWLockReleaseAll();
5294 : :
5295 : : /*
5296 : : * Cleanup waiting for LSN if any.
5297 : : */
5298 : 5491 : WaitLSNCleanup();
5299 : :
5300 : 5491 : pgstat_report_wait_end();
5301 : 5491 : pgstat_progress_end_command();
5302 : :
5303 : 5491 : pgaio_error_cleanup();
5304 : :
5305 : 5491 : UnlockBuffers();
5306 : :
5307 : : /* Reset WAL record construction state */
5308 : 5491 : XLogResetInsertion();
5309 : :
5310 : : /* Cancel condition variable sleep */
5311 : 5491 : ConditionVariableCancelSleep();
5312 : :
5313 : : /*
5314 : : * Also clean up any open wait for lock, since the lock manager will choke
5315 : : * if we try to wait for another lock before doing this.
5316 : : */
5317 : 5491 : LockErrorCleanup();
5318 : :
5319 : : /*
5320 : : * If any timeout events are still active, make sure the timeout interrupt
5321 : : * is scheduled. This covers possible loss of a timeout interrupt due to
5322 : : * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
5323 : : * We delay this till after LockErrorCleanup so that we don't uselessly
5324 : : * reschedule lock or deadlock check timeouts.
5325 : : */
5326 : 5491 : reschedule_timeouts();
5327 : :
5328 : : /*
5329 : : * Re-enable signals, in case we got here by longjmp'ing out of a signal
5330 : : * handler. We do this fairly early in the sequence so that the timeout
5331 : : * infrastructure will be functional if needed while aborting.
5332 : : */
5333 : 5491 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5334 : :
5335 : : /*
5336 : : * check the current transaction state
5337 : : */
5338 : 5491 : ShowTransactionState("AbortSubTransaction");
5339 : :
5340 [ - + ]: 5491 : if (s->state != TRANS_INPROGRESS)
5341 [ # # ]: 0 : elog(WARNING, "AbortSubTransaction while in %s state",
5342 : : TransStateAsString(s->state));
5343 : :
5344 : 5491 : s->state = TRANS_ABORT;
5345 : :
5346 : : /*
5347 : : * Reset user ID which might have been changed transiently. (See notes in
5348 : : * AbortTransaction.)
5349 : : */
5350 : 5491 : SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
5351 : :
5352 : : /* Forget about any active REINDEX. */
5353 : 5491 : ResetReindexState(s->nestingLevel);
5354 : :
5355 : : /* Reset logical streaming state. */
5356 : 5491 : ResetLogicalStreamingState();
5357 : :
5358 : : /*
5359 : : * No need for SnapBuildResetExportedSnapshotState() here, snapshot
5360 : : * exports are not supported in subtransactions.
5361 : : */
5362 : :
5363 : : /*
5364 : : * If this subxact has started any unfinished parallel operation, clean up
5365 : : * its workers and exit parallel mode. Don't warn about leaked resources.
5366 : : */
5367 : 5491 : AtEOSubXact_Parallel(false, s->subTransactionId);
5368 : 5491 : s->parallelModeLevel = 0;
5369 : :
5370 : : /*
5371 : : * We can skip all this stuff if the subxact failed before creating a
5372 : : * ResourceOwner...
5373 : : */
5374 [ + - ]: 5491 : if (s->curTransactionOwner)
5375 : : {
5376 : 5491 : AfterTriggerEndSubXact(false);
5377 : 5491 : AtSubAbort_Portals(s->subTransactionId,
5378 : 5491 : s->parent->subTransactionId,
5379 : : s->curTransactionOwner,
5380 : 5491 : s->parent->curTransactionOwner);
5381 : 5491 : AtEOSubXact_LargeObject(false, s->subTransactionId,
5382 : 5491 : s->parent->subTransactionId);
5383 : 5491 : AtSubAbort_Notify();
5384 : :
5385 : : /* Advertise the fact that we aborted in pg_xact. */
5386 : 5491 : (void) RecordTransactionAbort(true);
5387 : :
5388 : : /* Post-abort cleanup */
5389 [ + + ]: 5491 : if (FullTransactionIdIsValid(s->fullTransactionId))
5390 : 865 : AtSubAbort_childXids();
5391 : :
5392 : 5491 : CallSubXactCallbacks(SUBXACT_EVENT_ABORT_SUB, s->subTransactionId,
5393 : 5491 : s->parent->subTransactionId);
5394 : :
5395 : 5491 : ResourceOwnerRelease(s->curTransactionOwner,
5396 : : RESOURCE_RELEASE_BEFORE_LOCKS,
5397 : : false, false);
5398 : :
5399 : 5491 : AtEOXact_Aio(false);
5400 : 5491 : AtEOSubXact_RelationCache(false, s->subTransactionId,
5401 : 5491 : s->parent->subTransactionId);
5402 : 5491 : AtEOSubXact_TypeCache();
5403 : 5491 : AtEOSubXact_Inval(false);
5404 : 5491 : ResourceOwnerRelease(s->curTransactionOwner,
5405 : : RESOURCE_RELEASE_LOCKS,
5406 : : false, false);
5407 : 5491 : ResourceOwnerRelease(s->curTransactionOwner,
5408 : : RESOURCE_RELEASE_AFTER_LOCKS,
5409 : : false, false);
5410 : 5491 : AtSubAbort_smgr();
5411 : :
5412 : 5491 : AtEOXact_GUC(false, s->gucNestLevel);
5413 : 5491 : AtEOSubXact_SPI(false, s->subTransactionId);
5414 : 5491 : AtEOSubXact_on_commit_actions(false, s->subTransactionId,
5415 : 5491 : s->parent->subTransactionId);
5416 : 5491 : AtEOSubXact_Namespace(false, s->subTransactionId,
5417 : 5491 : s->parent->subTransactionId);
5418 : 5491 : AtEOSubXact_Files(false, s->subTransactionId,
5419 : 5491 : s->parent->subTransactionId);
5420 : 5491 : AtEOSubXact_HashTables(false, s->nestingLevel);
5421 : 5491 : AtEOSubXact_PgStat(false, s->nestingLevel);
5422 : 5491 : AtEOSubXact_RI(false, s->subTransactionId, s->parent->subTransactionId);
5423 : 5491 : AtSubAbort_Snapshot(s->nestingLevel);
5424 : : }
5425 : :
5426 : : /*
5427 : : * Restore the upper transaction's read-only state, too. This should be
5428 : : * redundant with GUC's cleanup but we may as well do it for consistency
5429 : : * with the commit case.
5430 : : */
5431 : 5491 : XactReadOnly = s->prevXactReadOnly;
5432 : :
5433 : 5491 : RESUME_INTERRUPTS();
5434 : 5491 : }
5435 : :
5436 : : /*
5437 : : * CleanupSubTransaction
5438 : : *
5439 : : * The caller has to make sure to always reassign CurrentTransactionState
5440 : : * if it has a local pointer to it after calling this function.
5441 : : */
5442 : : static void
5443 : 5491 : CleanupSubTransaction(void)
5444 : : {
5445 : 5491 : TransactionState s = CurrentTransactionState;
5446 : :
5447 : 5491 : ShowTransactionState("CleanupSubTransaction");
5448 : :
5449 [ - + ]: 5491 : if (s->state != TRANS_ABORT)
5450 [ # # ]: 0 : elog(WARNING, "CleanupSubTransaction while in %s state",
5451 : : TransStateAsString(s->state));
5452 : :
5453 : 5491 : AtSubCleanup_Portals(s->subTransactionId);
5454 : :
5455 : 5491 : CurrentResourceOwner = s->parent->curTransactionOwner;
5456 : 5491 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5457 [ + - ]: 5491 : if (s->curTransactionOwner)
5458 : 5491 : ResourceOwnerDelete(s->curTransactionOwner);
5459 : 5491 : s->curTransactionOwner = NULL;
5460 : :
5461 : 5491 : AtSubCleanup_Memory();
5462 : :
5463 : 5491 : s->state = TRANS_DEFAULT;
5464 : :
5465 : 5491 : PopTransaction();
5466 : 5491 : }
5467 : :
5468 : : /*
5469 : : * PushTransaction
5470 : : * Create transaction state stack entry for a subtransaction
5471 : : *
5472 : : * The caller has to make sure to always reassign CurrentTransactionState
5473 : : * if it has a local pointer to it after calling this function.
5474 : : */
5475 : : static void
5476 : 22875 : PushTransaction(void)
5477 : : {
5478 : 22875 : TransactionState p = CurrentTransactionState;
5479 : : TransactionState s;
5480 : :
5481 : : /*
5482 : : * We keep subtransaction state nodes in TopTransactionContext.
5483 : : */
5484 : : s = (TransactionState)
5485 : 22875 : MemoryContextAllocZero(TopTransactionContext,
5486 : : sizeof(TransactionStateData));
5487 : :
5488 : : /*
5489 : : * Assign a subtransaction ID, watching out for counter wraparound.
5490 : : */
5491 : 22875 : currentSubTransactionId += 1;
5492 [ - + ]: 22875 : if (currentSubTransactionId == InvalidSubTransactionId)
5493 : : {
5494 : 0 : currentSubTransactionId -= 1;
5495 : 0 : pfree(s);
5496 [ # # ]: 0 : ereport(ERROR,
5497 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5498 : : errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5499 : : }
5500 : :
5501 : : /*
5502 : : * We can now stack a minimally valid subtransaction without fear of
5503 : : * failure.
5504 : : */
5505 : 22875 : s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5506 : 22875 : s->subTransactionId = currentSubTransactionId;
5507 : 22875 : s->parent = p;
5508 : 22875 : s->nestingLevel = p->nestingLevel + 1;
5509 : 22875 : s->gucNestLevel = NewGUCNestLevel();
5510 : 22875 : s->savepointLevel = p->savepointLevel;
5511 : 22875 : s->state = TRANS_DEFAULT;
5512 : 22875 : s->blockState = TBLOCK_SUBBEGIN;
5513 : 22875 : GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
5514 : 22875 : s->prevXactReadOnly = XactReadOnly;
5515 : 22875 : s->startedInRecovery = p->startedInRecovery;
5516 : 22875 : s->parallelModeLevel = 0;
5517 [ + + - + ]: 22875 : s->parallelChildXact = (p->parallelModeLevel != 0 || p->parallelChildXact);
5518 : 22875 : s->topXidLogged = false;
5519 : :
5520 : 22875 : CurrentTransactionState = s;
5521 : :
5522 : : /*
5523 : : * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5524 : : * with the subtransaction from here on out; in particular they should not
5525 : : * assume that it necessarily has a transaction context, resource owner,
5526 : : * or XID.
5527 : : */
5528 : 22875 : }
5529 : :
5530 : : /*
5531 : : * PopTransaction
5532 : : * Pop back to parent transaction state
5533 : : *
5534 : : * The caller has to make sure to always reassign CurrentTransactionState
5535 : : * if it has a local pointer to it after calling this function.
5536 : : */
5537 : : static void
5538 : 22875 : PopTransaction(void)
5539 : : {
5540 : 22875 : TransactionState s = CurrentTransactionState;
5541 : :
5542 [ - + ]: 22875 : if (s->state != TRANS_DEFAULT)
5543 [ # # ]: 0 : elog(WARNING, "PopTransaction while in %s state",
5544 : : TransStateAsString(s->state));
5545 : :
5546 [ - + ]: 22875 : if (s->parent == NULL)
5547 [ # # ]: 0 : elog(FATAL, "PopTransaction with no parent");
5548 : :
5549 : 22875 : CurrentTransactionState = s->parent;
5550 : :
5551 : : /* Let's just make sure CurTransactionContext is good */
5552 : 22875 : CurTransactionContext = s->parent->curTransactionContext;
5553 : 22875 : MemoryContextSwitchTo(CurTransactionContext);
5554 : :
5555 : : /* Ditto for ResourceOwner links */
5556 : 22875 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5557 : 22875 : CurrentResourceOwner = s->parent->curTransactionOwner;
5558 : :
5559 : : /* Free the old child structure */
5560 [ + + ]: 22875 : if (s->name)
5561 : 2205 : pfree(s->name);
5562 : 22875 : pfree(s);
5563 : 22875 : }
5564 : :
5565 : : /*
5566 : : * EstimateTransactionStateSpace
5567 : : * Estimate the amount of space that will be needed by
5568 : : * SerializeTransactionState. It would be OK to overestimate slightly,
5569 : : * but it's simple for us to work out the precise value, so we do.
5570 : : */
5571 : : Size
5572 : 681 : EstimateTransactionStateSpace(void)
5573 : : {
5574 : : TransactionState s;
5575 : 681 : Size nxids = 0;
5576 : 681 : Size size = SerializedTransactionStateHeaderSize;
5577 : :
5578 [ + + ]: 3054 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5579 : : {
5580 [ + + ]: 2373 : if (FullTransactionIdIsValid(s->fullTransactionId))
5581 : 1359 : nxids = add_size(nxids, 1);
5582 : 2373 : nxids = add_size(nxids, s->nChildXids);
5583 : : }
5584 : :
5585 : 681 : return add_size(size, mul_size(sizeof(TransactionId), nxids));
5586 : : }
5587 : :
5588 : : /*
5589 : : * SerializeTransactionState
5590 : : * Write out relevant details of our transaction state that will be
5591 : : * needed by a parallel worker.
5592 : : *
5593 : : * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5594 : : * associated with this transaction. These are serialized into a
5595 : : * caller-supplied buffer big enough to hold the number of bytes reported by
5596 : : * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5597 : : * convenience of the receiving process.
5598 : : */
5599 : : void
5600 : 681 : SerializeTransactionState(Size maxsize, char *start_address)
5601 : : {
5602 : : TransactionState s;
5603 : 681 : Size nxids = 0;
5604 : 681 : Size i = 0;
5605 : : TransactionId *workspace;
5606 : : SerializedTransactionState *result;
5607 : :
5608 : 681 : result = (SerializedTransactionState *) start_address;
5609 : :
5610 : 681 : result->xactIsoLevel = XactIsoLevel;
5611 : 681 : result->xactDeferrable = XactDeferrable;
5612 : 681 : result->topFullTransactionId = XactTopFullTransactionId;
5613 : 681 : result->currentFullTransactionId =
5614 : 681 : CurrentTransactionState->fullTransactionId;
5615 : 681 : result->currentCommandId = currentCommandId;
5616 : :
5617 : : /*
5618 : : * If we're running in a parallel worker and launching a parallel worker
5619 : : * of our own, we can just pass along the information that was passed to
5620 : : * us.
5621 : : */
5622 [ - + ]: 681 : if (nParallelCurrentXids > 0)
5623 : : {
5624 : 0 : result->nParallelCurrentXids = nParallelCurrentXids;
5625 : 0 : memcpy(&result->parallelCurrentXids[0], ParallelCurrentXids,
5626 : : nParallelCurrentXids * sizeof(TransactionId));
5627 : 0 : return;
5628 : : }
5629 : :
5630 : : /*
5631 : : * OK, we need to generate a sorted list of XIDs that our workers should
5632 : : * view as current. First, figure out how many there are.
5633 : : */
5634 [ + + ]: 3054 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5635 : : {
5636 [ + + ]: 2373 : if (FullTransactionIdIsValid(s->fullTransactionId))
5637 : 1359 : nxids = add_size(nxids, 1);
5638 : 2373 : nxids = add_size(nxids, s->nChildXids);
5639 : : }
5640 : : Assert(SerializedTransactionStateHeaderSize + nxids * sizeof(TransactionId)
5641 : : <= maxsize);
5642 : :
5643 : : /* Copy them to our scratch space. */
5644 : 681 : workspace = palloc_array(TransactionId, nxids);
5645 [ + + ]: 3054 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5646 : : {
5647 [ + + ]: 2373 : if (FullTransactionIdIsValid(s->fullTransactionId))
5648 : 1359 : workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
5649 [ - + ]: 2373 : if (s->nChildXids > 0)
5650 : 0 : memcpy(&workspace[i], s->childXids,
5651 : 0 : s->nChildXids * sizeof(TransactionId));
5652 : 2373 : i += s->nChildXids;
5653 : : }
5654 : : Assert(i == nxids);
5655 : :
5656 : : /* Sort them. */
5657 : 681 : qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5658 : :
5659 : : /* Copy data into output area. */
5660 : 681 : result->nParallelCurrentXids = nxids;
5661 : 681 : memcpy(&result->parallelCurrentXids[0], workspace,
5662 : : nxids * sizeof(TransactionId));
5663 : : }
5664 : :
5665 : : /*
5666 : : * StartParallelWorkerTransaction
5667 : : * Start a parallel worker transaction, restoring the relevant
5668 : : * transaction state serialized by SerializeTransactionState.
5669 : : */
5670 : : void
5671 : 2020 : StartParallelWorkerTransaction(char *tstatespace)
5672 : : {
5673 : : SerializedTransactionState *tstate;
5674 : :
5675 : : Assert(CurrentTransactionState->blockState == TBLOCK_DEFAULT);
5676 : 2020 : StartTransaction();
5677 : :
5678 : 2020 : tstate = (SerializedTransactionState *) tstatespace;
5679 : 2020 : XactIsoLevel = tstate->xactIsoLevel;
5680 : 2020 : XactDeferrable = tstate->xactDeferrable;
5681 : 2020 : XactTopFullTransactionId = tstate->topFullTransactionId;
5682 : 2020 : CurrentTransactionState->fullTransactionId =
5683 : : tstate->currentFullTransactionId;
5684 : 2020 : currentCommandId = tstate->currentCommandId;
5685 : 2020 : nParallelCurrentXids = tstate->nParallelCurrentXids;
5686 : 2020 : ParallelCurrentXids = &tstate->parallelCurrentXids[0];
5687 : :
5688 : 2020 : CurrentTransactionState->blockState = TBLOCK_PARALLEL_INPROGRESS;
5689 : 2020 : }
5690 : :
5691 : : /*
5692 : : * EndParallelWorkerTransaction
5693 : : * End a parallel worker transaction.
5694 : : */
5695 : : void
5696 : 2012 : EndParallelWorkerTransaction(void)
5697 : : {
5698 : : Assert(CurrentTransactionState->blockState == TBLOCK_PARALLEL_INPROGRESS);
5699 : 2012 : CommitTransaction();
5700 : 2012 : CurrentTransactionState->blockState = TBLOCK_DEFAULT;
5701 : 2012 : }
5702 : :
5703 : : /*
5704 : : * ShowTransactionState
5705 : : * Debug support
5706 : : */
5707 : : static void
5708 : 1347733 : ShowTransactionState(const char *str)
5709 : : {
5710 : : /* skip work if message will definitely not be printed */
5711 [ - + ]: 1347733 : if (message_level_is_interesting(DEBUG5))
5712 : 0 : ShowTransactionStateRec(str, CurrentTransactionState);
5713 : 1347733 : }
5714 : :
5715 : : /*
5716 : : * ShowTransactionStateRec
5717 : : * Recursive subroutine for ShowTransactionState
5718 : : */
5719 : : static void
5720 : 0 : ShowTransactionStateRec(const char *str, TransactionState s)
5721 : : {
5722 : : StringInfoData buf;
5723 : :
5724 [ # # ]: 0 : if (s->parent)
5725 : : {
5726 : : /*
5727 : : * Since this function recurses, it could be driven to stack overflow.
5728 : : * This is just a debugging aid, so we can leave out some details
5729 : : * instead of erroring out with check_stack_depth().
5730 : : */
5731 [ # # ]: 0 : if (stack_is_too_deep())
5732 [ # # ]: 0 : ereport(DEBUG5,
5733 : : (errmsg_internal("%s(%d): parent omitted to avoid stack overflow",
5734 : : str, s->nestingLevel)));
5735 : : else
5736 : 0 : ShowTransactionStateRec(str, s->parent);
5737 : : }
5738 : :
5739 : 0 : initStringInfo(&buf);
5740 [ # # ]: 0 : if (s->nChildXids > 0)
5741 : : {
5742 : : int i;
5743 : :
5744 : 0 : appendStringInfo(&buf, ", children: %u", s->childXids[0]);
5745 [ # # ]: 0 : for (i = 1; i < s->nChildXids; i++)
5746 : 0 : appendStringInfo(&buf, " %u", s->childXids[i]);
5747 : : }
5748 [ # # # # : 0 : ereport(DEBUG5,
# # ]
5749 : : (errmsg_internal("%s(%d) name: %s; blockState: %s; state: %s, xid/subid/cid: %u/%u/%u%s%s",
5750 : : str, s->nestingLevel,
5751 : : s->name ? s->name : "unnamed",
5752 : : BlockStateAsString(s->blockState),
5753 : : TransStateAsString(s->state),
5754 : : XidFromFullTransactionId(s->fullTransactionId),
5755 : : s->subTransactionId,
5756 : : currentCommandId,
5757 : : currentCommandIdUsed ? " (used)" : "",
5758 : : buf.data)));
5759 : 0 : pfree(buf.data);
5760 : 0 : }
5761 : :
5762 : : /*
5763 : : * BlockStateAsString
5764 : : * Debug support
5765 : : */
5766 : : static const char *
5767 : 0 : BlockStateAsString(TBlockState blockState)
5768 : : {
5769 [ # # # # : 0 : switch (blockState)
# # # # #
# # # # #
# # # # #
# # ]
5770 : : {
5771 : 0 : case TBLOCK_DEFAULT:
5772 : 0 : return "DEFAULT";
5773 : 0 : case TBLOCK_STARTED:
5774 : 0 : return "STARTED";
5775 : 0 : case TBLOCK_BEGIN:
5776 : 0 : return "BEGIN";
5777 : 0 : case TBLOCK_INPROGRESS:
5778 : 0 : return "INPROGRESS";
5779 : 0 : case TBLOCK_IMPLICIT_INPROGRESS:
5780 : 0 : return "IMPLICIT_INPROGRESS";
5781 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
5782 : 0 : return "PARALLEL_INPROGRESS";
5783 : 0 : case TBLOCK_END:
5784 : 0 : return "END";
5785 : 0 : case TBLOCK_ABORT:
5786 : 0 : return "ABORT";
5787 : 0 : case TBLOCK_ABORT_END:
5788 : 0 : return "ABORT_END";
5789 : 0 : case TBLOCK_ABORT_PENDING:
5790 : 0 : return "ABORT_PENDING";
5791 : 0 : case TBLOCK_PREPARE:
5792 : 0 : return "PREPARE";
5793 : 0 : case TBLOCK_SUBBEGIN:
5794 : 0 : return "SUBBEGIN";
5795 : 0 : case TBLOCK_SUBINPROGRESS:
5796 : 0 : return "SUBINPROGRESS";
5797 : 0 : case TBLOCK_SUBRELEASE:
5798 : 0 : return "SUBRELEASE";
5799 : 0 : case TBLOCK_SUBCOMMIT:
5800 : 0 : return "SUBCOMMIT";
5801 : 0 : case TBLOCK_SUBABORT:
5802 : 0 : return "SUBABORT";
5803 : 0 : case TBLOCK_SUBABORT_END:
5804 : 0 : return "SUBABORT_END";
5805 : 0 : case TBLOCK_SUBABORT_PENDING:
5806 : 0 : return "SUBABORT_PENDING";
5807 : 0 : case TBLOCK_SUBRESTART:
5808 : 0 : return "SUBRESTART";
5809 : 0 : case TBLOCK_SUBABORT_RESTART:
5810 : 0 : return "SUBABORT_RESTART";
5811 : : }
5812 : 0 : return "UNRECOGNIZED";
5813 : : }
5814 : :
5815 : : /*
5816 : : * TransStateAsString
5817 : : * Debug support
5818 : : */
5819 : : static const char *
5820 : 0 : TransStateAsString(TransState state)
5821 : : {
5822 [ # # # # : 0 : switch (state)
# # # ]
5823 : : {
5824 : 0 : case TRANS_DEFAULT:
5825 : 0 : return "DEFAULT";
5826 : 0 : case TRANS_START:
5827 : 0 : return "START";
5828 : 0 : case TRANS_INPROGRESS:
5829 : 0 : return "INPROGRESS";
5830 : 0 : case TRANS_COMMIT:
5831 : 0 : return "COMMIT";
5832 : 0 : case TRANS_ABORT:
5833 : 0 : return "ABORT";
5834 : 0 : case TRANS_PREPARE:
5835 : 0 : return "PREPARE";
5836 : : }
5837 : 0 : return "UNRECOGNIZED";
5838 : : }
5839 : :
5840 : : /*
5841 : : * xactGetCommittedChildren
5842 : : *
5843 : : * Gets the list of committed children of the current transaction. The return
5844 : : * value is the number of child transactions. *ptr is set to point to an
5845 : : * array of TransactionIds. The array is allocated in TopTransactionContext;
5846 : : * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
5847 : : * If there are no subxacts, *ptr is set to NULL.
5848 : : */
5849 : : int
5850 : 637367 : xactGetCommittedChildren(TransactionId **ptr)
5851 : : {
5852 : 637367 : TransactionState s = CurrentTransactionState;
5853 : :
5854 [ + + ]: 637367 : if (s->nChildXids == 0)
5855 : 636731 : *ptr = NULL;
5856 : : else
5857 : 636 : *ptr = s->childXids;
5858 : :
5859 : 637367 : return s->nChildXids;
5860 : : }
5861 : :
5862 : : /*
5863 : : * XLOG support routines
5864 : : */
5865 : :
5866 : :
5867 : : /*
5868 : : * Log the commit record for a plain or twophase transaction commit.
5869 : : *
5870 : : * A 2pc commit will be emitted when twophase_xid is valid, a plain one
5871 : : * otherwise.
5872 : : */
5873 : : XLogRecPtr
5874 : 159624 : XactLogCommitRecord(TimestampTz commit_time,
5875 : : int nsubxacts, TransactionId *subxacts,
5876 : : int nrels, RelFileLocator *rels,
5877 : : int ndroppedstats, xl_xact_stats_item *droppedstats,
5878 : : int nmsgs, SharedInvalidationMessage *msgs,
5879 : : bool relcacheInval,
5880 : : int xactflags, TransactionId twophase_xid,
5881 : : const char *twophase_gid)
5882 : : {
5883 : : xl_xact_commit xlrec;
5884 : : xl_xact_xinfo xl_xinfo;
5885 : : xl_xact_dbinfo xl_dbinfo;
5886 : : xl_xact_subxacts xl_subxacts;
5887 : : xl_xact_relfilelocators xl_relfilelocators;
5888 : : xl_xact_stats_items xl_dropped_stats;
5889 : : xl_xact_invals xl_invals;
5890 : : xl_xact_twophase xl_twophase;
5891 : : xl_xact_origin xl_origin;
5892 : : uint8 info;
5893 : :
5894 : : Assert(CritSectionCount > 0);
5895 : :
5896 : 159624 : xl_xinfo.xinfo = 0;
5897 : :
5898 : : /* decide between a plain and 2pc commit */
5899 [ + + ]: 159624 : if (!TransactionIdIsValid(twophase_xid))
5900 : 159350 : info = XLOG_XACT_COMMIT;
5901 : : else
5902 : 274 : info = XLOG_XACT_COMMIT_PREPARED;
5903 : :
5904 : : /* First figure out and collect all the information needed */
5905 : :
5906 : 159624 : xlrec.xact_time = commit_time;
5907 : :
5908 [ + + ]: 159624 : if (relcacheInval)
5909 : 4629 : xl_xinfo.xinfo |= XACT_COMPLETION_UPDATE_RELCACHE_FILE;
5910 [ + + ]: 159624 : if (forceSyncCommit)
5911 : 576 : xl_xinfo.xinfo |= XACT_COMPLETION_FORCE_SYNC_COMMIT;
5912 [ + + ]: 159624 : if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5913 : 64415 : xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5914 : :
5915 : : /*
5916 : : * Check if the caller would like to ask standbys for immediate feedback
5917 : : * once this commit is applied.
5918 : : */
5919 [ + + ]: 159624 : if (synchronous_commit >= SYNCHRONOUS_COMMIT_REMOTE_APPLY)
5920 : 2 : xl_xinfo.xinfo |= XACT_COMPLETION_APPLY_FEEDBACK;
5921 : :
5922 : : /*
5923 : : * Relcache invalidations requires information about the current database
5924 : : * and so does logical decoding.
5925 : : */
5926 [ + + + + : 159624 : if (nmsgs > 0 || XLogLogicalInfoActive())
+ + ]
5927 : : {
5928 : 112694 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
5929 : 112694 : xl_dbinfo.dbId = MyDatabaseId;
5930 : 112694 : xl_dbinfo.tsId = MyDatabaseTableSpace;
5931 : : }
5932 : :
5933 [ + + ]: 159624 : if (nsubxacts > 0)
5934 : : {
5935 : 531 : xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
5936 : 531 : xl_subxacts.nsubxacts = nsubxacts;
5937 : : }
5938 : :
5939 [ + + ]: 159624 : if (nrels > 0)
5940 : : {
5941 : 12566 : xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILELOCATORS;
5942 : 12566 : xl_relfilelocators.nrels = nrels;
5943 : 12566 : info |= XLR_SPECIAL_REL_UPDATE;
5944 : : }
5945 : :
5946 [ + + ]: 159624 : if (ndroppedstats > 0)
5947 : : {
5948 : 14988 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DROPPED_STATS;
5949 : 14988 : xl_dropped_stats.nitems = ndroppedstats;
5950 : : }
5951 : :
5952 [ + + ]: 159624 : if (nmsgs > 0)
5953 : : {
5954 : 111743 : xl_xinfo.xinfo |= XACT_XINFO_HAS_INVALS;
5955 : 111743 : xl_invals.nmsgs = nmsgs;
5956 : : }
5957 : :
5958 [ + + ]: 159624 : if (TransactionIdIsValid(twophase_xid))
5959 : : {
5960 : 274 : xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
5961 : 274 : xl_twophase.xid = twophase_xid;
5962 : : Assert(twophase_gid != NULL);
5963 : :
5964 [ + + - + ]: 274 : if (XLogLogicalInfoActive())
5965 : 43 : xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
5966 : : }
5967 : :
5968 : : /* dump transaction origin information */
5969 [ + + ]: 159624 : if (replorigin_xact_state.origin != InvalidReplOriginId)
5970 : : {
5971 : 1119 : xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
5972 : :
5973 : 1119 : xl_origin.origin_lsn = replorigin_xact_state.origin_lsn;
5974 : 1119 : xl_origin.origin_timestamp = replorigin_xact_state.origin_timestamp;
5975 : : }
5976 : :
5977 [ + + ]: 159624 : if (xl_xinfo.xinfo != 0)
5978 : 115912 : info |= XLOG_XACT_HAS_INFO;
5979 : :
5980 : : /* Then include all the collected data into the commit record. */
5981 : :
5982 : 159624 : XLogBeginInsert();
5983 : :
5984 : 159624 : XLogRegisterData(&xlrec, sizeof(xl_xact_commit));
5985 : :
5986 [ + + ]: 159624 : if (xl_xinfo.xinfo != 0)
5987 : 115912 : XLogRegisterData(&xl_xinfo.xinfo, sizeof(xl_xinfo.xinfo));
5988 : :
5989 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
5990 : 112694 : XLogRegisterData(&xl_dbinfo, sizeof(xl_dbinfo));
5991 : :
5992 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
5993 : : {
5994 : 531 : XLogRegisterData(&xl_subxacts,
5995 : : MinSizeOfXactSubxacts);
5996 : 531 : XLogRegisterData(subxacts,
5997 : : nsubxacts * sizeof(TransactionId));
5998 : : }
5999 : :
6000 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILELOCATORS)
6001 : : {
6002 : 12566 : XLogRegisterData(&xl_relfilelocators,
6003 : : MinSizeOfXactRelfileLocators);
6004 : 12566 : XLogRegisterData(rels,
6005 : : nrels * sizeof(RelFileLocator));
6006 : : }
6007 : :
6008 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DROPPED_STATS)
6009 : : {
6010 : 14988 : XLogRegisterData(&xl_dropped_stats,
6011 : : MinSizeOfXactStatsItems);
6012 : 14988 : XLogRegisterData(droppedstats,
6013 : : ndroppedstats * sizeof(xl_xact_stats_item));
6014 : : }
6015 : :
6016 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_INVALS)
6017 : : {
6018 : 111743 : XLogRegisterData(&xl_invals, MinSizeOfXactInvals);
6019 : 111743 : XLogRegisterData(msgs,
6020 : : nmsgs * sizeof(SharedInvalidationMessage));
6021 : : }
6022 : :
6023 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
6024 : : {
6025 : 274 : XLogRegisterData(&xl_twophase, sizeof(xl_xact_twophase));
6026 [ + + ]: 274 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
6027 : 43 : XLogRegisterData(twophase_gid, strlen(twophase_gid) + 1);
6028 : : }
6029 : :
6030 [ + + ]: 159624 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
6031 : 1119 : XLogRegisterData(&xl_origin, sizeof(xl_xact_origin));
6032 : :
6033 : : /* we allow filtering by xacts */
6034 : 159624 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6035 : :
6036 : 159624 : return XLogInsert(RM_XACT_ID, info);
6037 : : }
6038 : :
6039 : : /*
6040 : : * Log the commit record for a plain or twophase transaction abort.
6041 : : *
6042 : : * A 2pc abort will be emitted when twophase_xid is valid, a plain one
6043 : : * otherwise.
6044 : : */
6045 : : XLogRecPtr
6046 : 9443 : XactLogAbortRecord(TimestampTz abort_time,
6047 : : int nsubxacts, TransactionId *subxacts,
6048 : : int nrels, RelFileLocator *rels,
6049 : : int ndroppedstats, xl_xact_stats_item *droppedstats,
6050 : : int xactflags, TransactionId twophase_xid,
6051 : : const char *twophase_gid)
6052 : : {
6053 : : xl_xact_abort xlrec;
6054 : : xl_xact_xinfo xl_xinfo;
6055 : : xl_xact_subxacts xl_subxacts;
6056 : : xl_xact_relfilelocators xl_relfilelocators;
6057 : : xl_xact_stats_items xl_dropped_stats;
6058 : : xl_xact_twophase xl_twophase;
6059 : : xl_xact_dbinfo xl_dbinfo;
6060 : : xl_xact_origin xl_origin;
6061 : :
6062 : : uint8 info;
6063 : :
6064 : : Assert(CritSectionCount > 0);
6065 : :
6066 : 9443 : xl_xinfo.xinfo = 0;
6067 : :
6068 : : /* decide between a plain and 2pc abort */
6069 [ + + ]: 9443 : if (!TransactionIdIsValid(twophase_xid))
6070 : 9392 : info = XLOG_XACT_ABORT;
6071 : : else
6072 : 51 : info = XLOG_XACT_ABORT_PREPARED;
6073 : :
6074 : :
6075 : : /* First figure out and collect all the information needed */
6076 : :
6077 : 9443 : xlrec.xact_time = abort_time;
6078 : :
6079 [ + + ]: 9443 : if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
6080 : 5161 : xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
6081 : :
6082 [ + + ]: 9443 : if (nsubxacts > 0)
6083 : : {
6084 : 109 : xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
6085 : 109 : xl_subxacts.nsubxacts = nsubxacts;
6086 : : }
6087 : :
6088 [ + + ]: 9443 : if (nrels > 0)
6089 : : {
6090 : 1403 : xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILELOCATORS;
6091 : 1403 : xl_relfilelocators.nrels = nrels;
6092 : 1403 : info |= XLR_SPECIAL_REL_UPDATE;
6093 : : }
6094 : :
6095 [ + + ]: 9443 : if (ndroppedstats > 0)
6096 : : {
6097 : 1999 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DROPPED_STATS;
6098 : 1999 : xl_dropped_stats.nitems = ndroppedstats;
6099 : : }
6100 : :
6101 [ + + ]: 9443 : if (TransactionIdIsValid(twophase_xid))
6102 : : {
6103 : 51 : xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
6104 : 51 : xl_twophase.xid = twophase_xid;
6105 : : Assert(twophase_gid != NULL);
6106 : :
6107 [ + + - + ]: 51 : if (XLogLogicalInfoActive())
6108 : 15 : xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
6109 : : }
6110 : :
6111 [ + + + + : 9443 : if (TransactionIdIsValid(twophase_xid) && XLogLogicalInfoActive())
- + ]
6112 : : {
6113 : 15 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
6114 : 15 : xl_dbinfo.dbId = MyDatabaseId;
6115 : 15 : xl_dbinfo.tsId = MyDatabaseTableSpace;
6116 : : }
6117 : :
6118 : : /*
6119 : : * Dump transaction origin information. We need this during recovery to
6120 : : * update the replication origin progress.
6121 : : */
6122 [ + + ]: 9443 : if (replorigin_xact_state.origin != InvalidReplOriginId)
6123 : : {
6124 : 29 : xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
6125 : :
6126 : 29 : xl_origin.origin_lsn = replorigin_xact_state.origin_lsn;
6127 : 29 : xl_origin.origin_timestamp = replorigin_xact_state.origin_timestamp;
6128 : : }
6129 : :
6130 [ + + ]: 9443 : if (xl_xinfo.xinfo != 0)
6131 : 5418 : info |= XLOG_XACT_HAS_INFO;
6132 : :
6133 : : /* Then include all the collected data into the abort record. */
6134 : :
6135 : 9443 : XLogBeginInsert();
6136 : :
6137 : 9443 : XLogRegisterData(&xlrec, MinSizeOfXactAbort);
6138 : :
6139 [ + + ]: 9443 : if (xl_xinfo.xinfo != 0)
6140 : 5418 : XLogRegisterData(&xl_xinfo, sizeof(xl_xinfo));
6141 : :
6142 [ + + ]: 9443 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
6143 : 15 : XLogRegisterData(&xl_dbinfo, sizeof(xl_dbinfo));
6144 : :
6145 [ + + ]: 9443 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
6146 : : {
6147 : 109 : XLogRegisterData(&xl_subxacts,
6148 : : MinSizeOfXactSubxacts);
6149 : 109 : XLogRegisterData(subxacts,
6150 : : nsubxacts * sizeof(TransactionId));
6151 : : }
6152 : :
6153 [ + + ]: 9443 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILELOCATORS)
6154 : : {
6155 : 1403 : XLogRegisterData(&xl_relfilelocators,
6156 : : MinSizeOfXactRelfileLocators);
6157 : 1403 : XLogRegisterData(rels,
6158 : : nrels * sizeof(RelFileLocator));
6159 : : }
6160 : :
6161 [ + + ]: 9443 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DROPPED_STATS)
6162 : : {
6163 : 1999 : XLogRegisterData(&xl_dropped_stats,
6164 : : MinSizeOfXactStatsItems);
6165 : 1999 : XLogRegisterData(droppedstats,
6166 : : ndroppedstats * sizeof(xl_xact_stats_item));
6167 : : }
6168 : :
6169 [ + + ]: 9443 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
6170 : : {
6171 : 51 : XLogRegisterData(&xl_twophase, sizeof(xl_xact_twophase));
6172 [ + + ]: 51 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
6173 : 15 : XLogRegisterData(twophase_gid, strlen(twophase_gid) + 1);
6174 : : }
6175 : :
6176 [ + + ]: 9443 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
6177 : 29 : XLogRegisterData(&xl_origin, sizeof(xl_xact_origin));
6178 : :
6179 : : /* Include the replication origin */
6180 : 9443 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6181 : :
6182 : 9443 : return XLogInsert(RM_XACT_ID, info);
6183 : : }
6184 : :
6185 : : /*
6186 : : * Before 9.0 this was a fairly short function, but now it performs many
6187 : : * actions for which the order of execution is critical.
6188 : : */
6189 : : static void
6190 : 23997 : xact_redo_commit(xl_xact_parsed_commit *parsed,
6191 : : TransactionId xid,
6192 : : XLogRecPtr lsn,
6193 : : ReplOriginId origin_id)
6194 : : {
6195 : : TransactionId max_xid;
6196 : : TimestampTz commit_time;
6197 : :
6198 : : Assert(TransactionIdIsValid(xid));
6199 : :
6200 : 23997 : max_xid = TransactionIdLatest(xid, parsed->nsubxacts, parsed->subxacts);
6201 : :
6202 : : /* Make sure nextXid is beyond any XID mentioned in the record. */
6203 : 23997 : AdvanceNextFullTransactionIdPastXid(max_xid);
6204 : :
6205 : : Assert(((parsed->xinfo & XACT_XINFO_HAS_ORIGIN) == 0) ==
6206 : : (origin_id == InvalidReplOriginId));
6207 : :
6208 [ + + ]: 23997 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6209 : 20 : commit_time = parsed->origin_timestamp;
6210 : : else
6211 : 23977 : commit_time = parsed->xact_time;
6212 : :
6213 : : /* Set the transaction commit timestamp and metadata */
6214 : 23997 : TransactionTreeSetCommitTsData(xid, parsed->nsubxacts, parsed->subxacts,
6215 : : commit_time, origin_id);
6216 : :
6217 [ + + ]: 23997 : if (standbyState == STANDBY_DISABLED)
6218 : : {
6219 : : /*
6220 : : * Mark the transaction committed in pg_xact.
6221 : : */
6222 : 2225 : TransactionIdCommitTree(xid, parsed->nsubxacts, parsed->subxacts);
6223 : : }
6224 : : else
6225 : : {
6226 : : /*
6227 : : * If a transaction completion record arrives that has as-yet
6228 : : * unobserved subtransactions then this will not have been fully
6229 : : * handled by the call to RecordKnownAssignedTransactionIds() in the
6230 : : * main recovery loop in PerformWalRecovery(). So we need to do
6231 : : * bookkeeping again to cover that case. This is confusing and it is
6232 : : * easy to think this call is irrelevant, which has happened three
6233 : : * times in development already. Leave it in.
6234 : : */
6235 : 21772 : RecordKnownAssignedTransactionIds(max_xid);
6236 : :
6237 : : /*
6238 : : * Mark the transaction committed in pg_xact. We use async commit
6239 : : * protocol during recovery to provide information on database
6240 : : * consistency for when users try to set hint bits. It is important
6241 : : * that we do not set hint bits until the minRecoveryPoint is past
6242 : : * this commit record. This ensures that if we crash we don't see hint
6243 : : * bits set on changes made by transactions that haven't yet
6244 : : * recovered. It's unlikely but it's good to be safe.
6245 : : */
6246 : 21772 : TransactionIdAsyncCommitTree(xid, parsed->nsubxacts, parsed->subxacts, lsn);
6247 : :
6248 : : /*
6249 : : * We must mark clog before we update the ProcArray.
6250 : : */
6251 : 21772 : ExpireTreeKnownAssignedTransactionIds(xid, parsed->nsubxacts, parsed->subxacts, max_xid);
6252 : :
6253 : : /*
6254 : : * Send any cache invalidations attached to the commit. We must
6255 : : * maintain the same order of invalidation then release locks as
6256 : : * occurs in CommitTransaction().
6257 : : */
6258 : 21772 : ProcessCommittedInvalidationMessages(parsed->msgs, parsed->nmsgs,
6259 : 21772 : XactCompletionRelcacheInitFileInval(parsed->xinfo),
6260 : : parsed->dbId, parsed->tsId);
6261 : :
6262 : : /*
6263 : : * Release locks, if any. We do this for both two phase and normal one
6264 : : * phase transactions. In effect we are ignoring the prepare phase and
6265 : : * just going straight to lock release.
6266 : : */
6267 [ + + ]: 21772 : if (parsed->xinfo & XACT_XINFO_HAS_AE_LOCKS)
6268 : 10555 : StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
6269 : : }
6270 : :
6271 [ + + ]: 23997 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6272 : : {
6273 : : /* recover apply progress */
6274 : 20 : replorigin_advance(origin_id, parsed->origin_lsn, lsn,
6275 : : false /* backward */ , false /* WAL */ );
6276 : : }
6277 : :
6278 : : /* Make sure files supposed to be dropped are dropped */
6279 [ + + ]: 23997 : if (parsed->nrels > 0)
6280 : : {
6281 : : /*
6282 : : * First update minimum recovery point to cover this WAL record. Once
6283 : : * a relation is deleted, there's no going back. The buffer manager
6284 : : * enforces the WAL-first rule for normal updates to relation files,
6285 : : * so that the minimum recovery point is always updated before the
6286 : : * corresponding change in the data file is flushed to disk, but we
6287 : : * have to do the same here since we're bypassing the buffer manager.
6288 : : *
6289 : : * Doing this before deleting the files means that if a deletion fails
6290 : : * for some reason, you cannot start up the system even after restart,
6291 : : * until you fix the underlying situation so that the deletion will
6292 : : * succeed. Alternatively, we could update the minimum recovery point
6293 : : * after deletion, but that would leave a small window where the
6294 : : * WAL-first rule would be violated.
6295 : : */
6296 : 2257 : XLogFlush(lsn);
6297 : :
6298 : : /* Make sure files supposed to be dropped are dropped */
6299 : 2257 : DropRelationFiles(parsed->xlocators, parsed->nrels, true);
6300 : : }
6301 : :
6302 [ + + ]: 23997 : if (parsed->nstats > 0)
6303 : : {
6304 : : /* see equivalent call for relations above */
6305 : 2962 : XLogFlush(lsn);
6306 : :
6307 : 2962 : pgstat_execute_transactional_drops(parsed->nstats, parsed->stats, true);
6308 : : }
6309 : :
6310 : : /*
6311 : : * We issue an XLogFlush() for the same reason we emit ForceSyncCommit()
6312 : : * in normal operation. For example, in CREATE DATABASE, we copy all files
6313 : : * from the template database, and then commit the transaction. If we
6314 : : * crash after all the files have been copied but before the commit, you
6315 : : * have files in the data directory without an entry in pg_database. To
6316 : : * minimize the window for that, we use ForceSyncCommit() to rush the
6317 : : * commit record to disk as quick as possible. We have the same window
6318 : : * during recovery, and forcing an XLogFlush() (which updates
6319 : : * minRecoveryPoint during recovery) helps to reduce that problem window,
6320 : : * for any user that requested ForceSyncCommit().
6321 : : */
6322 [ + + ]: 23997 : if (XactCompletionForceSyncCommit(parsed->xinfo))
6323 : 51 : XLogFlush(lsn);
6324 : :
6325 : : /*
6326 : : * If asked by the primary (because someone is waiting for a synchronous
6327 : : * commit = remote_apply), we will need to ask walreceiver to send a reply
6328 : : * immediately.
6329 : : */
6330 [ + + ]: 23997 : if (XactCompletionApplyFeedback(parsed->xinfo))
6331 : 2 : XLogRequestWalReceiverReply();
6332 : 23997 : }
6333 : :
6334 : : /*
6335 : : * Be careful with the order of execution, as with xact_redo_commit().
6336 : : * The two functions are similar but differ in key places.
6337 : : *
6338 : : * Note also that an abort can be for a subtransaction and its children,
6339 : : * not just for a top level abort. That means we have to consider
6340 : : * topxid != xid, whereas in commit we would find topxid == xid always
6341 : : * because subtransaction commit is never WAL logged.
6342 : : */
6343 : : static void
6344 : 2012 : xact_redo_abort(xl_xact_parsed_abort *parsed, TransactionId xid,
6345 : : XLogRecPtr lsn, ReplOriginId origin_id)
6346 : : {
6347 : : TransactionId max_xid;
6348 : :
6349 : : Assert(TransactionIdIsValid(xid));
6350 : :
6351 : : /* Make sure nextXid is beyond any XID mentioned in the record. */
6352 : 2012 : max_xid = TransactionIdLatest(xid,
6353 : : parsed->nsubxacts,
6354 : 2012 : parsed->subxacts);
6355 : 2012 : AdvanceNextFullTransactionIdPastXid(max_xid);
6356 : :
6357 [ + + ]: 2012 : if (standbyState == STANDBY_DISABLED)
6358 : : {
6359 : : /* Mark the transaction aborted in pg_xact, no need for async stuff */
6360 : 20 : TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
6361 : : }
6362 : : else
6363 : : {
6364 : : /*
6365 : : * If a transaction completion record arrives that has as-yet
6366 : : * unobserved subtransactions then this will not have been fully
6367 : : * handled by the call to RecordKnownAssignedTransactionIds() in the
6368 : : * main recovery loop in PerformWalRecovery(). So we need to do
6369 : : * bookkeeping again to cover that case. This is confusing and it is
6370 : : * easy to think this call is irrelevant, which has happened three
6371 : : * times in development already. Leave it in.
6372 : : */
6373 : 1992 : RecordKnownAssignedTransactionIds(max_xid);
6374 : :
6375 : : /* Mark the transaction aborted in pg_xact, no need for async stuff */
6376 : 1992 : TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
6377 : :
6378 : : /*
6379 : : * We must update the ProcArray after we have marked clog.
6380 : : */
6381 : 1992 : ExpireTreeKnownAssignedTransactionIds(xid, parsed->nsubxacts, parsed->subxacts, max_xid);
6382 : :
6383 : : /*
6384 : : * There are no invalidation messages to send or undo.
6385 : : */
6386 : :
6387 : : /*
6388 : : * Release locks, if any. There are no invalidations to send.
6389 : : */
6390 [ + + ]: 1992 : if (parsed->xinfo & XACT_XINFO_HAS_AE_LOCKS)
6391 : 1238 : StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
6392 : : }
6393 : :
6394 [ + + ]: 2012 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6395 : : {
6396 : : /* recover apply progress */
6397 : 5 : replorigin_advance(origin_id, parsed->origin_lsn, lsn,
6398 : : false /* backward */ , false /* WAL */ );
6399 : : }
6400 : :
6401 : : /* Make sure files supposed to be dropped are dropped */
6402 [ + + ]: 2012 : if (parsed->nrels > 0)
6403 : : {
6404 : : /*
6405 : : * See comments about update of minimum recovery point on truncation,
6406 : : * in xact_redo_commit().
6407 : : */
6408 : 337 : XLogFlush(lsn);
6409 : :
6410 : 337 : DropRelationFiles(parsed->xlocators, parsed->nrels, true);
6411 : : }
6412 : :
6413 [ + + ]: 2012 : if (parsed->nstats > 0)
6414 : : {
6415 : : /* see equivalent call for relations above */
6416 : 468 : XLogFlush(lsn);
6417 : :
6418 : 468 : pgstat_execute_transactional_drops(parsed->nstats, parsed->stats, true);
6419 : : }
6420 : 2012 : }
6421 : :
6422 : : void
6423 : 26394 : xact_redo(XLogReaderState *record)
6424 : : {
6425 : 26394 : uint8 info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
6426 : :
6427 : : /* Backup blocks are not used in xact records */
6428 : : Assert(!XLogRecHasAnyBlockRefs(record));
6429 : :
6430 [ + + ]: 26394 : if (info == XLOG_XACT_COMMIT)
6431 : : {
6432 : 23951 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
6433 : : xl_xact_parsed_commit parsed;
6434 : :
6435 : 23951 : ParseCommitRecord(XLogRecGetInfo(record), xlrec, &parsed);
6436 : 23951 : xact_redo_commit(&parsed, XLogRecGetXid(record),
6437 : 23951 : record->EndRecPtr, XLogRecGetOrigin(record));
6438 : : }
6439 [ + + ]: 2443 : else if (info == XLOG_XACT_COMMIT_PREPARED)
6440 : : {
6441 : 46 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
6442 : : xl_xact_parsed_commit parsed;
6443 : :
6444 : 46 : ParseCommitRecord(XLogRecGetInfo(record), xlrec, &parsed);
6445 : 46 : xact_redo_commit(&parsed, parsed.twophase_xid,
6446 : 46 : record->EndRecPtr, XLogRecGetOrigin(record));
6447 : :
6448 : : /* Delete TwoPhaseState gxact entry and/or 2PC file. */
6449 : 46 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6450 : 46 : PrepareRedoRemove(parsed.twophase_xid, false);
6451 : 46 : LWLockRelease(TwoPhaseStateLock);
6452 : : }
6453 [ + + ]: 2397 : else if (info == XLOG_XACT_ABORT)
6454 : : {
6455 : 1987 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
6456 : : xl_xact_parsed_abort parsed;
6457 : :
6458 : 1987 : ParseAbortRecord(XLogRecGetInfo(record), xlrec, &parsed);
6459 : 1987 : xact_redo_abort(&parsed, XLogRecGetXid(record),
6460 : 1987 : record->EndRecPtr, XLogRecGetOrigin(record));
6461 : : }
6462 [ + + ]: 410 : else if (info == XLOG_XACT_ABORT_PREPARED)
6463 : : {
6464 : 25 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
6465 : : xl_xact_parsed_abort parsed;
6466 : :
6467 : 25 : ParseAbortRecord(XLogRecGetInfo(record), xlrec, &parsed);
6468 : 25 : xact_redo_abort(&parsed, parsed.twophase_xid,
6469 : 25 : record->EndRecPtr, XLogRecGetOrigin(record));
6470 : :
6471 : : /* Delete TwoPhaseState gxact entry and/or 2PC file. */
6472 : 25 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6473 : 25 : PrepareRedoRemove(parsed.twophase_xid, false);
6474 : 25 : LWLockRelease(TwoPhaseStateLock);
6475 : : }
6476 [ + + ]: 385 : else if (info == XLOG_XACT_PREPARE)
6477 : : {
6478 : : /*
6479 : : * Store xid and start/end pointers of the WAL record in TwoPhaseState
6480 : : * gxact entry.
6481 : : */
6482 : 81 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6483 : 81 : PrepareRedoAdd(InvalidFullTransactionId,
6484 : 81 : XLogRecGetData(record),
6485 : : record->ReadRecPtr,
6486 : : record->EndRecPtr,
6487 : 81 : XLogRecGetOrigin(record));
6488 : 81 : LWLockRelease(TwoPhaseStateLock);
6489 : : }
6490 [ + + ]: 304 : else if (info == XLOG_XACT_ASSIGNMENT)
6491 : : {
6492 : 22 : xl_xact_assignment *xlrec = (xl_xact_assignment *) XLogRecGetData(record);
6493 : :
6494 [ + - ]: 22 : if (standbyState >= STANDBY_INITIALIZED)
6495 : 22 : ProcArrayApplyXidAssignment(xlrec->xtop,
6496 : 22 : xlrec->nsubxacts, xlrec->xsub);
6497 : : }
6498 [ - + ]: 282 : else if (info == XLOG_XACT_INVALIDATIONS)
6499 : : {
6500 : : /*
6501 : : * XXX we do ignore this for now, what matters are invalidations
6502 : : * written into the commit record.
6503 : : */
6504 : : }
6505 : : else
6506 [ # # ]: 0 : elog(PANIC, "xact_redo: unknown op code %u", info);
6507 : 26394 : }
|