Preconditions: 1. xid must in ended state.

Implementation deficiency preconditions: 1. this connection must have been used to run the
transaction

Postconditions: 1. Transaction is committed
550302
private void commitOnePhase(Xid xid) throws XAException {
    try {
      // Check preconditions
      if (currentXid == null || !currentXid.equals(xid)) {
        // In fact, we don't know if xid is bogus, or if it just wasn't
        // associated with this
        // connection.
        // Assume it's our fault.
        throw new CloudSpannerXAException(CloudSpannerXAException.ONE_PHASE_SAME,
            Code.UNIMPLEMENTED, XAException.XAER_RMERR);
      }
      if (state != STATE_ENDED) {
        throw new CloudSpannerXAException(CloudSpannerXAException.COMMIT_BEFORE_END,
            Code.FAILED_PRECONDITION, XAException.XAER_PROTO);
      }

      // Preconditions are met. Commit
      state = STATE_IDLE;
      currentXid = null;

      conn.commit();
      conn.setAutoCommit(localAutoCommitMode);
    } catch (CloudSpannerSQLException ex) {
      throw new CloudSpannerXAException(CloudSpannerXAException.ERROR_ONE_PHASE, ex,
          XAException.XAER_RMERR);
    } catch (SQLException ex) {
      throw new CloudSpannerXAException(CloudSpannerXAException.ERROR_ONE_PHASE, ex, Code.UNKNOWN,
          XAException.XAER_RMERR);
    }
  }
89795
function TXDBState(wid, id) {
  this.wid = wid;
  this.id = id;
  this.tx = 0;
  this.coin = 0;
  this.unconfirmed = 0;
  this.confirmed = 0;
  this.committed = false;
}
658306
@Override
    public void afterCompletion(TransactionCommon transaction, boolean committed)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "afterCompletion", new Object[] { transaction, Boolean.valueOf(committed) });

        synchronized (this)
        {
            // If the connection is already closed this transaction
            // will have been removed.
            if (!_closed)
            {
                synchronized (_ownedTransactions)
                {
                    // Remove the transaction from the connections list
                    _ownedTransactions.remove(transaction);
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "afterCompletion");
    }
1122234
public void commit(final Xid xid, final boolean onePhase)
            throws XAException {

        final String methodName = "commit";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, new Object[] { xid,
                    Boolean.valueOf(onePhase) });
        }

        _siXaResource.commit(xid, onePhase);

        // Add the value false to indicate we have commited to the hashtable of
        // stats (keying off the xid)
        synchronized (_transactionStates) {

          _transactionStates.put (xid, Boolean.FALSE);

          if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer ("After adding the xid ");
            sb.append (xid);
            sb.append (" the hashtable of transactionStates now contains ");
            sb.append (_transactionStates.size());
            sb.append (" entries");
            SibTr.debug (this, TRACE, sb.toString());
          }

        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }
929419
private void visitTxId() throws IOException {
    if (LayoutVersion.supports(Feature.STORED_TXIDS, editsVersion)) {
      v.visitLong(EditsElement.TRANSACTION_ID);
    }
  }
675837
public static long checkPostconditionL(
    final long value,
    final ContractLongConditionType condition)
    throws PostconditionViolationException
  {
    return checkPostconditionL(
      value, condition.predicate(), condition.describer());
  }
403424
@Override
	public void commit() throws IndoubtException {
		session.transaction.remove();
		
		if (logs.size() == 0) {
			return;
		}
		
		try {
			for (Log log : logs) {
				if (log.operation() != Operation.GET) {
					if (transaction.isActive()) {
						transaction.commit();
					}
					
					log.state(State.COMMITTED);
				}
			}

		} catch (Exception e) {
			throw new UncheckedException(e);
		}
		
		logger.fine("Transaction [" + id + "] committed");
	}
1354831
async def commit_prepared(self, xid, *, is_prepared=True):
        """"""
        if not is_prepared:
            await self.execute("XA END '%s'" % xid)
        await self.execute("XA COMMIT '%s'" % xid)
672214
public static void afterCompletion(TransactionImpl tran, int status, int syncLevel) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "afterCompletion", new Object[] { tran, status, syncLevel });

        if (syncLevel >= 0) {
            final ArrayList syncs = _syncLevels.get(syncLevel);

            if (syncs != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "syncs.length=" + syncs.size());

                final int localID = (int) tran.getLocalTID();
                final byte[] globalID = tran.getTID();
                // d281425 - status maybe committed, unknown or rolledback
                final boolean committed = !(status == Status.STATUS_ROLLEDBACK); // @281425C
                final int numSyncs = syncs.size();

                for (int s = 0; s < numSyncs; s++) {
                    try {
                        ((SynchronizationCallback) syncs.get(s)).afterCompletion(localID, globalID, committed);
                    } catch (Throwable t) {
                        // No FFDC needed
                        Tr.error(tc, "WTRN0074_SYNCHRONIZATION_EXCEPTION", new Object[] { "afterCompletion", syncs.get(s), t });
                        // absorb and allow other afterCompletions to run.
                    }
                }
            } else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "syncs is null");
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "afterCompletion");
    }
1216435
protected void transactionComplete() {

        if (state != STATE_TRAN_WRAPPER_INUSE) {
            IllegalStateException e = new IllegalStateException("transactionComplete: illegal state exception. State = " + getStateString() + " MCW = "
                                                                + mcWrapperObject_hexString);
            Object[] parms = new Object[] { "transactionComplete", e };
            Tr.error(tc, "ILLEGAL_STATE_EXCEPTION_J2CA0079", parms);
            throw e;
        }

        state = STATE_ACTIVE_INUSE;
    }
834034
public int prepare() throws ProtocolException, RollbackException, SeverePersistenceException, TransactionException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "prepare");

        // Check the current transaction state (use state lock to ensure we see the latest value)
        synchronized (_stateLock)
        {
            if (_state != TransactionState.STATE_ACTIVE)
            {
                ProtocolException pe = new ProtocolException("TRAN_PROTOCOL_ERROR_SIMS1001", new Object[]{});
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Cannot prepare Transaction. Transaction is complete or completing!", pe);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
                throw pe;
            }

            // Transition our prepare sub-state immediately - before we call the callbacks
            _preCommitSubstate = TransactionState.STATE_PREPARING;
        }

        // PK81848
        // From this point on, we must perform a rollback if we fail to complete the prepare,
        // or another thread requests a deferred rollback
        try
        {
            // Call beforeCompletion on MP callback
            for (int i = 0; i < _callbacks.size(); i++)
            {
                TransactionCallback callback = (TransactionCallback) _callbacks.get(i);
                callback.beforeCompletion(this);
            }

            // Do we have work to do?
            if (_workList != null)
            {
                _workList.preCommit(this);

                synchronized (_stateLock)
                {
                    // Need to change the overalll state after we have 
                    // called the callbacks and preCommitted 
                    // the workList as they may trigger
                    // an addWork call to add work to the
                    // transaction.
                    _state = TransactionState.STATE_PREPARING;
                }

                // The transaction is about to be in a state where any rollback must
                // update the database.  We cannot narrow the window any more than this
                _rollbackChanges = true;
                
                // Perform the prepare
                _persistence.prepare(this);

                // State check/change must be performed holding the state lock
                synchronized (_stateLock)
                {
                    // Another thread may have have received a rollback, while we were
                    // performing our prepare - if the database was extremely slow to respond
                    if (_preCommitSubstate == TransactionState.STATE_ROLLBACK_DEFERRED)
                    {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.event(this, tc, "Deferred rollback requested during prepare for TranId: "+_ptid);

                        // Throw an exception to trigger rollback processing.
                        throw new DeferredRollbackException();
                    }
                    else
                    {
                        _state = _preCommitSubstate = TransactionState.STATE_PREPARED;
                    }
                }                
            }
            else
            {
                // State change must be performed holding the state lock
                synchronized (_stateLock)
                {
                    // Defect 301480
                    // We don't have any work in our workList so in theory we should be
                    // able to vote READ_ONLY at this point. However in a particular case
                    // (Best Effort message being sent off server) a call back in an empty
                    // XAResource is used to trigger work on a remote server. In this case 
                    // we need beforeCompletion AND afterCompletion to be called at the 
                    // CORRECT time during transaction completion to ensure that the off 
                    // server work stays part of the XA transaction and gets informed of 
                    // the correct completion direction.
                    _state = _preCommitSubstate = TransactionState.STATE_PREPARED;
                }
            }
        }
        catch (SeverePersistenceException spe)
        {
            // SPE exceptions are handled with an RMFAIL return code by the caller,
            // so unlike all other types of exception no attempt is made here to
            // rollback the transaction. However, we report a local error - so
            // the whole JVM will be coming down with a few minutes.
            com.ibm.ws.ffdc.FFDCFilter.processException(spe, "com.ibm.ws.sib.msgstore.transactions.XidParticipant.prepare", "1:420:1.73", this);

            // As we have thrown a severe exception we need to inform
            // the ME that this instance is no longer able to continue.
            if (_ms != null)
            {
                _ms.reportLocalError();
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Unrecoverable persistence exception caught during prepare phase of transaction!", spe);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", spe);
            throw spe;
        }
        // Catch and handle all exceptions but allow 
        // Errors to filter up without interference
        catch (Exception e)
        {
            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.sib.msgstore.transactions.XidParticipant.prepare", "1:436:1.73", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Transaction will roll-back due to Exception in prepare!", e);

            // Update our prepare state before calling rollback. If we are responding
            // to a deferred rollback request this will have no affect but if this is 
            // due to some other failure it will lock out any other attempts to rollback
            synchronized (_stateLock)
            {
                _preCommitSubstate = TransactionState.STATE_ROLLINGBACK;
            }

            // An error has occurred but we are able to keep the ME
            // going so we just need to clean up this transaction.
            try
            {
                // When we throw our RollbackException the TM is
                // going to assume we are complete so we need to 
                // ensure we are rolled-back.
                // 
                // PK81848.2
                // We need to pass "true" in order to turn off the
                // state checking which should block other threads 
                // from attempting a rollback when we are in the 
                // middle of internal rollback processing.
                rollback(true);
            }
            // Catch and handle all exceptions but allow 
            // Errors to filter up without interference
            catch (Exception e2)
            {
                com.ibm.ws.ffdc.FFDCFilter.processException(e2, "com.ibm.ws.sib.msgstore.transactions.XIDParticipant.prepare", "1:466:1.73", this);
                
                // This is a problem because we now must RMFAIL this prepare call as we do not know the outcome.
                // Transition to rollback expected state now even if we are in deferred rollback.  This is the
                // only thing we can do (problem is we said XA_OK to roll back in deferred case and now we
                // cannot honour it).  This case may still leave indoubts.
                synchronized(_stateLock)
                {
                    _state = _preCommitSubstate = TransactionState.STATE_ROLLBACK_EXPECTED;
                }
                
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", "Exception caught rolling-back transaction after preCommit failure! " + e2);
                throw new TransactionException(e2);
            }

            // Mark ourselves as complete, regardless of the outcome of the attempt to rollback.
            synchronized (_stateLock)
            {
                _state = _preCommitSubstate = TransactionState.STATE_ROLLEDBACK;
            }

            // Wrap any persistence exception, or an unexpected exception, in a rollback exception.
            // This informs the TM that they can forget about this transaction.
            RollbackException re = new RollbackException("COMPLETION_EXCEPTION_SIMS1002", new Object[]{e}, e);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", re);
            throw re;
        }

        // Non-exception return path always returns XA_OK
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", "return="+XAResource.XA_OK);
        return XAResource.XA_OK;
    }
103729
public int prepare(Xid xid) throws XAException {

        validateXid(xid);

        /**
         * @todo:  This is where the real 2-phase work should be done to
         * determine if a commit done here would succeed or not.
         */

        /**
         * @todo:  May improve performance to return XA_RDONLY whenever
         * possible, but I don't know.
         * Could determine this by checking if DB instance is in RO mode,
         * or perhaps (with much difficulty) to determine if there have
         * been any modifications performed.
         */
        if (state != XA_STATE_ENDED) {
            throw new XAException("Invalid XAResource state");
        }

        // throw new XAException(
        // "Sorry.  HSQLDB has not implemented 2-phase commits yet");
        state = XA_STATE_PREPARED;

        return XA_OK;    // As noted above, should check non-committed work.
    }
674548
@Override
    public final void commit() throws XAException
    {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "commit", new Object[] { _resource, _xid, getPriority() });
        if (tcSummary.isDebugEnabled())
            Tr.debug(tcSummary, "xa_commit", this);
        if (tc.isDebugEnabled())
            Tr.debug(tc, "Committing resource with priority " + getPriority());

        try {
            if (_state == FAILED)
                _resource = reconnectRM();

            _resource.commit(_xid, false);

            // Record the completion direction
            _completedCommit = true;

            destroy();
        } catch (XAException xae) {
            _completionXARC = xae.errorCode;
            // Record the completion XA return code
            FFDCFilter.processException(xae, "com.ibm.ws.Transaction.JTA.JTAXAResourceImpl.commit", "317", this);
            throw xae;
        } finally {
            if (tc.isEntryEnabled())
                Tr.exit(tc, "commit");
            if (tcSummary.isDebugEnabled())
                Tr.debug(tcSummary, "xa_commit result: " +
                                    XAReturnCodeHelper.convertXACode(_completionXARC));
        }
    }
131926
public final void commitInternal(final PersistentTransaction transaction)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "commitInternal", transaction);

        getLink().internalCommitAdd();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "commitInternal");
    }
32268
protected synchronized void setXID(byte[] XID)
                    throws ObjectManagerException
    {
        throw new InvalidStateException(this, InternalTransaction.stateTerminated, InternalTransaction.stateNames[InternalTransaction.stateTerminated]);
    }
169847
public void commit(TransactionStatus status) throws TransactionException {

		MultiTransactionStatus multiTransactionStatus = (MultiTransactionStatus) status;

		boolean commit = true;
		Exception commitException = null;
		PlatformTransactionManager commitExceptionTransactionManager = null;

		for (PlatformTransactionManager transactionManager : reverse(transactionManagers)) {

			if (commit) {

				try {
					multiTransactionStatus.commit(transactionManager);
				} catch (Exception ex) {
					commit = false;
					commitException = ex;
					commitExceptionTransactionManager = transactionManager;
				}

			} else {

				// after unsucessfull commit we must try to rollback remaining transaction managers

				try {
					multiTransactionStatus.rollback(transactionManager);
				} catch (Exception ex) {
					LOGGER.warn("Rollback exception (after commit) (" + transactionManager + ") " + ex.getMessage(), ex);
				}
			}
		}

		if (multiTransactionStatus.isNewSynchronization()) {
			synchronizationManager.clearSynchronization();
		}

		if (commitException != null) {
			boolean firstTransactionManagerFailed = commitExceptionTransactionManager == getLastTransactionManager();
			int transactionState = firstTransactionManagerFailed ? HeuristicCompletionException.STATE_ROLLED_BACK
					: HeuristicCompletionException.STATE_MIXED;
			throw new HeuristicCompletionException(transactionState, commitException);
		}
	}
1295032
public final T execute()
   {
      boolean txOwner = !TransactionElf.hasTransactionManager() || TransactionElf.beginOrJoinTransaction();
      Connection connection = null;
      try {
         connection = ConnectionProxy.wrapConnection(dataSource.getConnection());
         if (txOwner) {
            // disable autoCommit mode as we are going to handle transaction by ourselves
            connection.setAutoCommit(false);
         }
         return (args == null)
            ? execute(connection)
            : execute(connection, args);
      }
      catch (SQLException e) {
         if (e.getNextException() != null) {
            e = e.getNextException();
         }
         if (txOwner) {
            // set the txOwner to false as we no longer own the transaction and we shouldn't try to commit it later
            txOwner = false;
            rollback(connection);
         }
         throw new RuntimeException(e);
      } catch (Throwable e) {
         if (txOwner) {
            txOwner = false;
            rollback(connection);
         }
         throw e;
      }
      finally {
         try {
            if (txOwner) {
               commit(connection);
            }
         }
         finally {
            quietClose(connection);
         }
      }
   }