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