PostgreSQL Source Code  git master
xact.c
Go to the documentation of this file.
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-2020, 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/xlogutils.h"
33 #include "catalog/index.h"
34 #include "catalog/namespace.h"
35 #include "catalog/pg_enum.h"
36 #include "catalog/storage.h"
37 #include "commands/async.h"
38 #include "commands/tablecmds.h"
39 #include "commands/trigger.h"
40 #include "executor/spi.h"
41 #include "libpq/be-fsstubs.h"
42 #include "libpq/pqsignal.h"
43 #include "miscadmin.h"
44 #include "pg_trace.h"
45 #include "pgstat.h"
46 #include "replication/logical.h"
48 #include "replication/origin.h"
49 #include "replication/syncrep.h"
50 #include "replication/walsender.h"
52 #include "storage/fd.h"
53 #include "storage/lmgr.h"
54 #include "storage/md.h"
55 #include "storage/predicate.h"
56 #include "storage/proc.h"
57 #include "storage/procarray.h"
58 #include "storage/sinvaladt.h"
59 #include "storage/smgr.h"
60 #include "utils/builtins.h"
61 #include "utils/catcache.h"
62 #include "utils/combocid.h"
63 #include "utils/guc.h"
64 #include "utils/inval.h"
65 #include "utils/memutils.h"
66 #include "utils/relmapper.h"
67 #include "utils/snapmgr.h"
68 #include "utils/timeout.h"
69 #include "utils/timestamp.h"
70 
71 /*
72  * User-tweakable parameters
73  */
76 
77 bool DefaultXactReadOnly = false;
79 
80 bool DefaultXactDeferrable = false;
82 
84 
85 /*
86  * When running as a parallel worker, we place only a single
87  * TransactionStateData on the parallel worker's state stack, and the XID
88  * reflected there will be that of the *innermost* currently-active
89  * subtransaction in the backend that initiated parallelism. However,
90  * GetTopTransactionId() and TransactionIdIsCurrentTransactionId()
91  * need to return the same answers in the parallel worker as they would have
92  * in the user backend, so we need some additional bookkeeping.
93  *
94  * XactTopFullTransactionId stores the XID of our toplevel transaction, which
95  * will be the same as TopTransactionStateData.fullTransactionId in an
96  * ordinary backend; but in a parallel backend, which does not have the entire
97  * transaction state, it will instead be copied from the backend that started
98  * the parallel operation.
99  *
100  * nParallelCurrentXids will be 0 and ParallelCurrentXids NULL in an ordinary
101  * backend, but in a parallel backend, nParallelCurrentXids will contain the
102  * number of XIDs that need to be considered current, and ParallelCurrentXids
103  * will contain the XIDs themselves. This includes all XIDs that were current
104  * or sub-committed in the parent at the time the parallel operation began.
105  * The XIDs are stored sorted in numerical order (not logical order) to make
106  * lookups as fast as possible.
107  */
111 
112 /*
113  * Miscellaneous flag bits to record events which occur on the top level
114  * transaction. These flags are only persisted in MyXactFlags and are intended
115  * so we remember to do certain things later on in the transaction. This is
116  * globally accessible, so can be set from anywhere in the code that requires
117  * recording flags.
118  */
120 
121 /*
122  * transaction states - transaction state from server perspective
123  */
124 typedef enum TransState
125 {
126  TRANS_DEFAULT, /* idle */
127  TRANS_START, /* transaction starting */
128  TRANS_INPROGRESS, /* inside a valid transaction */
129  TRANS_COMMIT, /* commit in progress */
130  TRANS_ABORT, /* abort in progress */
131  TRANS_PREPARE /* prepare in progress */
132 } TransState;
133 
134 /*
135  * transaction block states - transaction state of client queries
136  *
137  * Note: the subtransaction states are used only for non-topmost
138  * transactions; the others appear only in the topmost transaction.
139  */
140 typedef enum TBlockState
141 {
142  /* not-in-transaction-block states */
143  TBLOCK_DEFAULT, /* idle */
144  TBLOCK_STARTED, /* running single-query transaction */
145 
146  /* transaction block states */
147  TBLOCK_BEGIN, /* starting transaction block */
148  TBLOCK_INPROGRESS, /* live transaction */
149  TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
150  TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
151  TBLOCK_END, /* COMMIT received */
152  TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
153  TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
154  TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
155  TBLOCK_PREPARE, /* live xact, PREPARE received */
156 
157  /* subtransaction states */
158  TBLOCK_SUBBEGIN, /* starting a subtransaction */
159  TBLOCK_SUBINPROGRESS, /* live subtransaction */
160  TBLOCK_SUBRELEASE, /* RELEASE received */
161  TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
162  TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
163  TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
164  TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
165  TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
166  TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
167 } TBlockState;
168 
169 /*
170  * transaction state structure
171  */
172 typedef struct TransactionStateData
173 {
174  FullTransactionId fullTransactionId; /* my FullTransactionId */
175  SubTransactionId subTransactionId; /* my subxact ID */
176  char *name; /* savepoint name, if any */
177  int savepointLevel; /* savepoint level */
178  TransState state; /* low-level state */
179  TBlockState blockState; /* high-level state */
180  int nestingLevel; /* transaction nesting depth */
181  int gucNestLevel; /* GUC context nesting depth */
182  MemoryContext curTransactionContext; /* my xact-lifetime context */
183  ResourceOwner curTransactionOwner; /* my query resources */
184  TransactionId *childXids; /* subcommitted child XIDs, in XID order */
185  int nChildXids; /* # of subcommitted child XIDs */
186  int maxChildXids; /* allocated size of childXids[] */
187  Oid prevUser; /* previous CurrentUserId setting */
188  int prevSecContext; /* previous SecurityRestrictionContext */
189  bool prevXactReadOnly; /* entry-time xact r/o state */
190  bool startedInRecovery; /* did we start in recovery? */
191  bool didLogXid; /* has xid been included in WAL record? */
192  int parallelModeLevel; /* Enter/ExitParallelMode counter */
193  bool chain; /* start a new block after this one */
194  bool assigned; /* assigned to top-level XID */
195  struct TransactionStateData *parent; /* back link to parent */
197 
199 
200 /*
201  * Serialized representation used to transmit transaction state to parallel
202  * workers through shared memory.
203  */
205 {
212  TransactionId parallelCurrentXids[FLEXIBLE_ARRAY_MEMBER];
214 
215 /* The size of SerializedTransactionState, not including the final array. */
216 #define SerializedTransactionStateHeaderSize \
217  offsetof(SerializedTransactionState, parallelCurrentXids)
218 
219 /*
220  * CurrentTransactionState always points to the current transaction state
221  * block. It will point to TopTransactionStateData when not in a
222  * transaction at all, or when in a top-level transaction.
223  */
225  .state = TRANS_DEFAULT,
226  .blockState = TBLOCK_DEFAULT,
227  .assigned = false,
228 };
229 
230 /*
231  * unreportedXids holds XIDs of all subtransactions that have not yet been
232  * reported in an XLOG_XACT_ASSIGNMENT record.
233  */
234 static int nUnreportedXids;
236 
238 
239 /*
240  * The subtransaction ID and command ID assignment counters are global
241  * to a whole transaction, so we do not keep them in the state stack.
242  */
246 
247 /*
248  * xactStartTimestamp is the value of transaction_timestamp().
249  * stmtStartTimestamp is the value of statement_timestamp().
250  * xactStopTimestamp is the time at which we log a commit or abort WAL record.
251  * These do not change as we enter and exit subtransactions, so we don't
252  * keep them inside the TransactionState stack.
253  */
257 
258 /*
259  * GID to be used for preparing the current transaction. This is also
260  * global to a whole transaction, so we don't keep it in the state stack.
261  */
262 static char *prepareGID;
263 
264 /*
265  * Some commands want to force synchronous commit.
266  */
267 static bool forceSyncCommit = false;
268 
269 /* Flag for logging statements in a transaction. */
270 bool xact_is_sampled = false;
271 
272 /*
273  * Private context for transaction-abort work --- we reserve space for this
274  * at startup to ensure that AbortTransaction and AbortSubTransaction can work
275  * when we've run out of memory.
276  */
278 
279 /*
280  * List of add-on start- and end-of-xact callbacks
281  */
282 typedef struct XactCallbackItem
283 {
286  void *arg;
288 
290 
291 /*
292  * List of add-on start- and end-of-subxact callbacks
293  */
294 typedef struct SubXactCallbackItem
295 {
298  void *arg;
300 
302 
303 
304 /* local function prototypes */
306 static void AbortTransaction(void);
307 static void AtAbort_Memory(void);
308 static void AtCleanup_Memory(void);
309 static void AtAbort_ResourceOwner(void);
310 static void AtCCI_LocalCache(void);
311 static void AtCommit_Memory(void);
312 static void AtStart_Cache(void);
313 static void AtStart_Memory(void);
314 static void AtStart_ResourceOwner(void);
315 static void CallXactCallbacks(XactEvent event);
316 static void CallSubXactCallbacks(SubXactEvent event,
317  SubTransactionId mySubid,
318  SubTransactionId parentSubid);
319 static void CleanupTransaction(void);
320 static void CheckTransactionBlock(bool isTopLevel, bool throwError,
321  const char *stmtType);
322 static void CommitTransaction(void);
323 static TransactionId RecordTransactionAbort(bool isSubXact);
324 static void StartTransaction(void);
325 
326 static void StartSubTransaction(void);
327 static void CommitSubTransaction(void);
328 static void AbortSubTransaction(void);
329 static void CleanupSubTransaction(void);
330 static void PushTransaction(void);
331 static void PopTransaction(void);
332 
333 static void AtSubAbort_Memory(void);
334 static void AtSubCleanup_Memory(void);
335 static void AtSubAbort_ResourceOwner(void);
336 static void AtSubCommit_Memory(void);
337 static void AtSubStart_Memory(void);
338 static void AtSubStart_ResourceOwner(void);
339 
340 static void ShowTransactionState(const char *str);
341 static void ShowTransactionStateRec(const char *str, TransactionState state);
342 static const char *BlockStateAsString(TBlockState blockState);
343 static const char *TransStateAsString(TransState state);
344 
345 
346 /* ----------------------------------------------------------------
347  * transaction state accessors
348  * ----------------------------------------------------------------
349  */
350 
351 /*
352  * IsTransactionState
353  *
354  * This returns true if we are inside a valid transaction; that is,
355  * it is safe to initiate database access, take heavyweight locks, etc.
356  */
357 bool
359 {
361 
362  /*
363  * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
364  * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
365  * TRANS_PREPARE since it might be too soon or too late within those
366  * transition states to do anything interesting. Hence, the only "valid"
367  * state is TRANS_INPROGRESS.
368  */
369  return (s->state == TRANS_INPROGRESS);
370 }
371 
372 /*
373  * IsAbortedTransactionBlockState
374  *
375  * This returns true if we are within an aborted transaction block.
376  */
377 bool
379 {
381 
382  if (s->blockState == TBLOCK_ABORT ||
384  return true;
385 
386  return false;
387 }
388 
389 
390 /*
391  * GetTopTransactionId
392  *
393  * This will return the XID of the main transaction, assigning one if
394  * it's not yet set. Be careful to call this only inside a valid xact.
395  */
398 {
399  if (!FullTransactionIdIsValid(XactTopFullTransactionId))
400  AssignTransactionId(&TopTransactionStateData);
401  return XidFromFullTransactionId(XactTopFullTransactionId);
402 }
403 
404 /*
405  * GetTopTransactionIdIfAny
406  *
407  * This will return the XID of the main transaction, if one is assigned.
408  * It will return InvalidTransactionId if we are not currently inside a
409  * transaction, or inside a transaction that hasn't yet been assigned an XID.
410  */
413 {
414  return XidFromFullTransactionId(XactTopFullTransactionId);
415 }
416 
417 /*
418  * GetCurrentTransactionId
419  *
420  * This will return the XID of the current transaction (main or sub
421  * transaction), assigning one if it's not yet set. Be careful to call this
422  * only inside a valid xact.
423  */
426 {
428 
432 }
433 
434 /*
435  * GetCurrentTransactionIdIfAny
436  *
437  * This will return the XID of the current sub xact, if one is assigned.
438  * It will return InvalidTransactionId if we are not currently inside a
439  * transaction, or inside a transaction that hasn't been assigned an XID yet.
440  */
443 {
444  return XidFromFullTransactionId(CurrentTransactionState->fullTransactionId);
445 }
446 
447 /*
448  * GetTopFullTransactionId
449  *
450  * This will return the FullTransactionId of the main transaction, assigning
451  * one if it's not yet set. Be careful to call this only inside a valid xact.
452  */
455 {
456  if (!FullTransactionIdIsValid(XactTopFullTransactionId))
457  AssignTransactionId(&TopTransactionStateData);
459 }
460 
461 /*
462  * GetTopFullTransactionIdIfAny
463  *
464  * This will return the FullTransactionId of the main transaction, if one is
465  * assigned. It will return InvalidFullTransactionId if we are not currently
466  * inside a transaction, or inside a transaction that hasn't yet been assigned
467  * one.
468  */
471 {
473 }
474 
475 /*
476  * GetCurrentFullTransactionId
477  *
478  * This will return the FullTransactionId of the current transaction (main or
479  * sub transaction), assigning one if it's not yet set. Be careful to call
480  * this only inside a valid xact.
481  */
484 {
486 
489  return s->fullTransactionId;
490 }
491 
492 /*
493  * GetCurrentFullTransactionIdIfAny
494  *
495  * This will return the FullTransactionId of the current sub xact, 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 been assigned one
498  * yet.
499  */
502 {
503  return CurrentTransactionState->fullTransactionId;
504 }
505 
506 /*
507  * MarkCurrentTransactionIdLoggedIfAny
508  *
509  * Remember that the current xid - if it is assigned - now has been wal logged.
510  */
511 void
513 {
514  if (FullTransactionIdIsValid(CurrentTransactionState->fullTransactionId))
515  CurrentTransactionState->didLogXid = true;
516 }
517 
518 
519 /*
520  * GetStableLatestTransactionId
521  *
522  * Get the transaction's XID if it has one, else read the next-to-be-assigned
523  * XID. Once we have a value, return that same value for the remainder of the
524  * current transaction. This is meant to provide the reference point for the
525  * age(xid) function, but might be useful for other maintenance tasks as well.
526  */
529 {
531  static TransactionId stablexid = InvalidTransactionId;
532 
533  if (lxid != MyProc->lxid)
534  {
535  lxid = MyProc->lxid;
536  stablexid = GetTopTransactionIdIfAny();
537  if (!TransactionIdIsValid(stablexid))
538  stablexid = ReadNewTransactionId();
539  }
540 
541  Assert(TransactionIdIsValid(stablexid));
542 
543  return stablexid;
544 }
545 
546 /*
547  * AssignTransactionId
548  *
549  * Assigns a new permanent FullTransactionId to the given TransactionState.
550  * We do not assign XIDs to transactions until/unless this is called.
551  * Also, any parent TransactionStates that don't yet have XIDs are assigned
552  * one; this maintains the invariant that a child transaction has an XID
553  * following its parent's.
554  */
555 static void
557 {
558  bool isSubXact = (s->parent != NULL);
559  ResourceOwner currentOwner;
560  bool log_unknown_top = false;
561 
562  /* Assert that caller didn't screw up */
565 
566  /*
567  * Workers synchronize transaction state at the beginning of each parallel
568  * operation, so we can't account for new XIDs at this point.
569  */
571  elog(ERROR, "cannot assign XIDs during a parallel operation");
572 
573  /*
574  * Ensure parent(s) have XIDs, so that a child always has an XID later
575  * than its parent. Mustn't recurse here, or we might get a stack
576  * overflow if we're at the bottom of a huge stack of subtransactions none
577  * of which have XIDs yet.
578  */
579  if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
580  {
581  TransactionState p = s->parent;
582  TransactionState *parents;
583  size_t parentOffset = 0;
584 
585  parents = palloc(sizeof(TransactionState) * s->nestingLevel);
586  while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
587  {
588  parents[parentOffset++] = p;
589  p = p->parent;
590  }
591 
592  /*
593  * This is technically a recursive call, but the recursion will never
594  * be more than one layer deep.
595  */
596  while (parentOffset != 0)
597  AssignTransactionId(parents[--parentOffset]);
598 
599  pfree(parents);
600  }
601 
602  /*
603  * When wal_level=logical, guarantee that a subtransaction's xid can only
604  * be seen in the WAL stream if its toplevel xid has been logged before.
605  * If necessary we log an xact_assignment record with fewer than
606  * PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't set
607  * for a transaction even though it appears in a WAL record, we just might
608  * superfluously log something. That can happen when an xid is included
609  * somewhere inside a wal record, but not in XLogRecord->xl_xid, like in
610  * xl_standby_locks.
611  */
612  if (isSubXact && XLogLogicalInfoActive() &&
613  !TopTransactionStateData.didLogXid)
614  log_unknown_top = true;
615 
616  /*
617  * Generate a new FullTransactionId and record its xid in PG_PROC and
618  * pg_subtrans.
619  *
620  * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
621  * shared storage other than PG_PROC; because if there's no room for it in
622  * PG_PROC, the subtrans entry is needed to ensure that other backends see
623  * the Xid as "running". See GetNewTransactionId.
624  */
625  s->fullTransactionId = GetNewTransactionId(isSubXact);
626  if (!isSubXact)
627  XactTopFullTransactionId = s->fullTransactionId;
628 
629  if (isSubXact)
632 
633  /*
634  * If it's a top-level transaction, the predicate locking system needs to
635  * be told about it too.
636  */
637  if (!isSubXact)
639 
640  /*
641  * Acquire lock on the transaction XID. (We assume this cannot block.) We
642  * have to ensure that the lock is assigned to the transaction's own
643  * ResourceOwner.
644  */
645  currentOwner = CurrentResourceOwner;
647 
649 
650  CurrentResourceOwner = currentOwner;
651 
652  /*
653  * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
654  * top-level transaction we issue a WAL record for the assignment. We
655  * include the top-level xid and all the subxids that have not yet been
656  * reported using XLOG_XACT_ASSIGNMENT records.
657  *
658  * This is required to limit the amount of shared memory required in a hot
659  * standby server to keep track of in-progress XIDs. See notes for
660  * RecordKnownAssignedTransactionIds().
661  *
662  * We don't keep track of the immediate parent of each subxid, only the
663  * top-level transaction that each subxact belongs to. This is correct in
664  * recovery only because aborted subtransactions are separately WAL
665  * logged.
666  *
667  * This is correct even for the case where several levels above us didn't
668  * have an xid assigned as we recursed up to them beforehand.
669  */
670  if (isSubXact && XLogStandbyInfoActive())
671  {
673  nUnreportedXids++;
674 
675  /*
676  * ensure this test matches similar one in
677  * RecoverPreparedTransactions()
678  */
680  log_unknown_top)
681  {
682  xl_xact_assignment xlrec;
683 
684  /*
685  * xtop is always set by now because we recurse up transaction
686  * stack to the highest unassigned xid and then come back down
687  */
688  xlrec.xtop = GetTopTransactionId();
690  xlrec.nsubxacts = nUnreportedXids;
691 
692  XLogBeginInsert();
693  XLogRegisterData((char *) &xlrec, MinSizeOfXactAssignment);
695  nUnreportedXids * sizeof(TransactionId));
696 
697  (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
698 
699  nUnreportedXids = 0;
700  /* mark top, not current xact as having been logged */
701  TopTransactionStateData.didLogXid = true;
702  }
703  }
704 }
705 
706 /*
707  * GetCurrentSubTransactionId
708  */
711 {
713 
714  return s->subTransactionId;
715 }
716 
717 /*
718  * SubTransactionIsActive
719  *
720  * Test if the specified subxact ID is still active. Note caller is
721  * responsible for checking whether this ID is relevant to the current xact.
722  */
723 bool
725 {
727 
728  for (s = CurrentTransactionState; s != NULL; s = s->parent)
729  {
730  if (s->state == TRANS_ABORT)
731  continue;
732  if (s->subTransactionId == subxid)
733  return true;
734  }
735  return false;
736 }
737 
738 
739 /*
740  * GetCurrentCommandId
741  *
742  * "used" must be true if the caller intends to use the command ID to mark
743  * inserted/updated/deleted tuples. false means the ID is being fetched
744  * for read-only purposes (ie, as a snapshot validity cutoff). See
745  * CommandCounterIncrement() for discussion.
746  */
747 CommandId
749 {
750  /* this is global to a transaction, not subtransaction-local */
751  if (used)
752  {
753  /*
754  * Forbid setting currentCommandIdUsed in a parallel worker, because
755  * we have no provision for communicating this back to the leader. We
756  * could relax this restriction when currentCommandIdUsed was already
757  * true at the start of the parallel operation.
758  */
760  currentCommandIdUsed = true;
761  }
762  return currentCommandId;
763 }
764 
765 /*
766  * SetParallelStartTimestamps
767  *
768  * In a parallel worker, we should inherit the parent transaction's
769  * timestamps rather than setting our own. The parallel worker
770  * infrastructure must call this to provide those values before
771  * calling StartTransaction() or SetCurrentStatementStartTimestamp().
772  */
773 void
775 {
777  xactStartTimestamp = xact_ts;
778  stmtStartTimestamp = stmt_ts;
779 }
780 
781 /*
782  * GetCurrentTransactionStartTimestamp
783  */
786 {
787  return xactStartTimestamp;
788 }
789 
790 /*
791  * GetCurrentStatementStartTimestamp
792  */
795 {
796  return stmtStartTimestamp;
797 }
798 
799 /*
800  * GetCurrentTransactionStopTimestamp
801  *
802  * We return current time if the transaction stop time hasn't been set
803  * (which can happen if we decide we don't need to log an XLOG record).
804  */
807 {
808  if (xactStopTimestamp != 0)
809  return xactStopTimestamp;
810  return GetCurrentTimestamp();
811 }
812 
813 /*
814  * SetCurrentStatementStartTimestamp
815  *
816  * In a parallel worker, this should already have been provided by a call
817  * to SetParallelStartTimestamps().
818  */
819 void
821 {
822  if (!IsParallelWorker())
824  else
826 }
827 
828 /*
829  * SetCurrentTransactionStopTimestamp
830  */
831 static inline void
833 {
835 }
836 
837 /*
838  * GetCurrentTransactionNestLevel
839  *
840  * Note: this will return zero when not inside any transaction, one when
841  * inside a top-level transaction, etc.
842  */
843 int
845 {
847 
848  return s->nestingLevel;
849 }
850 
851 
852 /*
853  * TransactionIdIsCurrentTransactionId
854  */
855 bool
857 {
859 
860  /*
861  * We always say that BootstrapTransactionId is "not my transaction ID"
862  * even when it is (ie, during bootstrap). Along with the fact that
863  * transam.c always treats BootstrapTransactionId as already committed,
864  * this causes the heapam_visibility.c routines to see all tuples as
865  * committed, which is what we need during bootstrap. (Bootstrap mode
866  * only inserts tuples, it never updates or deletes them, so all tuples
867  * can be presumed good immediately.)
868  *
869  * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
870  * not my transaction ID, so we can just return "false" immediately for
871  * any non-normal XID.
872  */
873  if (!TransactionIdIsNormal(xid))
874  return false;
875 
877  return true;
878 
879  /*
880  * In parallel workers, the XIDs we must consider as current are stored in
881  * ParallelCurrentXids rather than the transaction-state stack. Note that
882  * the XIDs in this array are sorted numerically rather than according to
883  * transactionIdPrecedes order.
884  */
885  if (nParallelCurrentXids > 0)
886  {
887  int low,
888  high;
889 
890  low = 0;
891  high = nParallelCurrentXids - 1;
892  while (low <= high)
893  {
894  int middle;
895  TransactionId probe;
896 
897  middle = low + (high - low) / 2;
898  probe = ParallelCurrentXids[middle];
899  if (probe == xid)
900  return true;
901  else if (probe < xid)
902  low = middle + 1;
903  else
904  high = middle - 1;
905  }
906  return false;
907  }
908 
909  /*
910  * We will return true for the Xid of the current subtransaction, any of
911  * its subcommitted children, any of its parents, or any of their
912  * previously subcommitted children. However, a transaction being aborted
913  * is no longer "current", even though it may still have an entry on the
914  * state stack.
915  */
916  for (s = CurrentTransactionState; s != NULL; s = s->parent)
917  {
918  int low,
919  high;
920 
921  if (s->state == TRANS_ABORT)
922  continue;
924  continue; /* it can't have any child XIDs either */
926  return true;
927  /* As the childXids array is ordered, we can use binary search */
928  low = 0;
929  high = s->nChildXids - 1;
930  while (low <= high)
931  {
932  int middle;
933  TransactionId probe;
934 
935  middle = low + (high - low) / 2;
936  probe = s->childXids[middle];
937  if (TransactionIdEquals(probe, xid))
938  return true;
939  else if (TransactionIdPrecedes(probe, xid))
940  low = middle + 1;
941  else
942  high = middle - 1;
943  }
944  }
945 
946  return false;
947 }
948 
949 /*
950  * TransactionStartedDuringRecovery
951  *
952  * Returns true if the current transaction started while recovery was still
953  * in progress. Recovery might have ended since so RecoveryInProgress() might
954  * return false already.
955  */
956 bool
958 {
959  return CurrentTransactionState->startedInRecovery;
960 }
961 
962 /*
963  * EnterParallelMode
964  */
965 void
967 {
969 
970  Assert(s->parallelModeLevel >= 0);
971 
972  ++s->parallelModeLevel;
973 }
974 
975 /*
976  * ExitParallelMode
977  */
978 void
980 {
982 
983  Assert(s->parallelModeLevel > 0);
985 
986  --s->parallelModeLevel;
987 }
988 
989 /*
990  * IsInParallelMode
991  *
992  * Are we in a parallel operation, as either the leader or a worker? Check
993  * this to prohibit operations that change backend-local state expected to
994  * match across all workers. Mere caches usually don't require such a
995  * restriction. State modified in a strict push/pop fashion, such as the
996  * active snapshot stack, is often fine.
997  */
998 bool
1000 {
1001  return CurrentTransactionState->parallelModeLevel != 0;
1002 }
1003 
1004 /*
1005  * CommandCounterIncrement
1006  */
1007 void
1009 {
1010  /*
1011  * If the current value of the command counter hasn't been "used" to mark
1012  * tuples, we need not increment it, since there's no need to distinguish
1013  * a read-only command from others. This helps postpone command counter
1014  * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1015  */
1017  {
1018  /*
1019  * Workers synchronize transaction state at the beginning of each
1020  * parallel operation, so we can't account for new commands after that
1021  * point.
1022  */
1024  elog(ERROR, "cannot start commands during a parallel operation");
1025 
1026  currentCommandId += 1;
1028  {
1029  currentCommandId -= 1;
1030  ereport(ERROR,
1031  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1032  errmsg("cannot have more than 2^32-2 commands in a transaction")));
1033  }
1034  currentCommandIdUsed = false;
1035 
1036  /* Propagate new command ID into static snapshots */
1038 
1039  /*
1040  * Make any catalog changes done by the just-completed command visible
1041  * in the local syscache. We obviously don't need to do this after a
1042  * read-only command. (But see hacks in inval.c to make real sure we
1043  * don't think a command that queued inval messages was read-only.)
1044  */
1045  AtCCI_LocalCache();
1046  }
1047 }
1048 
1049 /*
1050  * ForceSyncCommit
1051  *
1052  * Interface routine to allow commands to force a synchronous commit of the
1053  * current top-level transaction. Currently, two-phase commit does not
1054  * persist and restore this variable. So long as all callers use
1055  * PreventInTransactionBlock(), that omission has no consequences.
1056  */
1057 void
1059 {
1060  forceSyncCommit = true;
1061 }
1062 
1063 
1064 /* ----------------------------------------------------------------
1065  * StartTransaction stuff
1066  * ----------------------------------------------------------------
1067  */
1068 
1069 /*
1070  * AtStart_Cache
1071  */
1072 static void
1074 {
1076 }
1077 
1078 /*
1079  * AtStart_Memory
1080  */
1081 static void
1083 {
1085 
1086  /*
1087  * If this is the first time through, create a private context for
1088  * AbortTransaction to work in. By reserving some space now, we can
1089  * insulate AbortTransaction from out-of-memory scenarios. Like
1090  * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1091  * size, so that space will be reserved immediately.
1092  */
1093  if (TransactionAbortContext == NULL)
1094  TransactionAbortContext =
1096  "TransactionAbortContext",
1097  32 * 1024,
1098  32 * 1024,
1099  32 * 1024);
1100 
1101  /*
1102  * We shouldn't have a transaction context already.
1103  */
1104  Assert(TopTransactionContext == NULL);
1105 
1106  /*
1107  * Create a toplevel context for the transaction.
1108  */
1111  "TopTransactionContext",
1113 
1114  /*
1115  * In a top-level transaction, CurTransactionContext is the same as
1116  * TopTransactionContext.
1117  */
1120 
1121  /* Make the CurTransactionContext active. */
1123 }
1124 
1125 /*
1126  * AtStart_ResourceOwner
1127  */
1128 static void
1130 {
1132 
1133  /*
1134  * We shouldn't have a transaction resource owner already.
1135  */
1137 
1138  /*
1139  * Create a toplevel resource owner for the transaction.
1140  */
1141  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1142 
1146 }
1147 
1148 /* ----------------------------------------------------------------
1149  * StartSubTransaction stuff
1150  * ----------------------------------------------------------------
1151  */
1152 
1153 /*
1154  * AtSubStart_Memory
1155  */
1156 static void
1158 {
1160 
1161  Assert(CurTransactionContext != NULL);
1162 
1163  /*
1164  * Create a CurTransactionContext, which will be used to hold data that
1165  * survives subtransaction commit but disappears on subtransaction abort.
1166  * We make it a child of the immediate parent's CurTransactionContext.
1167  */
1169  "CurTransactionContext",
1172 
1173  /* Make the CurTransactionContext active. */
1175 }
1176 
1177 /*
1178  * AtSubStart_ResourceOwner
1179  */
1180 static void
1182 {
1184 
1185  Assert(s->parent != NULL);
1186 
1187  /*
1188  * Create a resource owner for the subtransaction. We make it a child of
1189  * the immediate parent's resource owner.
1190  */
1191  s->curTransactionOwner =
1193  "SubTransaction");
1194 
1197 }
1198 
1199 /* ----------------------------------------------------------------
1200  * CommitTransaction stuff
1201  * ----------------------------------------------------------------
1202  */
1203 
1204 /*
1205  * RecordTransactionCommit
1206  *
1207  * Returns latest XID among xact and its children, or InvalidTransactionId
1208  * if the xact has no XID. (We compute that here just because it's easier.)
1209  *
1210  * If you change this function, see RecordTransactionCommitPrepared also.
1211  */
1212 static TransactionId
1214 {
1216  bool markXidCommitted = TransactionIdIsValid(xid);
1217  TransactionId latestXid = InvalidTransactionId;
1218  int nrels;
1219  RelFileNode *rels;
1220  int nchildren;
1221  TransactionId *children;
1222  int nmsgs = 0;
1223  SharedInvalidationMessage *invalMessages = NULL;
1224  bool RelcacheInitFileInval = false;
1225  bool wrote_xlog;
1226 
1227  /*
1228  * Log pending invalidations for logical decoding of in-progress
1229  * transactions. Normally for DDLs, we log this at each command end,
1230  * however, for certain cases where we directly update the system table
1231  * without a transaction block, the invalidations are not logged till this
1232  * time.
1233  */
1234  if (XLogLogicalInfoActive())
1236 
1237  /* Get data needed for commit record */
1238  nrels = smgrGetPendingDeletes(true, &rels);
1239  nchildren = xactGetCommittedChildren(&children);
1240  if (XLogStandbyInfoActive())
1241  nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1242  &RelcacheInitFileInval);
1243  wrote_xlog = (XactLastRecEnd != 0);
1244 
1245  /*
1246  * If we haven't been assigned an XID yet, we neither can, nor do we want
1247  * to write a COMMIT record.
1248  */
1249  if (!markXidCommitted)
1250  {
1251  /*
1252  * We expect that every RelationDropStorage is followed by a catalog
1253  * update, and hence XID assignment, so we shouldn't get here with any
1254  * pending deletes. Use a real test not just an Assert to check this,
1255  * since it's a bit fragile.
1256  */
1257  if (nrels != 0)
1258  elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1259 
1260  /* Can't have child XIDs either; AssignTransactionId enforces this */
1261  Assert(nchildren == 0);
1262 
1263  /*
1264  * Transactions without an assigned xid can contain invalidation
1265  * messages (e.g. explicit relcache invalidations or catcache
1266  * invalidations for inplace updates); standbys need to process those.
1267  * We can't emit a commit record without an xid, and we don't want to
1268  * force assigning an xid, because that'd be problematic for e.g.
1269  * vacuum. Hence we emit a bespoke record for the invalidations. We
1270  * don't want to use that in case a commit record is emitted, so they
1271  * happen synchronously with commits (besides not wanting to emit more
1272  * WAL records).
1273  */
1274  if (nmsgs != 0)
1275  {
1276  LogStandbyInvalidations(nmsgs, invalMessages,
1277  RelcacheInitFileInval);
1278  wrote_xlog = true; /* not strictly necessary */
1279  }
1280 
1281  /*
1282  * If we didn't create XLOG entries, we're done here; otherwise we
1283  * should trigger flushing those entries the same as a commit record
1284  * would. This will primarily happen for HOT pruning and the like; we
1285  * want these to be flushed to disk in due time.
1286  */
1287  if (!wrote_xlog)
1288  goto cleanup;
1289  }
1290  else
1291  {
1292  bool replorigin;
1293 
1294  /*
1295  * Are we using the replication origins feature? Or, in other words,
1296  * are we replaying remote actions?
1297  */
1298  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1300 
1301  /*
1302  * Begin commit critical section and insert the commit XLOG record.
1303  */
1304  /* Tell bufmgr and smgr to prepare for commit */
1305  BufmgrCommit();
1306 
1307  /*
1308  * Mark ourselves as within our "commit critical section". This
1309  * forces any concurrent checkpoint to wait until we've updated
1310  * pg_xact. Without this, it is possible for the checkpoint to set
1311  * REDO after the XLOG record but fail to flush the pg_xact update to
1312  * disk, leading to loss of the transaction commit if the system
1313  * crashes a little later.
1314  *
1315  * Note: we could, but don't bother to, set this flag in
1316  * RecordTransactionAbort. That's because loss of a transaction abort
1317  * is noncritical; the presumption would be that it aborted, anyway.
1318  *
1319  * It's safe to change the delayChkpt flag of our own backend without
1320  * holding the ProcArrayLock, since we're the only one modifying it.
1321  * This makes checkpoint's determination of which xacts are delayChkpt
1322  * a bit fuzzy, but it doesn't matter.
1323  */
1325  MyProc->delayChkpt = true;
1326 
1328 
1330  nchildren, children, nrels, rels,
1331  nmsgs, invalMessages,
1332  RelcacheInitFileInval,
1333  MyXactFlags,
1334  InvalidTransactionId, NULL /* plain commit */ );
1335 
1336  if (replorigin)
1337  /* Move LSNs forward for this replication origin */
1339  XactLastRecEnd);
1340 
1341  /*
1342  * Record commit timestamp. The value comes from plain commit
1343  * timestamp if there's no replication origin; otherwise, the
1344  * timestamp was already set in replorigin_session_origin_timestamp by
1345  * replication.
1346  *
1347  * We don't need to WAL-log anything here, as the commit record
1348  * written above already contains the data.
1349  */
1350 
1351  if (!replorigin || replorigin_session_origin_timestamp == 0)
1353 
1354  TransactionTreeSetCommitTsData(xid, nchildren, children,
1356  replorigin_session_origin, false);
1357  }
1358 
1359  /*
1360  * Check if we want to commit asynchronously. We can allow the XLOG flush
1361  * to happen asynchronously if synchronous_commit=off, or if the current
1362  * transaction has not performed any WAL-logged operation or didn't assign
1363  * an xid. The transaction can end up not writing any WAL, even if it has
1364  * an xid, if it only wrote to temporary and/or unlogged tables. It can
1365  * end up having written WAL without an xid if it did HOT pruning. In
1366  * case of a crash, the loss of such a transaction will be irrelevant;
1367  * temp tables will be lost anyway, unlogged tables will be truncated and
1368  * HOT pruning will be done again later. (Given the foregoing, you might
1369  * think that it would be unnecessary to emit the XLOG record at all in
1370  * this case, but we don't currently try to do that. It would certainly
1371  * cause problems at least in Hot Standby mode, where the
1372  * KnownAssignedXids machinery requires tracking every XID assignment. It
1373  * might be OK to skip it only when wal_level < replica, but for now we
1374  * don't.)
1375  *
1376  * However, if we're doing cleanup of any non-temp rels or committing any
1377  * command that wanted to force sync commit, then we must flush XLOG
1378  * immediately. (We must not allow asynchronous commit if there are any
1379  * non-temp tables to be deleted, because we might delete the files before
1380  * the COMMIT record is flushed to disk. We do allow asynchronous commit
1381  * if all to-be-deleted tables are temporary though, since they are lost
1382  * anyway if we crash.)
1383  */
1384  if ((wrote_xlog && markXidCommitted &&
1386  forceSyncCommit || nrels > 0)
1387  {
1389 
1390  /*
1391  * Now we may update the CLOG, if we wrote a COMMIT record above
1392  */
1393  if (markXidCommitted)
1394  TransactionIdCommitTree(xid, nchildren, children);
1395  }
1396  else
1397  {
1398  /*
1399  * Asynchronous commit case:
1400  *
1401  * This enables possible committed transaction loss in the case of a
1402  * postmaster crash because WAL buffers are left unwritten. Ideally we
1403  * could issue the WAL write without the fsync, but some
1404  * wal_sync_methods do not allow separate write/fsync.
1405  *
1406  * Report the latest async commit LSN, so that the WAL writer knows to
1407  * flush this commit.
1408  */
1410 
1411  /*
1412  * We must not immediately update the CLOG, since we didn't flush the
1413  * XLOG. Instead, we store the LSN up to which the XLOG must be
1414  * flushed before the CLOG may be updated.
1415  */
1416  if (markXidCommitted)
1417  TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1418  }
1419 
1420  /*
1421  * If we entered a commit critical section, leave it now, and let
1422  * checkpoints proceed.
1423  */
1424  if (markXidCommitted)
1425  {
1426  MyProc->delayChkpt = false;
1427  END_CRIT_SECTION();
1428  }
1429 
1430  /* Compute latestXid while we have the child XIDs handy */
1431  latestXid = TransactionIdLatest(xid, nchildren, children);
1432 
1433  /*
1434  * Wait for synchronous replication, if required. Similar to the decision
1435  * above about using committing asynchronously we only want to wait if
1436  * this backend assigned an xid and wrote WAL. No need to wait if an xid
1437  * was assigned due to temporary/unlogged tables or due to HOT pruning.
1438  *
1439  * Note that at this stage we have marked clog, but still show as running
1440  * in the procarray and continue to hold locks.
1441  */
1442  if (wrote_xlog && markXidCommitted)
1444 
1445  /* remember end of last commit record */
1447 
1448  /* Reset XactLastRecEnd until the next transaction writes something */
1449  XactLastRecEnd = 0;
1450 cleanup:
1451  /* Clean up local data */
1452  if (rels)
1453  pfree(rels);
1454 
1455  return latestXid;
1456 }
1457 
1458 
1459 /*
1460  * AtCCI_LocalCache
1461  */
1462 static void
1464 {
1465  /*
1466  * Make any pending relation map changes visible. We must do this before
1467  * processing local sinval messages, so that the map changes will get
1468  * reflected into the relcache when relcache invals are processed.
1469  */
1471 
1472  /*
1473  * Make catalog changes visible to me for the next command.
1474  */
1476 }
1477 
1478 /*
1479  * AtCommit_Memory
1480  */
1481 static void
1483 {
1484  /*
1485  * Now that we're "out" of a transaction, have the system allocate things
1486  * in the top memory context instead of per-transaction contexts.
1487  */
1489 
1490  /*
1491  * Release all transaction-local memory.
1492  */
1493  Assert(TopTransactionContext != NULL);
1495  TopTransactionContext = NULL;
1496  CurTransactionContext = NULL;
1497  CurrentTransactionState->curTransactionContext = NULL;
1498 }
1499 
1500 /* ----------------------------------------------------------------
1501  * CommitSubTransaction stuff
1502  * ----------------------------------------------------------------
1503  */
1504 
1505 /*
1506  * AtSubCommit_Memory
1507  */
1508 static void
1510 {
1512 
1513  Assert(s->parent != NULL);
1514 
1515  /* Return to parent transaction level's memory context. */
1518 
1519  /*
1520  * Ordinarily we cannot throw away the child's CurTransactionContext,
1521  * since the data it contains will be needed at upper commit. However, if
1522  * there isn't actually anything in it, we can throw it away. This avoids
1523  * a small memory leak in the common case of "trivial" subxacts.
1524  */
1526  {
1528  s->curTransactionContext = NULL;
1529  }
1530 }
1531 
1532 /*
1533  * AtSubCommit_childXids
1534  *
1535  * Pass my own XID and my child XIDs up to my parent as committed children.
1536  */
1537 static void
1539 {
1541  int new_nChildXids;
1542 
1543  Assert(s->parent != NULL);
1544 
1545  /*
1546  * The parent childXids array will need to hold my XID and all my
1547  * childXids, in addition to the XIDs already there.
1548  */
1549  new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1550 
1551  /* Allocate or enlarge the parent array if necessary */
1552  if (s->parent->maxChildXids < new_nChildXids)
1553  {
1554  int new_maxChildXids;
1555  TransactionId *new_childXids;
1556 
1557  /*
1558  * Make it 2x what's needed right now, to avoid having to enlarge it
1559  * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1560  * is what ensures that we don't need to worry about integer overflow
1561  * here or in the calculation of new_nChildXids.)
1562  */
1563  new_maxChildXids = Min(new_nChildXids * 2,
1564  (int) (MaxAllocSize / sizeof(TransactionId)));
1565 
1566  if (new_maxChildXids < new_nChildXids)
1567  ereport(ERROR,
1568  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1569  errmsg("maximum number of committed subtransactions (%d) exceeded",
1570  (int) (MaxAllocSize / sizeof(TransactionId)))));
1571 
1572  /*
1573  * We keep the child-XID arrays in TopTransactionContext; this avoids
1574  * setting up child-transaction contexts for what might be just a few
1575  * bytes of grandchild XIDs.
1576  */
1577  if (s->parent->childXids == NULL)
1578  new_childXids =
1580  new_maxChildXids * sizeof(TransactionId));
1581  else
1582  new_childXids = repalloc(s->parent->childXids,
1583  new_maxChildXids * sizeof(TransactionId));
1584 
1585  s->parent->childXids = new_childXids;
1586  s->parent->maxChildXids = new_maxChildXids;
1587  }
1588 
1589  /*
1590  * Copy all my XIDs to parent's array.
1591  *
1592  * Note: We rely on the fact that the XID of a child always follows that
1593  * of its parent. By copying the XID of this subtransaction before the
1594  * XIDs of its children, we ensure that the array stays ordered. Likewise,
1595  * all XIDs already in the array belong to subtransactions started and
1596  * subcommitted before us, so their XIDs must precede ours.
1597  */
1599 
1600  if (s->nChildXids > 0)
1601  memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1602  s->childXids,
1603  s->nChildXids * sizeof(TransactionId));
1604 
1605  s->parent->nChildXids = new_nChildXids;
1606 
1607  /* Release child's array to avoid leakage */
1608  if (s->childXids != NULL)
1609  pfree(s->childXids);
1610  /* We must reset these to avoid double-free if fail later in commit */
1611  s->childXids = NULL;
1612  s->nChildXids = 0;
1613  s->maxChildXids = 0;
1614 }
1615 
1616 /* ----------------------------------------------------------------
1617  * AbortTransaction stuff
1618  * ----------------------------------------------------------------
1619  */
1620 
1621 /*
1622  * RecordTransactionAbort
1623  *
1624  * Returns latest XID among xact and its children, or InvalidTransactionId
1625  * if the xact has no XID. (We compute that here just because it's easier.)
1626  */
1627 static TransactionId
1628 RecordTransactionAbort(bool isSubXact)
1629 {
1631  TransactionId latestXid;
1632  int nrels;
1633  RelFileNode *rels;
1634  int nchildren;
1635  TransactionId *children;
1636  TimestampTz xact_time;
1637 
1638  /*
1639  * If we haven't been assigned an XID, nobody will care whether we aborted
1640  * or not. Hence, we're done in that case. It does not matter if we have
1641  * rels to delete (note that this routine is not responsible for actually
1642  * deleting 'em). We cannot have any child XIDs, either.
1643  */
1644  if (!TransactionIdIsValid(xid))
1645  {
1646  /* Reset XactLastRecEnd until the next transaction writes something */
1647  if (!isSubXact)
1648  XactLastRecEnd = 0;
1649  return InvalidTransactionId;
1650  }
1651 
1652  /*
1653  * We have a valid XID, so we should write an ABORT record for it.
1654  *
1655  * We do not flush XLOG to disk here, since the default assumption after a
1656  * crash would be that we aborted, anyway. For the same reason, we don't
1657  * need to worry about interlocking against checkpoint start.
1658  */
1659 
1660  /*
1661  * Check that we haven't aborted halfway through RecordTransactionCommit.
1662  */
1663  if (TransactionIdDidCommit(xid))
1664  elog(PANIC, "cannot abort transaction %u, it was already committed",
1665  xid);
1666 
1667  /* Fetch the data we need for the abort record */
1668  nrels = smgrGetPendingDeletes(false, &rels);
1669  nchildren = xactGetCommittedChildren(&children);
1670 
1671  /* XXX do we really need a critical section here? */
1673 
1674  /* Write the ABORT record */
1675  if (isSubXact)
1676  xact_time = GetCurrentTimestamp();
1677  else
1678  {
1680  xact_time = xactStopTimestamp;
1681  }
1682 
1683  XactLogAbortRecord(xact_time,
1684  nchildren, children,
1685  nrels, rels,
1687  NULL);
1688 
1689  /*
1690  * Report the latest async abort LSN, so that the WAL writer knows to
1691  * flush this abort. There's nothing to be gained by delaying this, since
1692  * WALWriter may as well do this when it can. This is important with
1693  * streaming replication because if we don't flush WAL regularly we will
1694  * find that large aborts leave us with a long backlog for when commits
1695  * occur after the abort, increasing our window of data loss should
1696  * problems occur at that point.
1697  */
1698  if (!isSubXact)
1700 
1701  /*
1702  * Mark the transaction aborted in clog. This is not absolutely necessary
1703  * but we may as well do it while we are here; also, in the subxact case
1704  * it is helpful because XactLockTableWait makes use of it to avoid
1705  * waiting for already-aborted subtransactions. It is OK to do it without
1706  * having flushed the ABORT record to disk, because in event of a crash
1707  * we'd be assumed to have aborted anyway.
1708  */
1709  TransactionIdAbortTree(xid, nchildren, children);
1710 
1711  END_CRIT_SECTION();
1712 
1713  /* Compute latestXid while we have the child XIDs handy */
1714  latestXid = TransactionIdLatest(xid, nchildren, children);
1715 
1716  /*
1717  * If we're aborting a subtransaction, we can immediately remove failed
1718  * XIDs from PGPROC's cache of running child XIDs. We do that here for
1719  * subxacts, because we already have the child XID array at hand. For
1720  * main xacts, the equivalent happens just after this function returns.
1721  */
1722  if (isSubXact)
1723  XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1724 
1725  /* Reset XactLastRecEnd until the next transaction writes something */
1726  if (!isSubXact)
1727  XactLastRecEnd = 0;
1728 
1729  /* And clean up local data */
1730  if (rels)
1731  pfree(rels);
1732 
1733  return latestXid;
1734 }
1735 
1736 /*
1737  * AtAbort_Memory
1738  */
1739 static void
1741 {
1742  /*
1743  * Switch into TransactionAbortContext, which should have some free space
1744  * even if nothing else does. We'll work in this context until we've
1745  * finished cleaning up.
1746  *
1747  * It is barely possible to get here when we've not been able to create
1748  * TransactionAbortContext yet; if so use TopMemoryContext.
1749  */
1750  if (TransactionAbortContext != NULL)
1751  MemoryContextSwitchTo(TransactionAbortContext);
1752  else
1754 }
1755 
1756 /*
1757  * AtSubAbort_Memory
1758  */
1759 static void
1761 {
1762  Assert(TransactionAbortContext != NULL);
1763 
1764  MemoryContextSwitchTo(TransactionAbortContext);
1765 }
1766 
1767 
1768 /*
1769  * AtAbort_ResourceOwner
1770  */
1771 static void
1773 {
1774  /*
1775  * Make sure we have a valid ResourceOwner, if possible (else it will be
1776  * NULL, which is OK)
1777  */
1779 }
1780 
1781 /*
1782  * AtSubAbort_ResourceOwner
1783  */
1784 static void
1786 {
1788 
1789  /* Make sure we have a valid ResourceOwner */
1791 }
1792 
1793 
1794 /*
1795  * AtSubAbort_childXids
1796  */
1797 static void
1799 {
1801 
1802  /*
1803  * We keep the child-XID arrays in TopTransactionContext (see
1804  * AtSubCommit_childXids). This means we'd better free the array
1805  * explicitly at abort to avoid leakage.
1806  */
1807  if (s->childXids != NULL)
1808  pfree(s->childXids);
1809  s->childXids = NULL;
1810  s->nChildXids = 0;
1811  s->maxChildXids = 0;
1812 
1813  /*
1814  * We could prune the unreportedXids array here. But we don't bother. That
1815  * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1816  * would likely introduce more CPU time into the more common paths, so we
1817  * choose not to do that.
1818  */
1819 }
1820 
1821 /* ----------------------------------------------------------------
1822  * CleanupTransaction stuff
1823  * ----------------------------------------------------------------
1824  */
1825 
1826 /*
1827  * AtCleanup_Memory
1828  */
1829 static void
1831 {
1832  Assert(CurrentTransactionState->parent == NULL);
1833 
1834  /*
1835  * Now that we're "out" of a transaction, have the system allocate things
1836  * in the top memory context instead of per-transaction contexts.
1837  */
1839 
1840  /*
1841  * Clear the special abort context for next time.
1842  */
1843  if (TransactionAbortContext != NULL)
1844  MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1845 
1846  /*
1847  * Release all transaction-local memory.
1848  */
1849  if (TopTransactionContext != NULL)
1851  TopTransactionContext = NULL;
1852  CurTransactionContext = NULL;
1853  CurrentTransactionState->curTransactionContext = NULL;
1854 }
1855 
1856 
1857 /* ----------------------------------------------------------------
1858  * CleanupSubTransaction stuff
1859  * ----------------------------------------------------------------
1860  */
1861 
1862 /*
1863  * AtSubCleanup_Memory
1864  */
1865 static void
1867 {
1869 
1870  Assert(s->parent != NULL);
1871 
1872  /* Make sure we're not in an about-to-be-deleted context */
1875 
1876  /*
1877  * Clear the special abort context for next time.
1878  */
1879  if (TransactionAbortContext != NULL)
1880  MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1881 
1882  /*
1883  * Delete the subxact local memory contexts. Its CurTransactionContext can
1884  * go too (note this also kills CurTransactionContexts from any children
1885  * of the subxact).
1886  */
1887  if (s->curTransactionContext)
1889  s->curTransactionContext = NULL;
1890 }
1891 
1892 /* ----------------------------------------------------------------
1893  * interface routines
1894  * ----------------------------------------------------------------
1895  */
1896 
1897 /*
1898  * StartTransaction
1899  */
1900 static void
1902 {
1903  TransactionState s;
1904  VirtualTransactionId vxid;
1905 
1906  /*
1907  * Let's just make sure the state stack is empty
1908  */
1910  CurrentTransactionState = s;
1911 
1912  Assert(!FullTransactionIdIsValid(XactTopFullTransactionId));
1913 
1914  /* check the current transaction state */
1915  Assert(s->state == TRANS_DEFAULT);
1916 
1917  /*
1918  * Set the current transaction state information appropriately during
1919  * start processing. Note that once the transaction status is switched
1920  * this process cannot fail until the user ID and the security context
1921  * flags are fetched below.
1922  */
1923  s->state = TRANS_START;
1924  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
1925 
1926  /* Determine if statements are logged in this transaction */
1928  (log_xact_sample_rate == 1 ||
1930 
1931  /*
1932  * initialize current transaction state fields
1933  *
1934  * note: prevXactReadOnly is not used at the outermost level
1935  */
1936  s->nestingLevel = 1;
1937  s->gucNestLevel = 1;
1938  s->childXids = NULL;
1939  s->nChildXids = 0;
1940  s->maxChildXids = 0;
1941 
1942  /*
1943  * Once the current user ID and the security context flags are fetched,
1944  * both will be properly reset even if transaction startup fails.
1945  */
1947 
1948  /* SecurityRestrictionContext should never be set outside a transaction */
1949  Assert(s->prevSecContext == 0);
1950 
1951  /*
1952  * Make sure we've reset xact state variables
1953  *
1954  * If recovery is still in progress, mark this transaction as read-only.
1955  * We have lower level defences in XLogInsert and elsewhere to stop us
1956  * from modifying data during recovery, but this gives the normal
1957  * indication to the user that the transaction is read-only.
1958  */
1959  if (RecoveryInProgress())
1960  {
1961  s->startedInRecovery = true;
1962  XactReadOnly = true;
1963  }
1964  else
1965  {
1966  s->startedInRecovery = false;
1968  }
1971  forceSyncCommit = false;
1972  MyXactFlags = 0;
1973 
1974  /*
1975  * reinitialize within-transaction counters
1976  */
1980  currentCommandIdUsed = false;
1981 
1982  /*
1983  * initialize reported xid accounting
1984  */
1985  nUnreportedXids = 0;
1986  s->didLogXid = false;
1987 
1988  /*
1989  * must initialize resource-management stuff first
1990  */
1991  AtStart_Memory();
1993 
1994  /*
1995  * Assign a new LocalTransactionId, and combine it with the backendId to
1996  * form a virtual transaction id.
1997  */
1998  vxid.backendId = MyBackendId;
2000 
2001  /*
2002  * Lock the virtual transaction id before we announce it in the proc array
2003  */
2005 
2006  /*
2007  * Advertise it in the proc array. We assume assignment of
2008  * localTransactionId is atomic, and the backendId should be set already.
2009  */
2010  Assert(MyProc->backendId == vxid.backendId);
2011  MyProc->lxid = vxid.localTransactionId;
2012 
2013  TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
2014 
2015  /*
2016  * set transaction_timestamp() (a/k/a now()). Normally, we want this to
2017  * be the same as the first command's statement_timestamp(), so don't do a
2018  * fresh GetCurrentTimestamp() call (which'd be expensive anyway). But
2019  * for transactions started inside procedures (i.e., nonatomic SPI
2020  * contexts), we do need to advance the timestamp. Also, in a parallel
2021  * worker, the timestamp should already have been provided by a call to
2022  * SetParallelStartTimestamps().
2023  */
2024  if (!IsParallelWorker())
2025  {
2028  else
2030  }
2031  else
2032  Assert(xactStartTimestamp != 0);
2034  /* Mark xactStopTimestamp as unset. */
2035  xactStopTimestamp = 0;
2036 
2037  /*
2038  * initialize other subsystems for new transaction
2039  */
2040  AtStart_GUC();
2041  AtStart_Cache();
2043 
2044  /*
2045  * done with start processing, set current transaction state to "in
2046  * progress"
2047  */
2048  s->state = TRANS_INPROGRESS;
2049 
2050  ShowTransactionState("StartTransaction");
2051 }
2052 
2053 
2054 /*
2055  * CommitTransaction
2056  *
2057  * NB: if you change this routine, better look at PrepareTransaction too!
2058  */
2059 static void
2061 {
2063  TransactionId latestXid;
2064  bool is_parallel_worker;
2065 
2066  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2067 
2068  /* Enforce parallel mode restrictions during parallel worker commit. */
2069  if (is_parallel_worker)
2071 
2072  ShowTransactionState("CommitTransaction");
2073 
2074  /*
2075  * check the current transaction state
2076  */
2077  if (s->state != TRANS_INPROGRESS)
2078  elog(WARNING, "CommitTransaction while in %s state",
2080  Assert(s->parent == NULL);
2081 
2082  /*
2083  * Do pre-commit processing that involves calling user-defined code, such
2084  * as triggers. Since closing cursors could queue trigger actions,
2085  * triggers could open cursors, etc, we have to keep looping until there's
2086  * nothing left to do.
2087  */
2088  for (;;)
2089  {
2090  /*
2091  * Fire all currently pending deferred triggers.
2092  */
2094 
2095  /*
2096  * Close open portals (converting holdable ones into static portals).
2097  * If there weren't any, we are done ... otherwise loop back to check
2098  * if they queued deferred triggers. Lather, rinse, repeat.
2099  */
2100  if (!PreCommit_Portals(false))
2101  break;
2102  }
2103 
2106 
2107  /*
2108  * The remaining actions cannot call any user-defined code, so it's safe
2109  * to start shutting down within-transaction services. But note that most
2110  * of this stuff could still throw an error, which would switch us into
2111  * the transaction-abort path.
2112  */
2113 
2114  /* If we might have parallel workers, clean them up now. */
2115  if (IsInParallelMode())
2116  AtEOXact_Parallel(true);
2117 
2118  /* Shut down the deferred-trigger manager */
2119  AfterTriggerEndXact(true);
2120 
2121  /*
2122  * Let ON COMMIT management do its thing (must happen after closing
2123  * cursors, to avoid dangling-reference problems)
2124  */
2126 
2127  /*
2128  * Synchronize files that are created and not WAL-logged during this
2129  * transaction. This must happen before AtEOXact_RelationMap(), so that we
2130  * don't see committed-but-broken files after a crash.
2131  */
2132  smgrDoPendingSyncs(true, is_parallel_worker);
2133 
2134  /* close large objects before lower-level cleanup */
2135  AtEOXact_LargeObject(true);
2136 
2137  /*
2138  * Insert notifications sent by NOTIFY commands into the queue. This
2139  * should be late in the pre-commit sequence to minimize time spent
2140  * holding the notify-insertion lock. However, this could result in
2141  * creating a snapshot, so we must do it before serializable cleanup.
2142  */
2143  PreCommit_Notify();
2144 
2145  /*
2146  * Mark serializable transaction as complete for predicate locking
2147  * purposes. This should be done as late as we can put it and still allow
2148  * errors to be raised for failure patterns found at commit. This is not
2149  * appropriate in a parallel worker however, because we aren't committing
2150  * the leader's transaction and its serializable state will live on.
2151  */
2152  if (!is_parallel_worker)
2154 
2155  /* Prevent cancel/die interrupt while cleaning up */
2156  HOLD_INTERRUPTS();
2157 
2158  /* Commit updates to the relation map --- do this as late as possible */
2159  AtEOXact_RelationMap(true, is_parallel_worker);
2160 
2161  /*
2162  * set the current transaction state information appropriately during
2163  * commit processing
2164  */
2165  s->state = TRANS_COMMIT;
2166  s->parallelModeLevel = 0;
2167 
2168  if (!is_parallel_worker)
2169  {
2170  /*
2171  * We need to mark our XIDs as committed in pg_xact. This is where we
2172  * durably commit.
2173  */
2174  latestXid = RecordTransactionCommit();
2175  }
2176  else
2177  {
2178  /*
2179  * We must not mark our XID committed; the parallel leader is
2180  * responsible for that.
2181  */
2182  latestXid = InvalidTransactionId;
2183 
2184  /*
2185  * Make sure the leader will know about any WAL we wrote before it
2186  * commits.
2187  */
2189  }
2190 
2191  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
2192 
2193  /*
2194  * Let others know about no transaction in progress by me. Note that this
2195  * must be done _before_ releasing locks we hold and _after_
2196  * RecordTransactionCommit.
2197  */
2198  ProcArrayEndTransaction(MyProc, latestXid);
2199 
2200  /*
2201  * This is all post-commit cleanup. Note that if an error is raised here,
2202  * it's too late to abort the transaction. This should be just
2203  * noncritical resource releasing.
2204  *
2205  * The ordering of operations is not entirely random. The idea is:
2206  * release resources visible to other backends (eg, files, buffer pins);
2207  * then release locks; then release backend-local resources. We want to
2208  * release locks at the point where any backend waiting for us will see
2209  * our transaction as being fully cleaned up.
2210  *
2211  * Resources that can be associated with individual queries are handled by
2212  * the ResourceOwner mechanism. The other calls here are for backend-wide
2213  * state.
2214  */
2215 
2216  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2217  : XACT_EVENT_COMMIT);
2218 
2221  true, true);
2222 
2223  /* Check we've released all buffer pins */
2224  AtEOXact_Buffers(true);
2225 
2226  /* Clean up the relation cache */
2227  AtEOXact_RelationCache(true);
2228 
2229  /*
2230  * Make catalog changes visible to all backends. This has to happen after
2231  * relcache references are dropped (see comments for
2232  * AtEOXact_RelationCache), but before locks are released (if anyone is
2233  * waiting for lock on a relation we've modified, we want them to know
2234  * about the catalog change before they start using the relation).
2235  */
2236  AtEOXact_Inval(true);
2237 
2239 
2242  true, true);
2245  true, true);
2246 
2247  /*
2248  * Likewise, dropping of files deleted during the transaction is best done
2249  * after releasing relcache and buffer pins. (This is not strictly
2250  * necessary during commit, since such pins should have been released
2251  * already, but this ordering is definitely critical during abort.) Since
2252  * this may take many seconds, also delay until after releasing locks.
2253  * Other backends will observe the attendant catalog changes and not
2254  * attempt to access affected files.
2255  */
2256  smgrDoPendingDeletes(true);
2257 
2258  AtCommit_Notify();
2259  AtEOXact_GUC(true, 1);
2260  AtEOXact_SPI(true);
2261  AtEOXact_Enum();
2263  AtEOXact_Namespace(true, is_parallel_worker);
2264  AtEOXact_SMgr();
2265  AtEOXact_Files(true);
2267  AtEOXact_HashTables(true);
2268  AtEOXact_PgStat(true, is_parallel_worker);
2269  AtEOXact_Snapshot(true, false);
2270  AtEOXact_ApplyLauncher(true);
2272 
2273  CurrentResourceOwner = NULL;
2275  s->curTransactionOwner = NULL;
2278 
2279  AtCommit_Memory();
2280 
2283  s->nestingLevel = 0;
2284  s->gucNestLevel = 0;
2285  s->childXids = NULL;
2286  s->nChildXids = 0;
2287  s->maxChildXids = 0;
2288 
2289  XactTopFullTransactionId = InvalidFullTransactionId;
2291 
2292  /*
2293  * done with commit processing, set current transaction state back to
2294  * default
2295  */
2296  s->state = TRANS_DEFAULT;
2297 
2299 }
2300 
2301 
2302 /*
2303  * PrepareTransaction
2304  *
2305  * NB: if you change this routine, better look at CommitTransaction too!
2306  */
2307 static void
2309 {
2312  GlobalTransaction gxact;
2313  TimestampTz prepared_at;
2314 
2316 
2317  ShowTransactionState("PrepareTransaction");
2318 
2319  /*
2320  * check the current transaction state
2321  */
2322  if (s->state != TRANS_INPROGRESS)
2323  elog(WARNING, "PrepareTransaction while in %s state",
2325  Assert(s->parent == NULL);
2326 
2327  /*
2328  * Do pre-commit processing that involves calling user-defined code, such
2329  * as triggers. Since closing cursors could queue trigger actions,
2330  * triggers could open cursors, etc, we have to keep looping until there's
2331  * nothing left to do.
2332  */
2333  for (;;)
2334  {
2335  /*
2336  * Fire all currently pending deferred triggers.
2337  */
2339 
2340  /*
2341  * Close open portals (converting holdable ones into static portals).
2342  * If there weren't any, we are done ... otherwise loop back to check
2343  * if they queued deferred triggers. Lather, rinse, repeat.
2344  */
2345  if (!PreCommit_Portals(true))
2346  break;
2347  }
2348 
2350 
2351  /*
2352  * The remaining actions cannot call any user-defined code, so it's safe
2353  * to start shutting down within-transaction services. But note that most
2354  * of this stuff could still throw an error, which would switch us into
2355  * the transaction-abort path.
2356  */
2357 
2358  /* Shut down the deferred-trigger manager */
2359  AfterTriggerEndXact(true);
2360 
2361  /*
2362  * Let ON COMMIT management do its thing (must happen after closing
2363  * cursors, to avoid dangling-reference problems)
2364  */
2366 
2367  /*
2368  * Synchronize files that are created and not WAL-logged during this
2369  * transaction. This must happen before EndPrepare(), so that we don't see
2370  * committed-but-broken files after a crash and COMMIT PREPARED.
2371  */
2372  smgrDoPendingSyncs(true, false);
2373 
2374  /* close large objects before lower-level cleanup */
2375  AtEOXact_LargeObject(true);
2376 
2377  /* NOTIFY requires no work at this point */
2378 
2379  /*
2380  * Mark serializable transaction as complete for predicate locking
2381  * purposes. This should be done as late as we can put it and still allow
2382  * errors to be raised for failure patterns found at commit.
2383  */
2385 
2386  /*
2387  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2388  * this transaction. Having the prepared xact hold locks on another
2389  * backend's temp table seems a bad idea --- for instance it would prevent
2390  * the backend from exiting. There are other problems too, such as how to
2391  * clean up the source backend's local buffers and ON COMMIT state if the
2392  * prepared xact includes a DROP of a temp table.
2393  *
2394  * Other objects types, like functions, operators or extensions, share the
2395  * same restriction as they should not be created, locked or dropped as
2396  * this can mess up with this session or even a follow-up session trying
2397  * to use the same temporary namespace.
2398  *
2399  * We must check this after executing any ON COMMIT actions, because they
2400  * might still access a temp relation.
2401  *
2402  * XXX In principle this could be relaxed to allow some useful special
2403  * cases, such as a temp table created and dropped all within the
2404  * transaction. That seems to require much more bookkeeping though.
2405  */
2407  ereport(ERROR,
2408  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2409  errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2410 
2411  /*
2412  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2413  * supported if we added cleanup logic to twophase.c, but for now it
2414  * doesn't seem worth the trouble.
2415  */
2417  ereport(ERROR,
2418  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2419  errmsg("cannot PREPARE a transaction that has exported snapshots")));
2420 
2421  /*
2422  * Don't allow PREPARE but for transaction that has/might kill logical
2423  * replication workers.
2424  */
2426  ereport(ERROR,
2427  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2428  errmsg("cannot PREPARE a transaction that has manipulated logical replication workers")));
2429 
2430  /* Prevent cancel/die interrupt while cleaning up */
2431  HOLD_INTERRUPTS();
2432 
2433  /*
2434  * set the current transaction state information appropriately during
2435  * prepare processing
2436  */
2437  s->state = TRANS_PREPARE;
2438 
2439  prepared_at = GetCurrentTimestamp();
2440 
2441  /* Tell bufmgr and smgr to prepare for commit */
2442  BufmgrCommit();
2443 
2444  /*
2445  * Reserve the GID for this transaction. This could fail if the requested
2446  * GID is invalid or already in use.
2447  */
2448  gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2449  GetUserId(), MyDatabaseId);
2450  prepareGID = NULL;
2451 
2452  /*
2453  * Collect data for the 2PC state file. Note that in general, no actual
2454  * state change should happen in the called modules during this step,
2455  * since it's still possible to fail before commit, and in that case we
2456  * want transaction abort to be able to clean up. (In particular, the
2457  * AtPrepare routines may error out if they find cases they cannot
2458  * handle.) State cleanup should happen in the PostPrepare routines
2459  * below. However, some modules can go ahead and clear state here because
2460  * they wouldn't do anything with it during abort anyway.
2461  *
2462  * Note: because the 2PC state file records will be replayed in the same
2463  * order they are made, the order of these calls has to match the order in
2464  * which we want things to happen during COMMIT PREPARED or ROLLBACK
2465  * PREPARED; in particular, pay attention to whether things should happen
2466  * before or after releasing the transaction's locks.
2467  */
2468  StartPrepare(gxact);
2469 
2470  AtPrepare_Notify();
2471  AtPrepare_Locks();
2473  AtPrepare_PgStat();
2476 
2477  /*
2478  * Here is where we really truly prepare.
2479  *
2480  * We have to record transaction prepares even if we didn't make any
2481  * updates, because the transaction manager might get confused if we lose
2482  * a global transaction.
2483  */
2484  EndPrepare(gxact);
2485 
2486  /*
2487  * Now we clean up backend-internal state and release internal resources.
2488  */
2489 
2490  /* Reset XactLastRecEnd until the next transaction writes something */
2491  XactLastRecEnd = 0;
2492 
2493  /*
2494  * Let others know about no transaction in progress by me. This has to be
2495  * done *after* the prepared transaction has been marked valid, else
2496  * someone may think it is unlocked and recyclable.
2497  */
2499 
2500  /*
2501  * In normal commit-processing, this is all non-critical post-transaction
2502  * cleanup. When the transaction is prepared, however, it's important
2503  * that the locks and other per-backend resources are transferred to the
2504  * prepared transaction's PGPROC entry. Note that if an error is raised
2505  * here, it's too late to abort the transaction. XXX: This probably should
2506  * be in a critical section, to force a PANIC if any of this fails, but
2507  * that cure could be worse than the disease.
2508  */
2509 
2511 
2514  true, true);
2515 
2516  /* Check we've released all buffer pins */
2517  AtEOXact_Buffers(true);
2518 
2519  /* Clean up the relation cache */
2520  AtEOXact_RelationCache(true);
2521 
2522  /* notify doesn't need a postprepare call */
2523 
2525 
2527 
2528  PostPrepare_smgr();
2529 
2530  PostPrepare_MultiXact(xid);
2531 
2532  PostPrepare_Locks(xid);
2534 
2537  true, true);
2540  true, true);
2541 
2542  /*
2543  * Allow another backend to finish the transaction. After
2544  * PostPrepare_Twophase(), the transaction is completely detached from our
2545  * backend. The rest is just non-critical cleanup of backend-local state.
2546  */
2548 
2549  /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2550  AtEOXact_GUC(true, 1);
2551  AtEOXact_SPI(true);
2552  AtEOXact_Enum();
2554  AtEOXact_Namespace(true, false);
2555  AtEOXact_SMgr();
2556  AtEOXact_Files(true);
2558  AtEOXact_HashTables(true);
2559  /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2560  AtEOXact_Snapshot(true, true);
2562 
2563  CurrentResourceOwner = NULL;
2565  s->curTransactionOwner = NULL;
2568 
2569  AtCommit_Memory();
2570 
2573  s->nestingLevel = 0;
2574  s->gucNestLevel = 0;
2575  s->childXids = NULL;
2576  s->nChildXids = 0;
2577  s->maxChildXids = 0;
2578 
2579  XactTopFullTransactionId = InvalidFullTransactionId;
2581 
2582  /*
2583  * done with 1st phase commit processing, set current transaction state
2584  * back to default
2585  */
2586  s->state = TRANS_DEFAULT;
2587 
2589 }
2590 
2591 
2592 /*
2593  * AbortTransaction
2594  */
2595 static void
2597 {
2599  TransactionId latestXid;
2600  bool is_parallel_worker;
2601 
2602  /* Prevent cancel/die interrupt while cleaning up */
2603  HOLD_INTERRUPTS();
2604 
2605  /* Make sure we have a valid memory context and resource owner */
2606  AtAbort_Memory();
2608 
2609  /*
2610  * Release any LW locks we might be holding as quickly as possible.
2611  * (Regular locks, however, must be held till we finish aborting.)
2612  * Releasing LW locks is critical since we might try to grab them again
2613  * while cleaning up!
2614  */
2615  LWLockReleaseAll();
2616 
2617  /* Clear wait information and command progress indicator */
2620 
2621  /* Clean up buffer I/O and buffer context locks, too */
2622  AbortBufferIO();
2623  UnlockBuffers();
2624 
2625  /* Reset WAL record construction state */
2627 
2628  /* Cancel condition variable sleep */
2630 
2631  /*
2632  * Also clean up any open wait for lock, since the lock manager will choke
2633  * if we try to wait for another lock before doing this.
2634  */
2635  LockErrorCleanup();
2636 
2637  /*
2638  * If any timeout events are still active, make sure the timeout interrupt
2639  * is scheduled. This covers possible loss of a timeout interrupt due to
2640  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2641  * We delay this till after LockErrorCleanup so that we don't uselessly
2642  * reschedule lock or deadlock check timeouts.
2643  */
2645 
2646  /*
2647  * Re-enable signals, in case we got here by longjmp'ing out of a signal
2648  * handler. We do this fairly early in the sequence so that the timeout
2649  * infrastructure will be functional if needed while aborting.
2650  */
2652 
2653  /*
2654  * check the current transaction state
2655  */
2656  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2657  if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2658  elog(WARNING, "AbortTransaction while in %s state",
2660  Assert(s->parent == NULL);
2661 
2662  /*
2663  * set the current transaction state information appropriately during the
2664  * abort processing
2665  */
2666  s->state = TRANS_ABORT;
2667 
2668  /*
2669  * Reset user ID which might have been changed transiently. We need this
2670  * to clean up in case control escaped out of a SECURITY DEFINER function
2671  * or other local change of CurrentUserId; therefore, the prior value of
2672  * SecurityRestrictionContext also needs to be restored.
2673  *
2674  * (Note: it is not necessary to restore session authorization or role
2675  * settings here because those can only be changed via GUC, and GUC will
2676  * take care of rolling them back if need be.)
2677  */
2679 
2680  /* Forget about any active REINDEX. */
2682 
2683  /* If in parallel mode, clean up workers and exit parallel mode. */
2684  if (IsInParallelMode())
2685  {
2686  AtEOXact_Parallel(false);
2687  s->parallelModeLevel = 0;
2688  }
2689 
2690  /*
2691  * do abort processing
2692  */
2693  AfterTriggerEndXact(false); /* 'false' means it's abort */
2694  AtAbort_Portals();
2695  smgrDoPendingSyncs(false, is_parallel_worker);
2696  AtEOXact_LargeObject(false);
2697  AtAbort_Notify();
2698  AtEOXact_RelationMap(false, is_parallel_worker);
2699  AtAbort_Twophase();
2700 
2701  /*
2702  * Advertise the fact that we aborted in pg_xact (assuming that we got as
2703  * far as assigning an XID to advertise). But if we're inside a parallel
2704  * worker, skip this; the user backend must be the one to write the abort
2705  * record.
2706  */
2707  if (!is_parallel_worker)
2708  latestXid = RecordTransactionAbort(false);
2709  else
2710  {
2711  latestXid = InvalidTransactionId;
2712 
2713  /*
2714  * Since the parallel leader won't get our value of XactLastRecEnd in
2715  * this case, we nudge WAL-writer ourselves in this case. See related
2716  * comments in RecordTransactionAbort for why this matters.
2717  */
2719  }
2720 
2721  TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2722 
2723  /*
2724  * Let others know about no transaction in progress by me. Note that this
2725  * must be done _before_ releasing locks we hold and _after_
2726  * RecordTransactionAbort.
2727  */
2728  ProcArrayEndTransaction(MyProc, latestXid);
2729 
2730  /*
2731  * Post-abort cleanup. See notes in CommitTransaction() concerning
2732  * ordering. We can skip all of it if the transaction failed before
2733  * creating a resource owner.
2734  */
2735  if (TopTransactionResourceOwner != NULL)
2736  {
2737  if (is_parallel_worker)
2739  else
2741 
2744  false, true);
2745  AtEOXact_Buffers(false);
2746  AtEOXact_RelationCache(false);
2747  AtEOXact_Inval(false);
2751  false, true);
2754  false, true);
2755  smgrDoPendingDeletes(false);
2756 
2757  AtEOXact_GUC(false, 1);
2758  AtEOXact_SPI(false);
2759  AtEOXact_Enum();
2761  AtEOXact_Namespace(false, is_parallel_worker);
2762  AtEOXact_SMgr();
2763  AtEOXact_Files(false);
2765  AtEOXact_HashTables(false);
2766  AtEOXact_PgStat(false, is_parallel_worker);
2767  AtEOXact_ApplyLauncher(false);
2769  }
2770 
2771  /*
2772  * State remains TRANS_ABORT until CleanupTransaction().
2773  */
2775 }
2776 
2777 /*
2778  * CleanupTransaction
2779  */
2780 static void
2782 {
2784 
2785  /*
2786  * State should still be TRANS_ABORT from AbortTransaction().
2787  */
2788  if (s->state != TRANS_ABORT)
2789  elog(FATAL, "CleanupTransaction: unexpected state %s",
2791 
2792  /*
2793  * do abort cleanup processing
2794  */
2795  AtCleanup_Portals(); /* now safe to release portal memory */
2796  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
2797 
2798  CurrentResourceOwner = NULL; /* and resource owner */
2801  s->curTransactionOwner = NULL;
2804 
2805  AtCleanup_Memory(); /* and transaction memory */
2806 
2809  s->nestingLevel = 0;
2810  s->gucNestLevel = 0;
2811  s->childXids = NULL;
2812  s->nChildXids = 0;
2813  s->maxChildXids = 0;
2814  s->parallelModeLevel = 0;
2815 
2816  XactTopFullTransactionId = InvalidFullTransactionId;
2818 
2819  /*
2820  * done with abort processing, set current transaction state back to
2821  * default
2822  */
2823  s->state = TRANS_DEFAULT;
2824 }
2825 
2826 /*
2827  * StartTransactionCommand
2828  */
2829 void
2831 {
2833 
2834  switch (s->blockState)
2835  {
2836  /*
2837  * if we aren't in a transaction block, we just do our usual start
2838  * transaction.
2839  */
2840  case TBLOCK_DEFAULT:
2841  StartTransaction();
2843  break;
2844 
2845  /*
2846  * We are somewhere in a transaction block or subtransaction and
2847  * about to start a new command. For now we do nothing, but
2848  * someday we may do command-local resource initialization. (Note
2849  * that any needed CommandCounterIncrement was done by the
2850  * previous CommitTransactionCommand.)
2851  */
2852  case TBLOCK_INPROGRESS:
2854  case TBLOCK_SUBINPROGRESS:
2855  break;
2856 
2857  /*
2858  * Here we are in a failed transaction block (one of the commands
2859  * caused an abort) so we do nothing but remain in the abort
2860  * state. Eventually we will get a ROLLBACK command which will
2861  * get us out of this state. (It is up to other code to ensure
2862  * that no commands other than ROLLBACK will be processed in these
2863  * states.)
2864  */
2865  case TBLOCK_ABORT:
2866  case TBLOCK_SUBABORT:
2867  break;
2868 
2869  /* These cases are invalid. */
2870  case TBLOCK_STARTED:
2871  case TBLOCK_BEGIN:
2873  case TBLOCK_SUBBEGIN:
2874  case TBLOCK_END:
2875  case TBLOCK_SUBRELEASE:
2876  case TBLOCK_SUBCOMMIT:
2877  case TBLOCK_ABORT_END:
2878  case TBLOCK_SUBABORT_END:
2879  case TBLOCK_ABORT_PENDING:
2881  case TBLOCK_SUBRESTART:
2883  case TBLOCK_PREPARE:
2884  elog(ERROR, "StartTransactionCommand: unexpected state %s",
2886  break;
2887  }
2888 
2889  /*
2890  * We must switch to CurTransactionContext before returning. This is
2891  * already done if we called StartTransaction, otherwise not.
2892  */
2893  Assert(CurTransactionContext != NULL);
2895 }
2896 
2897 
2898 /*
2899  * Simple system for saving and restoring transaction characteristics
2900  * (isolation level, read only, deferrable). We need this for transaction
2901  * chaining, so that we can set the characteristics of the new transaction to
2902  * be the same as the previous one. (We need something like this because the
2903  * GUC system resets the characteristics at transaction end, so for example
2904  * just skipping the reset in StartTransaction() won't work.)
2905  */
2907 static bool save_XactReadOnly;
2909 
2910 void
2912 {
2916 }
2917 
2918 void
2920 {
2924 }
2925 
2926 
2927 /*
2928  * CommitTransactionCommand
2929  */
2930 void
2932 {
2934 
2935  if (s->chain)
2937 
2938  switch (s->blockState)
2939  {
2940  /*
2941  * These shouldn't happen. TBLOCK_DEFAULT means the previous
2942  * StartTransactionCommand didn't set the STARTED state
2943  * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
2944  * by EndParallelWorkerTransaction(), not this function.
2945  */
2946  case TBLOCK_DEFAULT:
2948  elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2950  break;
2951 
2952  /*
2953  * If we aren't in a transaction block, just do our usual
2954  * transaction commit, and return to the idle state.
2955  */
2956  case TBLOCK_STARTED:
2959  break;
2960 
2961  /*
2962  * We are completing a "BEGIN TRANSACTION" command, so we change
2963  * to the "transaction block in progress" state and return. (We
2964  * assume the BEGIN did nothing to the database, so we need no
2965  * CommandCounterIncrement.)
2966  */
2967  case TBLOCK_BEGIN:
2969  break;
2970 
2971  /*
2972  * This is the case when we have finished executing a command
2973  * someplace within a transaction block. We increment the command
2974  * counter and return.
2975  */
2976  case TBLOCK_INPROGRESS:
2978  case TBLOCK_SUBINPROGRESS:
2980  break;
2981 
2982  /*
2983  * We are completing a "COMMIT" command. Do it and return to the
2984  * idle state.
2985  */
2986  case TBLOCK_END:
2989  if (s->chain)
2990  {
2991  StartTransaction();
2993  s->chain = false;
2995  }
2996  break;
2997 
2998  /*
2999  * Here we are in the middle of a transaction block but one of the
3000  * commands caused an abort so we do nothing but remain in the
3001  * abort state. Eventually we will get a ROLLBACK command.
3002  */
3003  case TBLOCK_ABORT:
3004  case TBLOCK_SUBABORT:
3005  break;
3006 
3007  /*
3008  * Here we were in an aborted transaction block and we just got
3009  * the ROLLBACK command from the user, so clean up the
3010  * already-aborted transaction and return to the idle state.
3011  */
3012  case TBLOCK_ABORT_END:
3015  if (s->chain)
3016  {
3017  StartTransaction();
3019  s->chain = false;
3021  }
3022  break;
3023 
3024  /*
3025  * Here we were in a perfectly good transaction block but the user
3026  * told us to ROLLBACK anyway. We have to abort the transaction
3027  * and then clean up.
3028  */
3029  case TBLOCK_ABORT_PENDING:
3030  AbortTransaction();
3033  if (s->chain)
3034  {
3035  StartTransaction();
3037  s->chain = false;
3039  }
3040  break;
3041 
3042  /*
3043  * We are completing a "PREPARE TRANSACTION" command. Do it and
3044  * return to the idle state.
3045  */
3046  case TBLOCK_PREPARE:
3049  break;
3050 
3051  /*
3052  * We were just issued a SAVEPOINT inside a transaction block.
3053  * Start a subtransaction. (DefineSavepoint already did
3054  * PushTransaction, so as to have someplace to put the SUBBEGIN
3055  * state.)
3056  */
3057  case TBLOCK_SUBBEGIN:
3060  break;
3061 
3062  /*
3063  * We were issued a RELEASE command, so we end the current
3064  * subtransaction and return to the parent transaction. The parent
3065  * might be ended too, so repeat till we find an INPROGRESS
3066  * transaction or subtransaction.
3067  */
3068  case TBLOCK_SUBRELEASE:
3069  do
3070  {
3072  s = CurrentTransactionState; /* changed by pop */
3073  } while (s->blockState == TBLOCK_SUBRELEASE);
3074 
3077  break;
3078 
3079  /*
3080  * We were issued a COMMIT, so we end the current subtransaction
3081  * hierarchy and perform final commit. We do this by rolling up
3082  * any subtransactions into their parent, which leads to O(N^2)
3083  * operations with respect to resource owners - this isn't that
3084  * bad until we approach a thousands of savepoints but is
3085  * necessary for correctness should after triggers create new
3086  * resource owners.
3087  */
3088  case TBLOCK_SUBCOMMIT:
3089  do
3090  {
3092  s = CurrentTransactionState; /* changed by pop */
3093  } while (s->blockState == TBLOCK_SUBCOMMIT);
3094  /* If we had a COMMIT command, finish off the main xact too */
3095  if (s->blockState == TBLOCK_END)
3096  {
3097  Assert(s->parent == NULL);
3100  }
3101  else if (s->blockState == TBLOCK_PREPARE)
3102  {
3103  Assert(s->parent == NULL);
3106  }
3107  else
3108  elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3110  break;
3111 
3112  /*
3113  * The current already-failed subtransaction is ending due to a
3114  * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3115  * examine the parent (which could be in any of several states).
3116  */
3117  case TBLOCK_SUBABORT_END:
3120  break;
3121 
3122  /*
3123  * As above, but it's not dead yet, so abort first.
3124  */
3129  break;
3130 
3131  /*
3132  * The current subtransaction is the target of a ROLLBACK TO
3133  * command. Abort and pop it, then start a new subtransaction
3134  * with the same name.
3135  */
3136  case TBLOCK_SUBRESTART:
3137  {
3138  char *name;
3139  int savepointLevel;
3140 
3141  /* save name and keep Cleanup from freeing it */
3142  name = s->name;
3143  s->name = NULL;
3144  savepointLevel = s->savepointLevel;
3145 
3148 
3149  DefineSavepoint(NULL);
3150  s = CurrentTransactionState; /* changed by push */
3151  s->name = name;
3153 
3154  /* This is the same as TBLOCK_SUBBEGIN case */
3158  }
3159  break;
3160 
3161  /*
3162  * Same as above, but the subtransaction had already failed, so we
3163  * don't need AbortSubTransaction.
3164  */
3166  {
3167  char *name;
3168  int savepointLevel;
3169 
3170  /* save name and keep Cleanup from freeing it */
3171  name = s->name;
3172  s->name = NULL;
3173  savepointLevel = s->savepointLevel;
3174 
3176 
3177  DefineSavepoint(NULL);
3178  s = CurrentTransactionState; /* changed by push */
3179  s->name = name;
3181 
3182  /* This is the same as TBLOCK_SUBBEGIN case */
3186  }
3187  break;
3188  }
3189 }
3190 
3191 /*
3192  * AbortCurrentTransaction
3193  */
3194 void
3196 {
3198 
3199  switch (s->blockState)
3200  {
3201  case TBLOCK_DEFAULT:
3202  if (s->state == TRANS_DEFAULT)
3203  {
3204  /* we are idle, so nothing to do */
3205  }
3206  else
3207  {
3208  /*
3209  * We can get here after an error during transaction start
3210  * (state will be TRANS_START). Need to clean up the
3211  * incompletely started transaction. First, adjust the
3212  * low-level state to suppress warning message from
3213  * AbortTransaction.
3214  */
3215  if (s->state == TRANS_START)
3216  s->state = TRANS_INPROGRESS;
3217  AbortTransaction();
3219  }
3220  break;
3221 
3222  /*
3223  * If we aren't in a transaction block, we just do the basic abort
3224  * & cleanup transaction. For this purpose, we treat an implicit
3225  * transaction block as if it were a simple statement.
3226  */
3227  case TBLOCK_STARTED:
3229  AbortTransaction();
3232  break;
3233 
3234  /*
3235  * If we are in TBLOCK_BEGIN it means something screwed up right
3236  * after reading "BEGIN TRANSACTION". We assume that the user
3237  * will interpret the error as meaning the BEGIN failed to get him
3238  * into a transaction block, so we should abort and return to idle
3239  * state.
3240  */
3241  case TBLOCK_BEGIN:
3242  AbortTransaction();
3245  break;
3246 
3247  /*
3248  * We are somewhere in a transaction block and we've gotten a
3249  * failure, so we abort the transaction and set up the persistent
3250  * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3251  */
3252  case TBLOCK_INPROGRESS:
3254  AbortTransaction();
3255  s->blockState = TBLOCK_ABORT;
3256  /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3257  break;
3258 
3259  /*
3260  * Here, we failed while trying to COMMIT. Clean up the
3261  * transaction and return to idle state (we do not want to stay in
3262  * the transaction).
3263  */
3264  case TBLOCK_END:
3265  AbortTransaction();
3268  break;
3269 
3270  /*
3271  * Here, we are already in an aborted transaction state and are
3272  * waiting for a ROLLBACK, but for some reason we failed again! So
3273  * we just remain in the abort state.
3274  */
3275  case TBLOCK_ABORT:
3276  case TBLOCK_SUBABORT:
3277  break;
3278 
3279  /*
3280  * We are in a failed transaction and we got the ROLLBACK command.
3281  * We have already aborted, we just need to cleanup and go to idle
3282  * state.
3283  */
3284  case TBLOCK_ABORT_END:
3287  break;
3288 
3289  /*
3290  * We are in a live transaction and we got a ROLLBACK command.
3291  * Abort, cleanup, go to idle state.
3292  */
3293  case TBLOCK_ABORT_PENDING:
3294  AbortTransaction();
3297  break;
3298 
3299  /*
3300  * Here, we failed while trying to PREPARE. Clean up the
3301  * transaction and return to idle state (we do not want to stay in
3302  * the transaction).
3303  */
3304  case TBLOCK_PREPARE:
3305  AbortTransaction();
3308  break;
3309 
3310  /*
3311  * We got an error inside a subtransaction. Abort just the
3312  * subtransaction, and go to the persistent SUBABORT state until
3313  * we get ROLLBACK.
3314  */
3315  case TBLOCK_SUBINPROGRESS:
3318  break;
3319 
3320  /*
3321  * If we failed while trying to create a subtransaction, clean up
3322  * the broken subtransaction and abort the parent. The same
3323  * applies if we get a failure while ending a subtransaction.
3324  */
3325  case TBLOCK_SUBBEGIN:
3326  case TBLOCK_SUBRELEASE:
3327  case TBLOCK_SUBCOMMIT:
3329  case TBLOCK_SUBRESTART:
3333  break;
3334 
3335  /*
3336  * Same as above, except the Abort() was already done.
3337  */
3338  case TBLOCK_SUBABORT_END:
3342  break;
3343  }
3344 }
3345 
3346 /*
3347  * PreventInTransactionBlock
3348  *
3349  * This routine is to be called by statements that must not run inside
3350  * a transaction block, typically because they have non-rollback-able
3351  * side effects or do internal commits.
3352  *
3353  * If we have already started a transaction block, issue an error; also issue
3354  * an error if we appear to be running inside a user-defined function (which
3355  * could issue more commands and possibly cause a failure after the statement
3356  * completes). Subtransactions are verboten too.
3357  *
3358  * isTopLevel: passed down from ProcessUtility to determine whether we are
3359  * inside a function. (We will always fail if this is false, but it's
3360  * convenient to centralize the check here instead of making callers do it.)
3361  * stmtType: statement type name, for error messages.
3362  */
3363 void
3364 PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3365 {
3366  /*
3367  * xact block already started?
3368  */
3369  if (IsTransactionBlock())
3370  ereport(ERROR,
3371  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3372  /* translator: %s represents an SQL statement name */
3373  errmsg("%s cannot run inside a transaction block",
3374  stmtType)));
3375 
3376  /*
3377  * subtransaction?
3378  */
3379  if (IsSubTransaction())
3380  ereport(ERROR,
3381  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3382  /* translator: %s represents an SQL statement name */
3383  errmsg("%s cannot run inside a subtransaction",
3384  stmtType)));
3385 
3386  /*
3387  * inside a function call?
3388  */
3389  if (!isTopLevel)
3390  ereport(ERROR,
3391  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3392  /* translator: %s represents an SQL statement name */
3393  errmsg("%s cannot be executed from a function", stmtType)));
3394 
3395  /* If we got past IsTransactionBlock test, should be in default state */
3396  if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3397  CurrentTransactionState->blockState != TBLOCK_STARTED)
3398  elog(FATAL, "cannot prevent transaction chain");
3399  /* all okay */
3400 }
3401 
3402 /*
3403  * WarnNoTransactionBlock
3404  * RequireTransactionBlock
3405  *
3406  * These two functions allow for warnings or errors if a command is executed
3407  * outside of a transaction block. This is useful for commands that have no
3408  * effects that persist past transaction end (and so calling them outside a
3409  * transaction block is presumably an error). DECLARE CURSOR is an example.
3410  * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3411  * that have no effect issue warnings, all other no-effect commands generate
3412  * errors.
3413  *
3414  * If we appear to be running inside a user-defined function, we do not
3415  * issue anything, since the function could issue more commands that make
3416  * use of the current statement's results. Likewise subtransactions.
3417  * Thus these are inverses for PreventInTransactionBlock.
3418  *
3419  * isTopLevel: passed down from ProcessUtility to determine whether we are
3420  * inside a function.
3421  * stmtType: statement type name, for warning or error messages.
3422  */
3423 void
3424 WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3425 {
3426  CheckTransactionBlock(isTopLevel, false, stmtType);
3427 }
3428 
3429 void
3430 RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3431 {
3432  CheckTransactionBlock(isTopLevel, true, stmtType);
3433 }
3434 
3435 /*
3436  * This is the implementation of the above two.
3437  */
3438 static void
3439 CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3440 {
3441  /*
3442  * xact block already started?
3443  */
3444  if (IsTransactionBlock())
3445  return;
3446 
3447  /*
3448  * subtransaction?
3449  */
3450  if (IsSubTransaction())
3451  return;
3452 
3453  /*
3454  * inside a function call?
3455  */
3456  if (!isTopLevel)
3457  return;
3458 
3459  ereport(throwError ? ERROR : WARNING,
3460  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3461  /* translator: %s represents an SQL statement name */
3462  errmsg("%s can only be used in transaction blocks",
3463  stmtType)));
3464 }
3465 
3466 /*
3467  * IsInTransactionBlock
3468  *
3469  * This routine is for statements that need to behave differently inside
3470  * a transaction block than when running as single commands. ANALYZE is
3471  * currently the only example.
3472  *
3473  * isTopLevel: passed down from ProcessUtility to determine whether we are
3474  * inside a function.
3475  */
3476 bool
3477 IsInTransactionBlock(bool isTopLevel)
3478 {
3479  /*
3480  * Return true on same conditions that would make
3481  * PreventInTransactionBlock error out
3482  */
3483  if (IsTransactionBlock())
3484  return true;
3485 
3486  if (IsSubTransaction())
3487  return true;
3488 
3489  if (!isTopLevel)
3490  return true;
3491 
3492  if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3493  CurrentTransactionState->blockState != TBLOCK_STARTED)
3494  return true;
3495 
3496  return false;
3497 }
3498 
3499 
3500 /*
3501  * Register or deregister callback functions for start- and end-of-xact
3502  * operations.
3503  *
3504  * These functions are intended for use by dynamically loaded modules.
3505  * For built-in modules we generally just hardwire the appropriate calls
3506  * (mainly because it's easier to control the order that way, where needed).
3507  *
3508  * At transaction end, the callback occurs post-commit or post-abort, so the
3509  * callback functions can only do noncritical cleanup.
3510  */
3511 void
3513 {
3514  XactCallbackItem *item;
3515 
3516  item = (XactCallbackItem *)
3518  item->callback = callback;
3519  item->arg = arg;
3520  item->next = Xact_callbacks;
3521  Xact_callbacks = item;
3522 }
3523 
3524 void
3526 {
3527  XactCallbackItem *item;
3528  XactCallbackItem *prev;
3529 
3530  prev = NULL;
3531  for (item = Xact_callbacks; item; prev = item, item = item->next)
3532  {
3533  if (item->callback == callback && item->arg == arg)
3534  {
3535  if (prev)
3536  prev->next = item->next;
3537  else
3538  Xact_callbacks = item->next;
3539  pfree(item);
3540  break;
3541  }
3542  }
3543 }
3544 
3545 static void
3547 {
3548  XactCallbackItem *item;
3549 
3550  for (item = Xact_callbacks; item; item = item->next)
3551  item->callback(event, item->arg);
3552 }
3553 
3554 
3555 /*
3556  * Register or deregister callback functions for start- and end-of-subxact
3557  * operations.
3558  *
3559  * Pretty much same as above, but for subtransaction events.
3560  *
3561  * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3562  * so the callback functions can only do noncritical cleanup. At
3563  * subtransaction start, the callback is called when the subtransaction has
3564  * finished initializing.
3565  */
3566 void
3568 {
3569  SubXactCallbackItem *item;
3570 
3571  item = (SubXactCallbackItem *)
3573  item->callback = callback;
3574  item->arg = arg;
3575  item->next = SubXact_callbacks;
3576  SubXact_callbacks = item;
3577 }
3578 
3579 void
3581 {
3582  SubXactCallbackItem *item;
3583  SubXactCallbackItem *prev;
3584 
3585  prev = NULL;
3586  for (item = SubXact_callbacks; item; prev = item, item = item->next)
3587  {
3588  if (item->callback == callback && item->arg == arg)
3589  {
3590  if (prev)
3591  prev->next = item->next;
3592  else
3593  SubXact_callbacks = item->next;
3594  pfree(item);
3595  break;
3596  }
3597  }
3598 }
3599 
3600 static void
3602  SubTransactionId mySubid,
3603  SubTransactionId parentSubid)
3604 {
3605  SubXactCallbackItem *item;
3606 
3607  for (item = SubXact_callbacks; item; item = item->next)
3608  item->callback(event, mySubid, parentSubid, item->arg);
3609 }
3610 
3611 
3612 /* ----------------------------------------------------------------
3613  * transaction block support
3614  * ----------------------------------------------------------------
3615  */
3616 
3617 /*
3618  * BeginTransactionBlock
3619  * This executes a BEGIN command.
3620  */
3621 void
3623 {
3625 
3626  switch (s->blockState)
3627  {
3628  /*
3629  * We are not inside a transaction block, so allow one to begin.
3630  */
3631  case TBLOCK_STARTED:
3632  s->blockState = TBLOCK_BEGIN;
3633  break;
3634 
3635  /*
3636  * BEGIN converts an implicit transaction block to a regular one.
3637  * (Note that we allow this even if we've already done some
3638  * commands, which is a bit odd but matches historical practice.)
3639  */
3641  s->blockState = TBLOCK_BEGIN;
3642  break;
3643 
3644  /*
3645  * Already a transaction block in progress.
3646  */
3647  case TBLOCK_INPROGRESS:
3649  case TBLOCK_SUBINPROGRESS:
3650  case TBLOCK_ABORT:
3651  case TBLOCK_SUBABORT:
3652  ereport(WARNING,
3653  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3654  errmsg("there is already a transaction in progress")));
3655  break;
3656 
3657  /* These cases are invalid. */
3658  case TBLOCK_DEFAULT:
3659  case TBLOCK_BEGIN:
3660  case TBLOCK_SUBBEGIN:
3661  case TBLOCK_END:
3662  case TBLOCK_SUBRELEASE:
3663  case TBLOCK_SUBCOMMIT:
3664  case TBLOCK_ABORT_END:
3665  case TBLOCK_SUBABORT_END:
3666  case TBLOCK_ABORT_PENDING:
3668  case TBLOCK_SUBRESTART:
3670  case TBLOCK_PREPARE:
3671  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3673  break;
3674  }
3675 }
3676 
3677 /*
3678  * PrepareTransactionBlock
3679  * This executes a PREPARE command.
3680  *
3681  * Since PREPARE may actually do a ROLLBACK, the result indicates what
3682  * happened: true for PREPARE, false for ROLLBACK.
3683  *
3684  * Note that we don't actually do anything here except change blockState.
3685  * The real work will be done in the upcoming PrepareTransaction().
3686  * We do it this way because it's not convenient to change memory context,
3687  * resource owner, etc while executing inside a Portal.
3688  */
3689 bool
3690 PrepareTransactionBlock(const char *gid)
3691 {
3692  TransactionState s;
3693  bool result;
3694 
3695  /* Set up to commit the current transaction */
3696  result = EndTransactionBlock(false);
3697 
3698  /* If successful, change outer tblock state to PREPARE */
3699  if (result)
3700  {
3702 
3703  while (s->parent != NULL)
3704  s = s->parent;
3705 
3706  if (s->blockState == TBLOCK_END)
3707  {
3708  /* Save GID where PrepareTransaction can find it again */
3710 
3712  }
3713  else
3714  {
3715  /*
3716  * ignore case where we are not in a transaction;
3717  * EndTransactionBlock already issued a warning.
3718  */
3721  /* Don't send back a PREPARE result tag... */
3722  result = false;
3723  }
3724  }
3725 
3726  return result;
3727 }
3728 
3729 /*
3730  * EndTransactionBlock
3731  * This executes a COMMIT command.
3732  *
3733  * Since COMMIT may actually do a ROLLBACK, the result indicates what
3734  * happened: true for COMMIT, false for ROLLBACK.
3735  *
3736  * Note that we don't actually do anything here except change blockState.
3737  * The real work will be done in the upcoming CommitTransactionCommand().
3738  * We do it this way because it's not convenient to change memory context,
3739  * resource owner, etc while executing inside a Portal.
3740  */
3741 bool
3743 {
3745  bool result = false;
3746 
3747  switch (s->blockState)
3748  {
3749  /*
3750  * We are in a transaction block, so tell CommitTransactionCommand
3751  * to COMMIT.
3752  */
3753  case TBLOCK_INPROGRESS:
3754  s->blockState = TBLOCK_END;
3755  result = true;
3756  break;
3757 
3758  /*
3759  * We are in an implicit transaction block. If AND CHAIN was
3760  * specified, error. Otherwise commit, but issue a warning
3761  * because there was no explicit BEGIN before this.
3762  */
3764  if (chain)
3765  ereport(ERROR,
3766  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3767  /* translator: %s represents an SQL statement name */
3768  errmsg("%s can only be used in transaction blocks",
3769  "COMMIT AND CHAIN")));
3770  else
3771  ereport(WARNING,
3772  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3773  errmsg("there is no transaction in progress")));
3774  s->blockState = TBLOCK_END;
3775  result = true;
3776  break;
3777 
3778  /*
3779  * We are in a failed transaction block. Tell
3780  * CommitTransactionCommand it's time to exit the block.
3781  */
3782  case TBLOCK_ABORT:
3784  break;
3785 
3786  /*
3787  * We are in a live subtransaction block. Set up to subcommit all
3788  * open subtransactions and then commit the main transaction.
3789  */
3790  case TBLOCK_SUBINPROGRESS:
3791  while (s->parent != NULL)
3792  {
3793  if (s->blockState == TBLOCK_SUBINPROGRESS)
3795  else
3796  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3798  s = s->parent;
3799  }
3800  if (s->blockState == TBLOCK_INPROGRESS)
3801  s->blockState = TBLOCK_END;
3802  else
3803  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3805  result = true;
3806  break;
3807 
3808  /*
3809  * Here we are inside an aborted subtransaction. Treat the COMMIT
3810  * as ROLLBACK: set up to abort everything and exit the main
3811  * transaction.
3812  */
3813  case TBLOCK_SUBABORT:
3814  while (s->parent != NULL)
3815  {
3816  if (s->blockState == TBLOCK_SUBINPROGRESS)
3818  else if (s->blockState == TBLOCK_SUBABORT)
3820  else
3821  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3823  s = s->parent;
3824  }
3825  if (s->blockState == TBLOCK_INPROGRESS)
3827  else if (s->blockState == TBLOCK_ABORT)
3829  else
3830  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3832  break;
3833 
3834  /*
3835  * The user issued COMMIT when not inside a transaction. For
3836  * COMMIT without CHAIN, issue a WARNING, staying in
3837  * TBLOCK_STARTED state. The upcoming call to
3838  * CommitTransactionCommand() will then close the transaction and
3839  * put us back into the default state. For COMMIT AND CHAIN,
3840  * error.
3841  */
3842  case TBLOCK_STARTED:
3843  if (chain)
3844  ereport(ERROR,
3845  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3846  /* translator: %s represents an SQL statement name */
3847  errmsg("%s can only be used in transaction blocks",
3848  "COMMIT AND CHAIN")));
3849  else
3850  ereport(WARNING,
3851  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3852  errmsg("there is no transaction in progress")));
3853  result = true;
3854  break;
3855 
3856  /*
3857  * The user issued a COMMIT that somehow ran inside a parallel
3858  * worker. We can't cope with that.
3859  */
3861  ereport(FATAL,
3862  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3863  errmsg("cannot commit during a parallel operation")));
3864  break;
3865 
3866  /* These cases are invalid. */
3867  case TBLOCK_DEFAULT:
3868  case TBLOCK_BEGIN:
3869  case TBLOCK_SUBBEGIN:
3870  case TBLOCK_END:
3871  case TBLOCK_SUBRELEASE:
3872  case TBLOCK_SUBCOMMIT:
3873  case TBLOCK_ABORT_END:
3874  case TBLOCK_SUBABORT_END:
3875  case TBLOCK_ABORT_PENDING:
3877  case TBLOCK_SUBRESTART:
3879  case TBLOCK_PREPARE:
3880  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3882  break;
3883  }
3884 
3886  s->blockState == TBLOCK_END ||
3887  s->blockState == TBLOCK_ABORT_END ||
3889 
3890  s->chain = chain;
3891 
3892  return result;
3893 }
3894 
3895 /*
3896  * UserAbortTransactionBlock
3897  * This executes a ROLLBACK command.
3898  *
3899  * As above, we don't actually do anything here except change blockState.
3900  */
3901 void
3903 {
3905 
3906  switch (s->blockState)
3907  {
3908  /*
3909  * We are inside a transaction block and we got a ROLLBACK command
3910  * from the user, so tell CommitTransactionCommand to abort and
3911  * exit the transaction block.
3912  */
3913  case TBLOCK_INPROGRESS:
3915  break;
3916 
3917  /*
3918  * We are inside a failed transaction block and we got a ROLLBACK
3919  * command from the user. Abort processing is already done, so
3920  * CommitTransactionCommand just has to cleanup and go back to
3921  * idle state.
3922  */
3923  case TBLOCK_ABORT:
3925  break;
3926 
3927  /*
3928  * We are inside a subtransaction. Mark everything up to top
3929  * level as exitable.
3930  */
3931  case TBLOCK_SUBINPROGRESS:
3932  case TBLOCK_SUBABORT:
3933  while (s->parent != NULL)
3934  {
3935  if (s->blockState == TBLOCK_SUBINPROGRESS)
3937  else if (s->blockState == TBLOCK_SUBABORT)
3939  else
3940  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3942  s = s->parent;
3943  }
3944  if (s->blockState == TBLOCK_INPROGRESS)
3946  else if (s->blockState == TBLOCK_ABORT)
3948  else
3949  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3951  break;
3952 
3953  /*
3954  * The user issued ABORT when not inside a transaction. For
3955  * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
3956  * The upcoming call to CommitTransactionCommand() will then put
3957  * us back into the default state. For ROLLBACK AND CHAIN, error.
3958  *
3959  * We do the same thing with ABORT inside an implicit transaction,
3960  * although in this case we might be rolling back actual database
3961  * state changes. (It's debatable whether we should issue a
3962  * WARNING in this case, but we have done so historically.)
3963  */
3964  case TBLOCK_STARTED:
3966  if (chain)
3967  ereport(ERROR,
3968  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3969  /* translator: %s represents an SQL statement name */
3970  errmsg("%s can only be used in transaction blocks",
3971  "ROLLBACK AND CHAIN")));
3972  else
3973  ereport(WARNING,
3974  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3975  errmsg("there is no transaction in progress")));
3977  break;
3978 
3979  /*
3980  * The user issued an ABORT that somehow ran inside a parallel
3981  * worker. We can't cope with that.
3982  */
3984  ereport(FATAL,
3985  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3986  errmsg("cannot abort during a parallel operation")));
3987  break;
3988 
3989  /* These cases are invalid. */
3990  case TBLOCK_DEFAULT:
3991  case TBLOCK_BEGIN:
3992  case TBLOCK_SUBBEGIN:
3993  case TBLOCK_END:
3994  case TBLOCK_SUBRELEASE:
3995  case TBLOCK_SUBCOMMIT:
3996  case TBLOCK_ABORT_END:
3997  case TBLOCK_SUBABORT_END:
3998  case TBLOCK_ABORT_PENDING:
4000  case TBLOCK_SUBRESTART:
4002  case TBLOCK_PREPARE:
4003  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4005  break;
4006  }
4007 
4010 
4011  s->chain = chain;
4012 }
4013 
4014 /*
4015  * BeginImplicitTransactionBlock
4016  * Start an implicit transaction block if we're not already in one.
4017  *
4018  * Unlike BeginTransactionBlock, this is called directly from the main loop
4019  * in postgres.c, not within a Portal. So we can just change blockState
4020  * without a lot of ceremony. We do not expect caller to do
4021  * CommitTransactionCommand/StartTransactionCommand.
4022  */
4023 void
4025 {
4027 
4028  /*
4029  * If we are in STARTED state (that is, no transaction block is open),
4030  * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4031  * block.
4032  *
4033  * For caller convenience, we consider all other transaction states as
4034  * legal here; otherwise the caller would need its own state check, which
4035  * seems rather pointless.
4036  */
4037  if (s->blockState == TBLOCK_STARTED)
4039 }
4040 
4041 /*
4042  * EndImplicitTransactionBlock
4043  * End an implicit transaction block, if we're in one.
4044  *
4045  * Like EndTransactionBlock, we just make any needed blockState change here.
4046  * The real work will be done in the upcoming CommitTransactionCommand().
4047  */
4048 void
4050 {
4052 
4053  /*
4054  * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4055  * allowing CommitTransactionCommand to commit whatever happened during
4056  * the implicit transaction block as though it were a single statement.
4057  *
4058  * For caller convenience, we consider all other transaction states as
4059  * legal here; otherwise the caller would need its own state check, which
4060  * seems rather pointless.
4061  */
4064 }
4065 
4066 /*
4067  * DefineSavepoint
4068  * This executes a SAVEPOINT command.
4069  */
4070 void
4071 DefineSavepoint(const char *name)
4072 {
4074 
4075  /*
4076  * Workers synchronize transaction state at the beginning of each parallel
4077  * operation, so we can't account for new subtransactions after that
4078  * point. (Note that this check will certainly error out if s->blockState
4079  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4080  * below.)
4081  */
4082  if (IsInParallelMode())
4083  ereport(ERROR,
4084  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4085  errmsg("cannot define savepoints during a parallel operation")));
4086 
4087  switch (s->blockState)
4088  {
4089  case TBLOCK_INPROGRESS:
4090  case TBLOCK_SUBINPROGRESS:
4091  /* Normal subtransaction start */
4092  PushTransaction();
4093  s = CurrentTransactionState; /* changed by push */
4094 
4095  /*
4096  * Savepoint names, like the TransactionState block itself, live
4097  * in TopTransactionContext.
4098  */
4099  if (name)
4101  break;
4102 
4103  /*
4104  * We disallow savepoint commands in implicit transaction blocks.
4105  * There would be no great difficulty in allowing them so far as
4106  * this module is concerned, but a savepoint seems inconsistent
4107  * with exec_simple_query's behavior of abandoning the whole query
4108  * string upon error. Also, the point of an implicit transaction
4109  * block (as opposed to a regular one) is to automatically close
4110  * after an error, so it's hard to see how a savepoint would fit
4111  * into that.
4112  *
4113  * The error messages for this are phrased as if there were no
4114  * active transaction block at all, which is historical but
4115  * perhaps could be improved.
4116  */
4118  ereport(ERROR,
4119  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4120  /* translator: %s represents an SQL statement name */
4121  errmsg("%s can only be used in transaction blocks",
4122  "SAVEPOINT")));
4123  break;
4124 
4125  /* These cases are invalid. */
4126  case TBLOCK_DEFAULT:
4127  case TBLOCK_STARTED:
4128  case TBLOCK_BEGIN:
4130  case TBLOCK_SUBBEGIN:
4131  case TBLOCK_END:
4132  case TBLOCK_SUBRELEASE:
4133  case TBLOCK_SUBCOMMIT:
4134  case TBLOCK_ABORT:
4135  case TBLOCK_SUBABORT:
4136  case TBLOCK_ABORT_END:
4137  case TBLOCK_SUBABORT_END:
4138  case TBLOCK_ABORT_PENDING:
4140  case TBLOCK_SUBRESTART:
4142  case TBLOCK_PREPARE:
4143  elog(FATAL, "DefineSavepoint: unexpected state %s",
4145  break;
4146  }
4147 }
4148 
4149 /*
4150  * ReleaseSavepoint
4151  * This executes a RELEASE command.
4152  *
4153  * As above, we don't actually do anything here except change blockState.
4154  */
4155 void
4157 {
4159  TransactionState target,
4160  xact;
4161 
4162  /*
4163  * Workers synchronize transaction state at the beginning of each parallel
4164  * operation, so we can't account for transaction state change after that
4165  * point. (Note that this check will certainly error out if s->blockState
4166  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4167  * below.)
4168  */
4169  if (IsInParallelMode())
4170  ereport(ERROR,
4171  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4172  errmsg("cannot release savepoints during a parallel operation")));
4173 
4174  switch (s->blockState)
4175  {
4176  /*
4177  * We can't release a savepoint if there is no savepoint defined.
4178  */
4179  case TBLOCK_INPROGRESS:
4180  ereport(ERROR,
4181  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4182  errmsg("savepoint \"%s\" does not exist", name)));
4183  break;
4184 
4186  /* See comment about implicit transactions in DefineSavepoint */
4187  ereport(ERROR,
4188  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4189  /* translator: %s represents an SQL statement name */
4190  errmsg("%s can only be used in transaction blocks",
4191  "RELEASE SAVEPOINT")));
4192  break;
4193 
4194  /*
4195  * We are in a non-aborted subtransaction. This is the only valid
4196  * case.
4197  */
4198  case TBLOCK_SUBINPROGRESS:
4199  break;
4200 
4201  /* These cases are invalid. */
4202  case TBLOCK_DEFAULT:
4203  case TBLOCK_STARTED:
4204  case TBLOCK_BEGIN:
4206  case TBLOCK_SUBBEGIN:
4207  case TBLOCK_END:
4208  case TBLOCK_SUBRELEASE:
4209  case TBLOCK_SUBCOMMIT:
4210  case TBLOCK_ABORT:
4211  case TBLOCK_SUBABORT:
4212  case TBLOCK_ABORT_END:
4213  case TBLOCK_SUBABORT_END:
4214  case TBLOCK_ABORT_PENDING:
4216  case TBLOCK_SUBRESTART:
4218  case TBLOCK_PREPARE:
4219  elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4221  break;
4222  }
4223 
4224  for (target = s; PointerIsValid(target); target = target->parent)
4225  {
4226  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4227  break;
4228  }
4229 
4230  if (!PointerIsValid(target))
4231  ereport(ERROR,
4232  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4233  errmsg("savepoint \"%s\" does not exist", name)));
4234 
4235  /* disallow crossing savepoint level boundaries */
4236  if (target->savepointLevel != s->savepointLevel)
4237  ereport(ERROR,
4238  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4239  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4240 
4241  /*
4242  * Mark "commit pending" all subtransactions up to the target
4243  * subtransaction. The actual commits will happen when control gets to
4244  * CommitTransactionCommand.
4245  */
4246  xact = CurrentTransactionState;
4247  for (;;)
4248  {
4250  xact->blockState = TBLOCK_SUBRELEASE;
4251  if (xact == target)
4252  break;
4253  xact = xact->parent;
4254  Assert(PointerIsValid(xact));
4255  }
4256 }
4257 
4258 /*
4259  * RollbackToSavepoint
4260  * This executes a ROLLBACK TO <savepoint> command.
4261  *
4262  * As above, we don't actually do anything here except change blockState.
4263  */
4264 void
4266 {
4268  TransactionState target,
4269  xact;
4270 
4271  /*
4272  * Workers synchronize transaction state at the beginning of each parallel
4273  * operation, so we can't account for transaction state change after that
4274  * point. (Note that this check will certainly error out if s->blockState
4275  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4276  * below.)
4277  */
4278  if (IsInParallelMode())
4279  ereport(ERROR,
4280  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4281  errmsg("cannot rollback to savepoints during a parallel operation")));
4282 
4283  switch (s->blockState)
4284  {
4285  /*
4286  * We can't rollback to a savepoint if there is no savepoint
4287  * defined.
4288  */
4289  case TBLOCK_INPROGRESS:
4290  case TBLOCK_ABORT:
4291  ereport(ERROR,
4292  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4293  errmsg("savepoint \"%s\" does not exist", name)));
4294  break;
4295 
4297  /* See comment about implicit transactions in DefineSavepoint */
4298  ereport(ERROR,
4299  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4300  /* translator: %s represents an SQL statement name */
4301  errmsg("%s can only be used in transaction blocks",
4302  "ROLLBACK TO SAVEPOINT")));
4303  break;
4304 
4305  /*
4306  * There is at least one savepoint, so proceed.
4307  */
4308  case TBLOCK_SUBINPROGRESS:
4309  case TBLOCK_SUBABORT:
4310  break;
4311 
4312  /* These cases are invalid. */
4313  case TBLOCK_DEFAULT:
4314  case TBLOCK_STARTED:
4315  case TBLOCK_BEGIN:
4317  case TBLOCK_SUBBEGIN:
4318  case TBLOCK_END:
4319  case TBLOCK_SUBRELEASE:
4320  case TBLOCK_SUBCOMMIT:
4321  case TBLOCK_ABORT_END:
4322  case TBLOCK_SUBABORT_END:
4323  case TBLOCK_ABORT_PENDING:
4325  case TBLOCK_SUBRESTART:
4327  case TBLOCK_PREPARE:
4328  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4330  break;
4331  }
4332 
4333  for (target = s; PointerIsValid(target); target = target->parent)
4334  {
4335  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4336  break;
4337  }
4338 
4339  if (!PointerIsValid(target))
4340  ereport(ERROR,
4341  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4342  errmsg("savepoint \"%s\" does not exist", name)));
4343 
4344  /* disallow crossing savepoint level boundaries */
4345  if (target->savepointLevel != s->savepointLevel)
4346  ereport(ERROR,
4347  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4348  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4349 
4350  /*
4351  * Mark "abort pending" all subtransactions up to the target
4352  * subtransaction. The actual aborts will happen when control gets to
4353  * CommitTransactionCommand.
4354  */
4355  xact = CurrentTransactionState;
4356  for (;;)
4357  {
4358  if (xact == target)
4359  break;
4360  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4362  else if (xact->blockState == TBLOCK_SUBABORT)
4364  else
4365  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4367  xact = xact->parent;
4368  Assert(PointerIsValid(xact));
4369  }
4370 
4371  /* And mark the target as "restart pending" */
4372  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4373  xact->blockState = TBLOCK_SUBRESTART;
4374  else if (xact->blockState == TBLOCK_SUBABORT)
4376  else
4377  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4379 }
4380 
4381 /*
4382  * BeginInternalSubTransaction
4383  * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4384  * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_END, and TBLOCK_PREPARE states,
4385  * and therefore it can safely be used in functions that might be called
4386  * when not inside a BEGIN block or when running deferred triggers at
4387  * COMMIT/PREPARE time. Also, it automatically does
4388  * CommitTransactionCommand/StartTransactionCommand instead of expecting
4389  * the caller to do it.
4390  */
4391 void
4393 {
4395 
4396  /*
4397  * Workers synchronize transaction state at the beginning of each parallel
4398  * operation, so we can't account for new subtransactions after that
4399  * point. We might be able to make an exception for the type of
4400  * subtransaction established by this function, which is typically used in
4401  * contexts where we're going to release or roll back the subtransaction
4402  * before proceeding further, so that no enduring change to the
4403  * transaction state occurs. For now, however, we prohibit this case along
4404  * with all the others.
4405  */
4406  if (IsInParallelMode())
4407  ereport(ERROR,
4408  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4409  errmsg("cannot start subtransactions during a parallel operation")));
4410 
4411  switch (s->blockState)
4412  {
4413  case TBLOCK_STARTED:
4414  case TBLOCK_INPROGRESS:
4416  case TBLOCK_END:
4417  case TBLOCK_PREPARE:
4418  case TBLOCK_SUBINPROGRESS:
4419  /* Normal subtransaction start */
4420  PushTransaction();
4421  s = CurrentTransactionState; /* changed by push */
4422 
4423  /*
4424  * Savepoint names, like the TransactionState block itself, live
4425  * in TopTransactionContext.
4426  */
4427  if (name)
4429  break;
4430 
4431  /* These cases are invalid. */
4432  case TBLOCK_DEFAULT:
4433  case TBLOCK_BEGIN:
4435  case TBLOCK_SUBBEGIN:
4436  case TBLOCK_SUBRELEASE:
4437  case TBLOCK_SUBCOMMIT:
4438  case TBLOCK_ABORT:
4439  case TBLOCK_SUBABORT:
4440  case TBLOCK_ABORT_END:
4441  case TBLOCK_SUBABORT_END:
4442  case TBLOCK_ABORT_PENDING:
4444  case TBLOCK_SUBRESTART:
4446  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4448  break;
4449  }
4450 
4453 }
4454 
4455 /*
4456  * ReleaseCurrentSubTransaction
4457  *
4458  * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4459  * savepoint name (if any).
4460  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4461  */
4462 void
4464 {
4466 
4467  /*
4468  * Workers synchronize transaction state at the beginning of each parallel
4469  * operation, so we can't account for commit of subtransactions after that
4470  * point. This should not happen anyway. Code calling this would
4471  * typically have called BeginInternalSubTransaction() first, failing
4472  * there.
4473  */
4474  if (IsInParallelMode())
4475  ereport(ERROR,
4476  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4477  errmsg("cannot commit subtransactions during a parallel operation")));
4478 
4479  if (s->blockState != TBLOCK_SUBINPROGRESS)
4480  elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4482  Assert(s->state == TRANS_INPROGRESS);
4485  s = CurrentTransactionState; /* changed by pop */
4486  Assert(s->state == TRANS_INPROGRESS);
4487 }
4488 
4489 /*
4490  * RollbackAndReleaseCurrentSubTransaction
4491  *
4492  * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4493  * of its savepoint name (if any).
4494  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4495  */
4496 void
4498 {
4500 
4501  /*
4502  * Unlike ReleaseCurrentSubTransaction(), this is nominally permitted
4503  * during parallel operations. That's because we may be in the leader,
4504  * recovering from an error thrown while we were in parallel mode. We
4505  * won't reach here in a worker, because BeginInternalSubTransaction()
4506  * will have failed.
4507  */
4508 
4509  switch (s->blockState)
4510  {
4511  /* Must be in a subtransaction */
4512  case TBLOCK_SUBINPROGRESS:
4513  case TBLOCK_SUBABORT:
4514  break;
4515 
4516  /* These cases are invalid. */
4517  case TBLOCK_DEFAULT:
4518  case TBLOCK_STARTED:
4519  case TBLOCK_BEGIN:
4522  case TBLOCK_SUBBEGIN:
4523  case TBLOCK_INPROGRESS:
4524  case TBLOCK_END:
4525  case TBLOCK_SUBRELEASE:
4526  case TBLOCK_SUBCOMMIT:
4527  case TBLOCK_ABORT:
4528  case TBLOCK_ABORT_END:
4529  case TBLOCK_SUBABORT_END:
4530  case TBLOCK_ABORT_PENDING:
4532  case TBLOCK_SUBRESTART:
4534  case TBLOCK_PREPARE:
4535  elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4537  break;
4538  }
4539 
4540  /*
4541  * Abort the current subtransaction, if needed.
4542  */
4543  if (s->blockState == TBLOCK_SUBINPROGRESS)
4545 
4546  /* And clean it up, too */
4548 
4549  s = CurrentTransactionState; /* changed by pop */
4551  s->blockState == TBLOCK_INPROGRESS ||
4553  s->blockState == TBLOCK_STARTED);
4554 }
4555 
4556 /*
4557  * AbortOutOfAnyTransaction
4558  *
4559  * This routine is provided for error recovery purposes. It aborts any
4560  * active transaction or transaction block, leaving the system in a known
4561  * idle state.
4562  */
4563 void
4565 {
4567 
4568  /* Ensure we're not running in a doomed memory context */
4569  AtAbort_Memory();
4570 
4571  /*
4572  * Get out of any transaction or nested transaction
4573  */
4574  do
4575  {
4576  switch (s->blockState)
4577  {
4578  case TBLOCK_DEFAULT:
4579  if (s->state == TRANS_DEFAULT)
4580  {
4581  /* Not in a transaction, do nothing */
4582  }
4583  else
4584  {
4585  /*
4586  * We can get here after an error during transaction start
4587  * (state will be TRANS_START). Need to clean up the
4588  * incompletely started transaction. First, adjust the
4589  * low-level state to suppress warning message from
4590  * AbortTransaction.
4591  */
4592  if (s->state == TRANS_START)
4593  s->state = TRANS_INPROGRESS;
4594  AbortTransaction();
4596  }
4597  break;
4598  case TBLOCK_STARTED:
4599  case TBLOCK_BEGIN:
4600  case TBLOCK_INPROGRESS:
4603  case TBLOCK_END:
4604  case TBLOCK_ABORT_PENDING:
4605  case TBLOCK_PREPARE:
4606  /* In a transaction, so clean up */
4607  AbortTransaction();
4610  break;
4611  case TBLOCK_ABORT:
4612  case TBLOCK_ABORT_END:
4613 
4614  /*
4615  * AbortTransaction is already done, still need Cleanup.
4616  * However, if we failed partway through running ROLLBACK,
4617  * there will be an active portal running that command, which
4618  * we need to shut down before doing CleanupTransaction.
4619  */
4620  AtAbort_Portals();
4623  break;
4624 
4625  /*
4626  * In a subtransaction, so clean it up and abort parent too
4627  */
4628  case TBLOCK_SUBBEGIN:
4629  case TBLOCK_SUBINPROGRESS:
4630  case TBLOCK_SUBRELEASE:
4631  case TBLOCK_SUBCOMMIT:
4633  case TBLOCK_SUBRESTART:
4636  s = CurrentTransactionState; /* changed by pop */
4637  break;
4638 
4639  case TBLOCK_SUBABORT:
4640  case TBLOCK_SUBABORT_END:
4642  /* As above, but AbortSubTransaction already done */
4643  if (s->curTransactionOwner)
4644  {
4645  /* As in TBLOCK_ABORT, might have a live portal to zap */
4650  }
4652  s = CurrentTransactionState; /* changed by pop */
4653  break;
4654  }
4655  } while (s->blockState != TBLOCK_DEFAULT);
4656 
4657  /* Should be out of all subxacts now */
4658  Assert(s->parent == NULL);
4659 
4660  /* If we didn't actually have anything to do, revert to TopMemoryContext */
4661  AtCleanup_Memory();
4662 }
4663 
4664 /*
4665  * IsTransactionBlock --- are we within a transaction block?
4666  */
4667 bool
4669 {
4671 
4673  return false;
4674 
4675  return true;
4676 }
4677 
4678 /*
4679  * IsTransactionOrTransactionBlock --- are we within either a transaction
4680  * or a transaction block? (The backend is only really "idle" when this
4681  * returns false.)
4682  *
4683  * This should match up with IsTransactionBlock and IsTransactionState.
4684  */
4685 bool
4687 {
4689 
4690  if (s->blockState == TBLOCK_DEFAULT)
4691  return false;
4692 
4693  return true;
4694 }
4695 
4696 /*
4697  * TransactionBlockStatusCode - return status code to send in ReadyForQuery
4698  */
4699 char
4701 {
4703 
4704  switch (s->blockState)
4705  {
4706  case TBLOCK_DEFAULT:
4707  case TBLOCK_STARTED:
4708  return 'I'; /* idle --- not in transaction */
4709  case TBLOCK_BEGIN:
4710  case TBLOCK_SUBBEGIN:
4711  case TBLOCK_INPROGRESS:
4714  case TBLOCK_SUBINPROGRESS:
4715  case TBLOCK_END:
4716  case TBLOCK_SUBRELEASE:
4717  case TBLOCK_SUBCOMMIT:
4718  case TBLOCK_PREPARE:
4719  return 'T'; /* in transaction */
4720  case TBLOCK_ABORT:
4721  case TBLOCK_SUBABORT:
4722  case TBLOCK_ABORT_END:
4723  case TBLOCK_SUBABORT_END:
4724  case TBLOCK_ABORT_PENDING:
4726  case TBLOCK_SUBRESTART:
4728  return 'E'; /* in failed transaction */
4729  }
4730 
4731  /* should never get here */
4732  elog(FATAL, "invalid transaction block state: %s",
4734  return 0; /* keep compiler quiet */
4735 }
4736 
4737 /*
4738  * IsSubTransaction
4739  */
4740 bool
4742 {
4744 
4745  if (s->nestingLevel >= 2)
4746  return true;
4747 
4748  return false;
4749 }
4750 
4751 /*
4752  * StartSubTransaction
4753  *
4754  * If you're wondering why this is separate from PushTransaction: it's because
4755  * we can't conveniently do this stuff right inside DefineSavepoint. The
4756  * SAVEPOINT utility command will be executed inside a Portal, and if we
4757  * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
4758  * the Portal will undo those settings. So we make DefineSavepoint just
4759  * push a dummy transaction block, and when control returns to the main
4760  * idle loop, CommitTransactionCommand will be called, and we'll come here
4761  * to finish starting the subtransaction.
4762  */
4763 static void
4765 {
4767 
4768  if (s->state != TRANS_DEFAULT)
4769  elog(WARNING, "StartSubTransaction while in %s state",
4771 
4772  s->state = TRANS_START;
4773 
4774  /*
4775  * Initialize subsystems for new subtransaction
4776  *
4777  * must initialize resource-management stuff first
4778  */
4782 
4783  s->state = TRANS_INPROGRESS;
4784 
4785  /*
4786  * Call start-of-subxact callbacks
4787  */
4789  s->parent->subTransactionId);
4790 
4791  ShowTransactionState("StartSubTransaction");
4792 }
4793 
4794 /*
4795  * CommitSubTransaction
4796  *
4797  * The caller has to make sure to always reassign CurrentTransactionState
4798  * if it has a local pointer to it after calling this function.
4799  */
4800 static void
4802 {
4804 
4805  ShowTransactionState("CommitSubTransaction");
4806 
4807  if (s->state != TRANS_INPROGRESS)
4808  elog(WARNING, "CommitSubTransaction while in %s state",
4810 
4811  /* Pre-commit processing goes here */
4812 
4814  s->parent->subTransactionId);
4815 
4816  /* If in parallel mode, clean up workers and exit parallel mode. */
4817  if (IsInParallelMode())
4818  {
4820  s->parallelModeLevel = 0;
4821  }
4822 
4823  /* Do the actual "commit", such as it is */
4824  s->state = TRANS_COMMIT;
4825 
4826  /* Must CCI to ensure commands of subtransaction are seen as done */
4828 
4829  /*
4830  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4831  * perform that step, if required, as part of the atomic update of the
4832  * whole transaction tree at top level commit or abort.
4833  */
4834 
4835  /* Post-commit cleanup */
4838  AfterTriggerEndSubXact(true);
4843  s->parent->subTransactionId);
4845 
4847  s->parent->subTransactionId);
4848 
4851  true, false);
4853  s->parent->subTransactionId);
4854  AtEOSubXact_Inval(true);
4855  AtSubCommit_smgr();
4856 
4857  /*
4858  * The only lock we actually release here is the subtransaction XID lock.
4859  */
4863 
4864  /*
4865  * Other locks should get transferred to their parent resource owner.
4866  */
4869  true, false);
4872  true, false);
4873 
4874  AtEOXact_GUC(true, s->gucNestLevel);
4877  s->parent->subTransactionId);
4879  s->parent->subTransactionId);
4881  s->parent->subTransactionId);
4883  AtEOSubXact_PgStat(true, s->nestingLevel);
4886 
4887  /*
4888  * We need to restore the upper transaction's read-only state, in case the
4889  * upper is read-write while the child is read-only; GUC will incorrectly
4890  * think it should leave the child state in place.
4891  */
4893 
4897  s->curTransactionOwner = NULL;
4898 
4900 
4901  s->state = TRANS_DEFAULT;
4902 
4903  PopTransaction();
4904 }
4905 
4906 /*
4907  * AbortSubTransaction
4908  */
4909 static void
4911 {
4913 
4914  /* Prevent cancel/die interrupt while cleaning up */
4915  HOLD_INTERRUPTS();
4916 
4917  /* Make sure we have a valid memory context and resource owner */
4920 
4921  /*
4922  * Release any LW locks we might be holding as quickly as possible.
4923  * (Regular locks, however, must be held till we finish aborting.)
4924  * Releasing LW locks is critical since we might try to grab them again
4925  * while cleaning up!
4926  *
4927  * FIXME This may be incorrect --- Are there some locks we should keep?
4928  * Buffer locks, for example? I don't think so but I'm not sure.
4929  */
4930  LWLockReleaseAll();
4931 
4934  AbortBufferIO();
4935  UnlockBuffers();
4936 
4937  /* Reset WAL record construction state */
4939 
4940  /* Cancel condition variable sleep */
4942 
4943  /*
4944  * Also clean up any open wait for lock, since the lock manager will choke
4945  * if we try to wait for another lock before doing this.
4946  */
4947  LockErrorCleanup();
4948 
4949  /*
4950  * If any timeout events are still active, make sure the timeout interrupt
4951  * is scheduled. This covers possible loss of a timeout interrupt due to
4952  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4953  * We delay this till after LockErrorCleanup so that we don't uselessly
4954  * reschedule lock or deadlock check timeouts.
4955  */
4957 
4958  /*
4959  * Re-enable signals, in case we got here by longjmp'ing out of a signal
4960  * handler. We do this fairly early in the sequence so that the timeout
4961  * infrastructure will be functional if needed while aborting.
4962  */
4964 
4965  /*
4966  * check the current transaction state
4967  */
4968  ShowTransactionState("AbortSubTransaction");
4969 
4970  if (s->state != TRANS_INPROGRESS)
4971  elog(WARNING, "AbortSubTransaction while in %s state",
4973 
4974  s->state = TRANS_ABORT;
4975 
4976  /*
4977  * Reset user ID which might have been changed transiently. (See notes in
4978  * AbortTransaction.)
4979  */
4981 
4982  /* Forget about any active REINDEX. */
4984 
4985  /* Exit from parallel mode, if necessary. */
4986  if (IsInParallelMode())
4987  {
4989  s->parallelModeLevel = 0;
4990  }
4991 
4992  /*
4993  * We can skip all this stuff if the subxact failed before creating a
4994  * ResourceOwner...
4995  */
4996  if (s->curTransactionOwner)
4997  {
4998  AfterTriggerEndSubXact(false);
5004  s->parent->subTransactionId);
5006 
5007  /* Advertise the fact that we aborted in pg_xact. */
5008  (void) RecordTransactionAbort(true);
5009 
5010  /* Post-abort cleanup */
5013 
5015  s->parent->subTransactionId);
5016 
5019  false, false);
5021  s->parent->subTransactionId);
5022  AtEOSubXact_Inval(false);
5025  false, false);
5028  false, false);
5029  AtSubAbort_smgr();
5030 
5031  AtEOXact_GUC(false, s->gucNestLevel);
5032  AtEOSubXact_SPI(false, s->subTransactionId);
5034  s->parent->subTransactionId);
5036  s->parent->subTransactionId);
5038  s->parent->subTransactionId);
5040  AtEOSubXact_PgStat(false, s->nestingLevel);
5043  }
5044 
5045  /*
5046  * Restore the upper transaction's read-only state, too. This should be
5047  * redundant with GUC's cleanup but we may as well do it for consistency
5048  * with the commit case.
5049  */
5051 
5053 }
5054 
5055 /*
5056  * CleanupSubTransaction
5057  *
5058  * The caller has to make sure to always reassign CurrentTransactionState
5059  * if it has a local pointer to it after calling this function.
5060  */
5061 static void
5063 {
5065 
5066  ShowTransactionState("CleanupSubTransaction");
5067 
5068  if (s->state != TRANS_ABORT)
5069  elog(WARNING, "CleanupSubTransaction while in %s state",
5071 
5073 
5076  if (s->curTransactionOwner)
5078  s->curTransactionOwner = NULL;
5079 
5081 
5082  s->state = TRANS_DEFAULT;
5083 
5084  PopTransaction();
5085 }
5086 
5087 /*
5088  * PushTransaction
5089  * Create transaction state stack entry for a subtransaction
5090  *
5091  * The caller has to make sure to always reassign CurrentTransactionState
5092  * if it has a local pointer to it after calling this function.
5093  */
5094 static void
5096 {
5098  TransactionState s;
5099 
5100  /*
5101  * We keep subtransaction state nodes in TopTransactionContext.
5102  */
5103  s = (TransactionState)
5105  sizeof(TransactionStateData));
5106 
5107  /*
5108  * Assign a subtransaction ID, watching out for counter wraparound.
5109  */
5112  {
5114  pfree(s);
5115  ereport(ERROR,
5116  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5117  errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5118  }
5119 
5120  /*
5121  * We can now stack a minimally valid subtransaction without fear of
5122  * failure.
5123  */
5124  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5126  s->parent = p;
5127  s->nestingLevel = p->nestingLevel + 1;
5130  s->state = TRANS_DEFAULT;
5134  s->parallelModeLevel = 0;
5135  s->assigned = false;
5136 
5137  CurrentTransactionState = s;
5138 
5139  /*
5140  * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5141  * with the subtransaction from here on out; in particular they should not
5142  * assume that it necessarily has a transaction context, resource owner,
5143  * or XID.
5144  */
5145 }
5146 
5147 /*
5148  * PopTransaction
5149  * Pop back to parent transaction state
5150  *
5151  * The caller has to make sure to always reassign CurrentTransactionState
5152  * if it has a local pointer to it after calling this function.
5153  */
5154 static void
5156 {
5158 
5159  if (s->state != TRANS_DEFAULT)
5160  elog(WARNING, "PopTransaction while in %s state",
5162 
5163  if (s->parent == NULL)
5164  elog(FATAL, "PopTransaction with no parent");
5165 
5166  CurrentTransactionState = s->parent;
5167 
5168  /* Let's just make sure CurTransactionContext is good */
5171 
5172  /* Ditto for ResourceOwner links */
5175 
5176  /* Free the old child structure */
5177  if (s->name)
5178  pfree(s->name);
5179  pfree(s);
5180 }
5181 
5182 /*
5183  * EstimateTransactionStateSpace
5184  * Estimate the amount of space that will be needed by
5185  * SerializeTransactionState. It would be OK to overestimate slightly,
5186  * but it's simple for us to work out the precise value, so we do.
5187  */
5188 Size
5190 {
5191  TransactionState s;
5192  Size nxids = 0;
5194 
5195  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5196  {
5198  nxids = add_size(nxids, 1);
5199  nxids = add_size(nxids, s->nChildXids);
5200  }
5201 
5202  return add_size(size, mul_size(sizeof(TransactionId), nxids));
5203 }
5204 
5205 /*
5206  * SerializeTransactionState
5207  * Write out relevant details of our transaction state that will be
5208  * needed by a parallel worker.
5209  *
5210  * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5211  * associated with this transaction. These are serialized into a
5212  * caller-supplied buffer big enough to hold the number of bytes reported by
5213  * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5214  * convenience of the receiving process.
5215  */
5216 void
5217 SerializeTransactionState(Size maxsize, char *start_address)
5218 {
5219  TransactionState s;
5220  Size nxids = 0;
5221  Size i = 0;
5222  TransactionId *workspace;
5224 
5225  result = (SerializedTransactionState *) start_address;
5226 
5227  result->xactIsoLevel = XactIsoLevel;
5228  result->xactDeferrable = XactDeferrable;
5230  result->currentFullTransactionId =
5231  CurrentTransactionState->fullTransactionId;
5233 
5234  /*
5235  * If we're running in a parallel worker and launching a parallel worker
5236  * of our own, we can just pass along the information that was passed to
5237  * us.
5238  */
5239  if (nParallelCurrentXids > 0)
5240  {
5242  memcpy(&result->parallelCurrentXids[0], ParallelCurrentXids,
5244  return;
5245  }
5246 
5247  /*
5248  * OK, we need to generate a sorted list of XIDs that our workers should
5249  * view as current. First, figure out how many there are.
5250  */
5251  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5252  {
5254  nxids = add_size(nxids, 1);
5255  nxids = add_size(nxids, s->nChildXids);
5256  }
5258  <= maxsize);
5259 
5260  /* Copy them to our scratch space. */
5261  workspace = palloc(nxids * sizeof(TransactionId));
5262  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5263  {
5265  workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
5266  memcpy(&workspace[i], s->childXids,
5267  s->nChildXids * sizeof(TransactionId));
5268  i += s->nChildXids;
5269  }
5270  Assert(i == nxids);
5271 
5272  /* Sort them. */
5273  qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5274 
5275  /* Copy data into output area. */
5276  result->nParallelCurrentXids = nxids;
5277  memcpy(&result->parallelCurrentXids[0], workspace,
5278  nxids * sizeof(TransactionId));
5279 }
5280 
5281 /*
5282  * StartParallelWorkerTransaction
5283  * Start a parallel worker transaction, restoring the relevant
5284  * transaction state serialized by SerializeTransactionState.
5285  */
5286 void
5288 {
5290 
5291  Assert(CurrentTransactionState->blockState == TBLOCK_DEFAULT);
5292  StartTransaction();
5293 
5294  tstate = (SerializedTransactionState *) tstatespace;
5295  XactIsoLevel = tstate->xactIsoLevel;
5296  XactDeferrable = tstate->xactDeferrable;
5297  XactTopFullTransactionId = tstate->topFullTransactionId;
5298  CurrentTransactionState->fullTransactionId =
5299  tstate->currentFullTransactionId;
5303 
5304  CurrentTransactionState->blockState = TBLOCK_PARALLEL_INPROGRESS;
5305 }
5306 
5307 /*
5308  * EndParallelWorkerTransaction
5309  * End a parallel worker transaction.
5310  */
5311 void
5313 {
5314  Assert(CurrentTransactionState->blockState == TBLOCK_PARALLEL_INPROGRESS);
5316  CurrentTransactionState->blockState = TBLOCK_DEFAULT;
5317 }
5318 
5319 /*
5320  * ShowTransactionState
5321  * Debug support
5322  */
5323 static void
5325 {
5326  /* skip work if message will definitely not be printed */
5328  ShowTransactionStateRec(str, CurrentTransactionState);
5329 }
5330 
5331 /*
5332  * ShowTransactionStateRec
5333  * Recursive subroutine for ShowTransactionState
5334  */
5335 static void
5337 {
5339 
5340  initStringInfo(&buf);
5341 
5342  if (s->nChildXids > 0)
5343  {
5344  int i;
5345 
5346  appendStringInfo(&buf, ", children: %u", s->childXids[0]);
5347  for (i = 1; i < s->nChildXids; i++)
5348  appendStringInfo(&buf, " %u", s->childXids[i]);
5349  }
5350 
5351  if (s->parent)
5353 
5354  /* use ereport to suppress computation if msg will not be printed */
5355  ereport(DEBUG5,
5356  (errmsg_internal("%s(%d) name: %s; blockState: %s; state: %s, xid/subid/cid: %u/%u/%u%s%s",
5357  str, s->nestingLevel,
5358  PointerIsValid(s->name) ? s->name : "unnamed",
5361  (unsigned int) XidFromFullTransactionId(s->fullTransactionId),
5362  (unsigned int) s->subTransactionId,
5363  (unsigned int) currentCommandId,
5364  currentCommandIdUsed ? " (used)" : "",
5365  buf.data)));
5366 
5367  pfree(buf.data);
5368 }
5369 
5370 /*
5371  * BlockStateAsString
5372  * Debug support
5373  */
5374 static const char *
5376 {
5377  switch (blockState)
5378  {
5379  case TBLOCK_DEFAULT:
5380  return "DEFAULT";
5381  case TBLOCK_STARTED:
5382  return "STARTED";
5383  case TBLOCK_BEGIN:
5384  return "BEGIN";
5385  case TBLOCK_INPROGRESS:
5386  return "INPROGRESS";
5388  return "IMPLICIT_INPROGRESS";
5390  return "PARALLEL_INPROGRESS";
5391  case TBLOCK_END:
5392  return "END";
5393  case TBLOCK_ABORT:
5394  return "ABORT";
5395  case TBLOCK_ABORT_END:
5396  return "ABORT_END";
5397  case TBLOCK_ABORT_PENDING:
5398  return "ABORT_PENDING";
5399  case TBLOCK_PREPARE:
5400  return "PREPARE";
5401  case TBLOCK_SUBBEGIN:
5402  return "SUBBEGIN";
5403  case TBLOCK_SUBINPROGRESS:
5404  return "SUBINPROGRESS";
5405  case TBLOCK_SUBRELEASE:
5406  return "SUBRELEASE";
5407  case TBLOCK_SUBCOMMIT:
5408  return "SUBCOMMIT";
5409  case TBLOCK_SUBABORT:
5410  return "SUBABORT";
5411  case TBLOCK_SUBABORT_END:
5412  return "SUBABORT_END";
5414  return "SUBABORT_PENDING";
5415  case TBLOCK_SUBRESTART:
5416  return "SUBRESTART";
5418  return "SUBABORT_RESTART";
5419  }
5420  return "UNRECOGNIZED";
5421 }
5422 
5423 /*
5424  * TransStateAsString
5425  * Debug support
5426  */
5427 static const char *
5429 {
5430  switch (state)
5431  {
5432  case TRANS_DEFAULT:
5433  return "DEFAULT";
5434  case TRANS_START:
5435  return "START";
5436  case TRANS_INPROGRESS:
5437  return "INPROGRESS";
5438  case TRANS_COMMIT:
5439  return "COMMIT";
5440  case TRANS_ABORT:
5441  return "ABORT";
5442  case TRANS_PREPARE:
5443  return "PREPARE";
5444  }
5445  return "UNRECOGNIZED";
5446 }
5447 
5448 /*
5449  * xactGetCommittedChildren
5450  *
5451  * Gets the list of committed children of the current transaction. The return
5452  * value is the number of child transactions. *ptr is set to point to an
5453  * array of TransactionIds. The array is allocated in TopTransactionContext;
5454  * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
5455  * If there are no subxacts, *ptr is set to NULL.
5456  */
5457 int
5459 {
5461 
5462  if (s->nChildXids == 0)
5463  *ptr = NULL;
5464  else
5465  *ptr = s->childXids;
5466 
5467  return s->nChildXids;
5468 }
5469 
5470 /*
5471  * XLOG support routines
5472  */
5473 
5474 
5475 /*
5476  * Log the commit record for a plain or twophase transaction commit.
5477  *
5478  * A 2pc commit will be emitted when twophase_xid is valid, a plain one
5479  * otherwise.
5480  */
5481 XLogRecPtr
5483  int nsubxacts, TransactionId *subxacts,
5484  int nrels, RelFileNode *rels,
5485  int nmsgs, SharedInvalidationMessage *msgs,
5486  bool relcacheInval,
5487  int xactflags, TransactionId twophase_xid,
5488  const char *twophase_gid)
5489 {
5490  xl_xact_commit xlrec;
5491  xl_xact_xinfo xl_xinfo;
5492  xl_xact_dbinfo xl_dbinfo;
5493  xl_xact_subxacts xl_subxacts;
5494  xl_xact_relfilenodes xl_relfilenodes;
5495  xl_xact_invals xl_invals;
5496  xl_xact_twophase xl_twophase;
5497  xl_xact_origin xl_origin;
5498  uint8 info;
5499 
5500  Assert(CritSectionCount > 0);
5501 
5502  xl_xinfo.xinfo = 0;
5503 
5504  /* decide between a plain and 2pc commit */
5505  if (!TransactionIdIsValid(twophase_xid))
5506  info = XLOG_XACT_COMMIT;
5507  else
5509 
5510  /* First figure out and collect all the information needed */
5511 
5512  xlrec.xact_time = commit_time;
5513 
5514  if (relcacheInval)
5516  if (forceSyncCommit)
5518  if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5519  xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5520 
5521  /*
5522  * Check if the caller would like to ask standbys for immediate feedback
5523  * once this commit is applied.
5524  */
5527 
5528  /*
5529  * Relcache invalidations requires information about the current database
5530  * and so does logical decoding.
5531  */
5532  if (nmsgs > 0 || XLogLogicalInfoActive())
5533  {
5534  xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
5535  xl_dbinfo.dbId = MyDatabaseId;
5536  xl_dbinfo.tsId = MyDatabaseTableSpace;
5537  }
5538 
5539  if (nsubxacts > 0)
5540  {
5541  xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
5542  xl_subxacts.nsubxacts = nsubxacts;
5543  }
5544 
5545  if (nrels > 0)
5546  {
5547  xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILENODES;
5548  xl_relfilenodes.nrels = nrels;
5549  }
5550 
5551  if (nmsgs > 0)
5552  {
5553  xl_xinfo.xinfo |= XACT_XINFO_HAS_INVALS;
5554  xl_invals.nmsgs = nmsgs;
5555  }
5556 
5557  if (TransactionIdIsValid(twophase_xid))
5558  {
5559  xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
5560  xl_twophase.xid = twophase_xid;
5561  Assert(twophase_gid != NULL);
5562 
5563  if (XLogLogicalInfoActive())
5564  xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
5565  }
5566 
5567  /* dump transaction origin information */
5569  {
5570  xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
5571 
5574  }
5575 
5576  if (xl_xinfo.xinfo != 0)
5577  info |= XLOG_XACT_HAS_INFO;
5578 
5579  /* Then include all the collected data into the commit record. */
5580 
5581  XLogBeginInsert();
5582 
5583  XLogRegisterData((char *) (&xlrec), sizeof(xl_xact_commit));
5584 
5585  if (xl_xinfo.xinfo != 0)
5586  XLogRegisterData((char *) (&xl_xinfo.xinfo), sizeof(xl_xinfo.xinfo));
5587 
5588  if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
5589  XLogRegisterData((char *) (&xl_dbinfo), sizeof(xl_dbinfo));
5590 
5591  if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
5592  {
5593  XLogRegisterData((char *) (&xl_subxacts),
5595  XLogRegisterData((char *) subxacts,
5596  nsubxacts * sizeof(TransactionId));
5597  }
5598 
5599  if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILENODES)
5600  {
5601  XLogRegisterData((char *) (&xl_relfilenodes),
5603  XLogRegisterData((char *) rels,
5604  nrels * sizeof(RelFileNode));
5605  }
5606 
5607  if (xl_xinfo.xinfo & XACT_XINFO_HAS_INVALS)
5608  {
5609  XLogRegisterData((char *) (&xl_invals), MinSizeOfXactInvals);
5610  XLogRegisterData((char *) msgs,
5611  nmsgs * sizeof(SharedInvalidationMessage));
5612  }
5613 
5614  if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
5615  {
5616  XLogRegisterData((char *) (&xl_twophase), sizeof(xl_xact_twophase));
5617  if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
5618  XLogRegisterData(unconstify(char *, twophase_gid), strlen(twophase_gid) + 1);
5619  }
5620 
5621  if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
5622  XLogRegisterData((char *) (&xl_origin), sizeof(xl_xact_origin));
5623 
5624  /* we allow filtering by xacts */
5626 
5627  return XLogInsert(RM_XACT_ID, info);
5628 }
5629 
5630 /*
5631  * Log the commit record for a plain or twophase transaction abort.
5632  *
5633  * A 2pc abort will be emitted when twophase_xid is valid, a plain one
5634  * otherwise.
5635  */
5636 XLogRecPtr
5638  int nsubxacts, TransactionId *subxacts,
5639  int nrels, RelFileNode *rels,
5640  int xactflags, TransactionId twophase_xid,
5641  const char *twophase_gid)
5642 {
5643  xl_xact_abort xlrec;
5644  xl_xact_xinfo xl_xinfo;
5645  xl_xact_subxacts xl_subxacts;
5646  xl_xact_relfilenodes xl_relfilenodes;
5647  xl_xact_twophase xl_twophase;
5648  xl_xact_dbinfo xl_dbinfo;
5649  xl_xact_origin xl_origin;
5650 
5651  uint8 info;
5652 
5653  Assert(CritSectionCount > 0);
5654 
5655  xl_xinfo.xinfo = 0;
5656 
5657  /* decide between a plain and 2pc abort */
5658  if (!TransactionIdIsValid(twophase_xid))
5659  info = XLOG_XACT_ABORT;
5660  else
5661  info = XLOG_XACT_ABORT_PREPARED;
5662 
5663 
5664  /* First figure out and collect all the information needed */
5665 
5666  xlrec.xact_time = abort_time;
5667 
5668  if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5669  xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5670 
5671  if (nsubxacts > 0)
5672  {
5673  xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
5674  xl_subxacts.nsubxacts = nsubxacts;
5675  }
5676 
5677  if (nrels > 0)
5678  {
5679  xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILENODES;
5680  xl_relfilenodes.nrels = nrels;
5681  }
5682 
5683  if (TransactionIdIsValid(twophase_xid))
5684  {
5685  xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
5686  xl_twophase.xid = twophase_xid;
5687  Assert(twophase_gid != NULL);
5688 
5689  if (XLogLogicalInfoActive())
5690  xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
5691  }
5692 
5693  if (TransactionIdIsValid(twophase_xid) && XLogLogicalInfoActive())
5694  {
5695  xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
5696  xl_dbinfo.dbId = MyDatabaseId;
5697  xl_dbinfo.tsId = MyDatabaseTableSpace;
5698  }
5699 
5700  /* dump transaction origin information only for abort prepared */
5702  TransactionIdIsValid(twophase_xid) &&
5704  {
5705  xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
5706 
5709  }
5710 
5711  if (xl_xinfo.xinfo != 0)
5712  info |= XLOG_XACT_HAS_INFO;
5713 
5714  /* Then include all the collected data into the abort record. */
5715 
5716  XLogBeginInsert();
5717 
5718  XLogRegisterData((char *) (&xlrec), MinSizeOfXactAbort);
5719 
5720  if (xl_xinfo.xinfo != 0)
5721  XLogRegisterData((char *) (&xl_xinfo), sizeof(xl_xinfo));
5722 
5723  if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
5724  XLogRegisterData((char *) (&xl_dbinfo), sizeof(xl_dbinfo));
5725 
5726  if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
5727  {
5728  XLogRegisterData((char *) (&xl_subxacts),
5730  XLogRegisterData((char *) subxacts,
5731  nsubxacts * sizeof(TransactionId));
5732  }
5733 
5734  if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILENODES)
5735  {
5736  XLogRegisterData((char *) (&xl_relfilenodes),
5738  XLogRegisterData((char *) rels,
5739  nrels * sizeof(RelFileNode));
5740  }
5741