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