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