This is required because beginTransaction increment _transactionNestingLevel
before the real query is executed, and results incremented also on gone away error.
This should be safe for a new established connection.
558235
private function resetTransactionNestingLevel(): void
    {
        if (!$this->selfReflectionNestingLevelProperty instanceof \ReflectionProperty) {
            $reflection                               = new \ts\Reflection\ReflectionClass(Connection::class);
            $this->selfReflectionNestingLevelProperty = $reflection->getProperty('transactionNestingLevel');
            $this->selfReflectionNestingLevelProperty->setAccessible(true);
        }

        $this->selfReflectionNestingLevelProperty->setValue($this, 0);
    }
368473
void rollback(long fromTransactionId) {
        long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "rollback", fromTransactionId);
        List<Long> rolledBack = new ArrayList<>();
        while (!this.transactions.isEmpty() && this.transactions.peekLast().getTransactionId() >= fromTransactionId) {
            ContainerMetadataUpdateTransaction txn = this.transactions.removeLast();
            txn.seal();
            rolledBack.add(txn.getTransactionId());
        }

        // At this point, the transaction list is either empty or its last one is sealed; any further changes would
        // require creating a new transaction.
        LoggerHelpers.traceLeave(log, this.traceObjectId, "rollback", traceId, rolledBack);
    }
494541
public void stopTransaction(TransactionWrapper transaction) throws DataAccessException {
        if (logger.isTraceEnabled()) {
            logger.trace("stopTransaction");
        }
        if (transaction==null) {
            if (logger.isTraceEnabled())
                logger.trace("   ... transaction is null");
            return;
        }
        if (!transaction.isTransactionAlreadyStarted()) {
            DataAccessException exception = null;
            if (!transaction.isDatabaseConnectionAlreadyOpened()) {
                if (!(db.getConnection() instanceof XAConnection)) {
                    if (transaction.isRollbackOnly()) db.rollback();
                    else {
                        try {
                            db.commit();
                        } catch (SQLException e) {
                            exception = new DataAccessException(0, "Fail to commit", e);
                        }
                    }
                }
                db.closeConnection();
            } else {
                if (logger.isTraceEnabled())
                    logger.trace("   ... database opened by others");
            }
            try {
                TransactionUtil transUtil = TransactionUtil.getInstance();
                TransactionManager transManager = transUtil.getTransactionManager();
                if (transaction.isRollbackOnly()) transManager.rollback();
                else transManager.commit();
                transUtil.setCurrentConnection(null);
                //transUtil.clearCurrentConnection();
            } catch (Exception e) {
                throw new DataAccessException(0, "Fail to stop the transaction", e);
            }
            if (exception!=null) throw exception;
        } else {
            if (logger.isTraceEnabled())
                logger.trace("   ... transaction started by others");
        }
    }
948126
public static void commitTransaction() {
        Connection connection = tl_conn.get();
        if (connection == null) {
            throw new RuntimeException("You do not start a Transaction so you can not commit a transaction!");
        }
        try {
            connection.commit();
            connection.close();
            tl_conn.remove();
            tl_sp.remove();
        } catch (SQLException e) {
            JDBCUtils.rollbackTransaction();
            throw new RuntimeException(e);
        }
    }
180691
protected void prepareTransactionMemoriesIfExists() {
        final SavedTransactionMemories memories = ThreadCacheContext.findTransactionMemories();
        if (memories != null) {
            final List<TransactionMemoriesProvider> providerList = memories.getOrderedProviderList();
            final StringBuilder sb = new StringBuilder();
            for (TransactionMemoriesProvider provider : providerList) {
                provider.provide().ifPresent(result -> sb.append("\n*").append(result));
            }
            final WholeShowAttribute attribute = new WholeShowAttribute(sb.toString().trim());
            requestManager.setAttribute(LastaWebKey.DBFLUTE_TRANSACTION_MEMORIES_KEY, attribute);
        }
    }
1184400
protected void checkTransactionSupported(Connection conn) throws SQLException, DbRuntimeException {
		if (null == isSupportTransaction) {
			isSupportTransaction = conn.getMetaData().supportsTransactions();
		}
		if (false == isSupportTransaction) {
			throw new DbRuntimeException("Transaction not supported for current database!");
		}
	}
866518
protected boolean beginTransaction(SQLiteDatabase db) {
		boolean endTransaction = false;
		if (!db.inTransaction()) {
			db.beginTransaction();
			endTransaction = true;
			LOGGER.trace("Begin transaction");
		}
		return endTransaction;
	}
618922
public void removeOngoingTransaction(Transaction transaction) {
		boolean removed = false;
		if(this.ongoingTransactions != null) {
			removed = this.ongoingTransactions.remove(transaction);
		}

//		if(sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getMessage() != null && JainSipUtils.DIALOG_CREATING_METHODS.contains(sessionCreatingTransactionRequest.getMethod())) {
//			sessionCreatingTransactionRequest = null;
//		}

		if (proxy != null) {
		    proxy.removeTransaction(transaction.getBranchId());
		}

		if(logger.isDebugEnabled()) {
			logger.debug("transaction "+ transaction +" has been removed from sip session's ongoingTransactions ? " + removed );
		}

		updateReadyToInvalidate(transaction);
		// nullify the sessionCreatingTransactionRequest only after updateReadyToInvalidate as it is used for error response checking

		final String branchId = transaction.getBranchId();
		if(sessionCreatingTransactionRequest != null &&
				 branchId != null) {

			// https://github.com/RestComm/sip-servlets/issues/101 fix for NPE happening due to concurrent behavior cleaning the transaction
			final Transaction sessionCreatingTransactionRequestTransaction = sessionCreatingTransactionRequest.getTransaction();
			String sessionCreatingTransactionRequestTransactionBranchId = null;
			if(sessionCreatingTransactionRequestTransaction != null) {
				sessionCreatingTransactionRequestTransactionBranchId = sessionCreatingTransactionRequestTransaction.getBranchId();
			}
			final String sessionCreatingTransactionRequestMethod = sessionCreatingTransactionRequest.getMethod();

			if(sessionCreatingTransactionRequestTransaction != null &&
					branchId.equals(sessionCreatingTransactionRequestTransactionBranchId)) {

				if(logger.isDebugEnabled()) {
					logger.debug("Session " + key + ": cleaning up "+ sessionCreatingTransactionRequest
							+ " since transaction " + transaction + " with branch id " + branchId
							+ " is the same as sessionCreatingRequestTransaction " +  sessionCreatingTransactionRequestTransaction
							+ " with branch id " + sessionCreatingTransactionRequestTransactionBranchId
							+ " and method " + sessionCreatingTransactionRequestMethod);
				}
				sessionCreatingTransactionRequest.cleanUp();
				// https://telestax.atlassian.net/browse/MSS-153 improve performance by cleaning the request for dialog based requests
				// or proxy case or dialog creating methods
				if(sessionCreatingDialog != null || proxy != null || JainSipUtils.DIALOG_CREATING_METHODS.contains(sessionCreatingTransactionRequestMethod)) {
					if(logger.isDebugEnabled()) {
						logger.debug("removeOngoingTransaction - sessionCreatingTransactionRequest=" + sessionCreatingTransactionRequest);
					}
					if(logger.isDebugEnabled() && sessionCreatingTransactionRequest != null) {
						logger.debug("nullifying  sessionCreatingTransactionRequest" + sessionCreatingTransactionRequest
								+ " from Session " + key);
					}
					if(logger.isDebugEnabled()) {
						logger.debug("invalidate - setting the sessionCreatingTransactionRequest to null, id:" + this.getId());
					}
					sessionCreatingTransactionRequest = null;
				}
			}
		}
	}
88277
function createTransaction(dbInfo, mode, callback, retries) {
    if (retries === undefined) {
        retries = 1;
    }

    try {
        var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
        callback(null, tx);
    } catch (err) {
        if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
            return Promise$1.resolve().then(function () {
                if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
                    // increase the db version, to create the new ObjectStore
                    if (dbInfo.db) {
                        dbInfo.version = dbInfo.db.version + 1;
                    }
                    // Reopen the database for upgrading.
                    return _getUpgradedConnection(dbInfo);
                }
            }).then(function () {
                return _tryReconnect(dbInfo).then(function () {
                    createTransaction(dbInfo, mode, callback, retries - 1);
                });
            })["catch"](callback);
        }

        callback(err);
    }
}
1363206
public static void beginTransaction() {
        ifNullThen(localConnection.get(),
                () -> {
                    Connection connection = getSql2o().beginTransaction();
                    localConnection.set(connection);
                });
    }
932806
private void internalCleanup()
    {
        if(hasBroker())
        {
            PersistenceBroker broker = getBroker();
            if(log.isDebugEnabled())
            {
                log.debug("Do internal cleanup and close the internal used connection without" +
                        " closing the used broker");
            }
            ConnectionManagerIF cm = broker.serviceConnectionManager();
            if(cm.isInLocalTransaction())
            {
                /*
                arminw:
                in managed environment this call will be ignored because, the JTA transaction
                manager control the connection status. But to make connectionManager happy we
                have to complete the "local tx" of the connectionManager before release the
                connection
                */
                cm.localCommit();
            }
            cm.releaseConnection();
        }
    }
80508
public void tx(VoidFunc1<Session> func) throws SQLException {
		try {
			beginTransaction();
			func.call(this);
			commit();
		} catch (Throwable e) {
			quietRollback();
			throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e);
		}
	}
1158535
protected function begin_transaction() {
        if (!$this->transactions_supported()) {
            return;
        }

        $sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
        $this->query_start($sql, NULL, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);

        $sql = "START TRANSACTION";
        $this->query_start($sql, NULL, SQL_QUERY_AUX);
        $result = $this->mysqli->query($sql);
        $this->query_end($result);
    }
816314
public void addOngoingTransaction(Transaction transaction) {

		if(transaction != null && ongoingTransactions != null  && !isReadyToInvalidate() ) {
			boolean added = this.ongoingTransactions.add(transaction);
			if(added) {
				if(logger.isDebugEnabled()) {
					logger.debug("transaction "+ transaction +" has been added to sip session's ongoingTransactions" );
				}
				setReadyToInvalidate(false);
			}
		}
	}
66045
def abort_transaction
      check_if_ended!
      check_if_no_transaction!

      if within_states?(TRANSACTION_COMMITTED_STATE)
        raise Mongo::Error::InvalidTransactionOperation.new(
          Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg(
            :commitTransaction, :abortTransaction))
      end

      if within_states?(TRANSACTION_ABORTED_STATE)
        raise Mongo::Error::InvalidTransactionOperation.new(
          Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction))
      end

      begin
        unless starting_transaction?
          write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num|
            Operation::Command.new(
              selector: { abortTransaction: 1 },
              db_name: 'admin',
              session: self,
              txn_num: txn_num
            ).execute(server)
          end
        end

        @state = TRANSACTION_ABORTED_STATE
      rescue Mongo::Error::InvalidTransactionOperation
        raise
      rescue Mongo::Error
        @state = TRANSACTION_ABORTED_STATE
      rescue Exception
        @state = TRANSACTION_ABORTED_STATE
        raise
      end
    end
1328815
protected boolean isExistingTransaction(Object transaction) {
        ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction;

        return super.isExistingTransaction(actualTransactionObject
                .getHibernateTransactionObject());
    }
698552
public Db tx(TransactionLevel transactionLevel, VoidFunc1<Db> func) throws SQLException {
		final Connection conn = getConnection();

		// 检查是否支持事务
		checkTransactionSupported(conn);

		// 设置事务级别
		if (null != transactionLevel) {
			final int level = transactionLevel.getLevel();
			if (conn.getTransactionIsolation() < level) {
				// 用户定义的事务级别如果比默认级别更严格，则按照严格的级别进行
				conn.setTransactionIsolation(level);
			}
		}

		// 开始事务
		boolean autoCommit = conn.getAutoCommit();
		if (autoCommit) {
			conn.setAutoCommit(false);
		}

		// 执行事务
		try {
			func.call(this);
			// 提交
			conn.commit();
		} catch (Throwable e) {
			quietRollback(conn);
			throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e);
		} finally {
			// 还原事务状态
			quietSetAutoCommit(conn, autoCommit);
			// 关闭连接或将连接归还连接池
			closeConnection(conn);
		}

		return this;
	}