tag::transaction-function[]
439284
public void addPerson( final String name )
    {
        try ( Session session = driver.session() )
        {
            session.writeTransaction( new TransactionWork<Integer>()
            {
                @Override
                public Integer execute( Transaction tx )
                {
                    return createPersonNode( tx, name );
                }
            } );
        }
    }
1115980
public static function initTransaction($transactionTemplate = null) {
        $fields = ['description', 'date', 'value'];
        
        $transaction = new Transaction();
        
        if ($transactionTemplate !== null) {
            foreach ($fields as $f) {
                $transaction->$f = $transactionTemplate->$f;
            }
        }
        
        return $transaction;
    }
818133
function _logTransaction($listenerName, $transactionStatus, $transactionMessage, $pdtResponse = null)
    {
        // Store the standard log information
        $om = $this->objectManager;
        if (!is_null($this->logID)) {
            $ipnLog  = $om->getRepository($this->clsIpnLog)->find($this->logID);
        } else {
            $ipnLog = new $this->clsIpnLog;
        }
        
        $ipnLog->setListenerName($listenerName);
        $ipnLog->setTransactionType(null);
        $ipnLog->setTransactionId($this->transactionID);
        $ipnLog->setStatus($transactionStatus);
        $ipnLog->setMessage($transactionMessage);
        
        if(!$ipnLog->getCreatedAt())
            $ipnLog->setCreatedAt(new \DateTime());
        $ipnLog->setUpdatedAt(new \DateTime());

        if ($transactionStatus == 'FAIL' || !$this->isLive) {
            $detailJSON = array();
            $detailJSON['pdt_response'] = $pdtResponse;
            $ipnLog->setDetail(json_encode($detailJSON));
        } else {
            $ipnLog->setDetail(null); // Turn it back to null (as it might have been set previously)
        }

        // Finally save down the log record.
        $om->persist($ipnLog);
        $om->flush();

        if (is_null($this->logID)) {
            $this->logID = $ipnLog->getId(); // Save the log ID for next time if we need to.
        }
    }
1274780
public function transaction(\Closure $callback): Transaction
    {
        /**
         * Get the Transaction class
         *
         * @var \Pecee\Pixie\QueryBuilder\Transaction $queryTransaction
         * @throws \Exception
         */
        $queryTransaction = new Transaction($this->connection);
        $queryTransaction->statements = $this->statements;

        try {
            // Begin the PDO transaction
            if ($this->pdo()->inTransaction() === false) {
                $this->pdo()->beginTransaction();
            }

            // Call closure - this callback will return TransactionHaltException if user has already committed the transaction
            $callback($queryTransaction);

            // If no errors have been thrown or the transaction wasn't completed within the closure, commit the changes
            $this->pdo()->commit();

        } catch (TransactionHaltException $e) {

            // Commit or rollback behavior has been triggered in the closure
            return $queryTransaction;

        } catch (\Exception $e) {

            // Something went wrong. Rollback and throw Exception
            if ($this->pdo()->inTransaction() === true) {
                $this->pdo()->rollBack();
            }

            throw Exception::create($e, $this->getConnection()->getAdapter()->getQueryAdapterClass(), $this->getLastQuery());
        }

        return $queryTransaction;
    }
30736
function IDBTransaction(db, storeNames, mode) {
        this.__id = ++uniqueID; // for debugging simultaneous transactions
        this.__active = true;
        this.__running = false;
        this.__errored = false;
        this.__requests = [];
        this.__storeNames = storeNames;
        this.mode = mode;
        this.db = db;
        this.error = null;
        this.onabort = this.onerror = this.oncomplete = null;

        // Kick off the transaction as soon as all synchronous code is done.
        var me = this;
        setTimeout(function() { me.__executeRequests(); }, 0);
    }
90973
public synchronized Token[] toArray(Transaction transaction)
                    throws ObjectManagerException
    {
        // Throws ArrayIndexOutOfBoundsException if size is larger than Integer.MAX_VALUE,
        // because i++ will wrap and go negative.
        Token[] tokens = new Token[(int) size(transaction)];
        int i = 0;
        try {
            for (Iterator iterator = iterator();; tokens[i++] = (Token) iterator.next(transaction));
        } catch (java.util.NoSuchElementException exception) {
            // No FFDC code needed.
            // We have run off the end of the collection.
        } // try.
        return tokens;
    }
889221
function showTransactions(height) {
	// Set the block height in modal title
	$('#txsHeight').html(height);
	// Get the transactions for that block
	var txs = transactions[height];
	// Reset the modal body
	$('#txs').html('');
	// Loop transactions
	for(var i = 0; i < txs.length; i++) {
		// Add stringified transaction object to the modal body
		$('#txs').append('<pre>'+JSON.stringify(txs[i])+'</pre>');
    }
    // Open modal
	$('#myModal').modal('show');
}
275491
private <T> void runTransaction(
      final Transaction.Function<T> transactionCallback,
      final SettableApiFuture<T> resultFuture,
      final TransactionOptions options) {
    // span is intentionally not ended here. It will be ended by runTransactionAttempt on success
    // or error.
    Span span = tracer.spanBuilder("CloudFirestore.Transaction").startSpan();
    try (Scope s = tracer.withSpan(span)) {
      runTransactionAttempt(transactionCallback, resultFuture, options, span);
    }
  }
1159280
public void getActiveTransactions(Set<PersistentTranId> transactionList) throws MessageStoreException
   {
     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
       SibTr.entry(tc, "getActiveTransactions", transactionList);
     
     AbstractItem item = null;
     
     NonLockingCursor cursor = newNonLockingItemCursor(
         new Filter() {
            public boolean filterMatches(AbstractItem abstractItem) throws MessageStoreException {
              if (abstractItem.isRemoving())
                return true;
              else
                return false;
            }      
       
         });
     
     cursor.allowUnavailableItems();
    
     while(null != (item = cursor.next()))
     {
       // Add matching tran id to the set
       transactionList.add(item.getTransactionId());
     }     
     
     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
       SibTr.exit(tc, "getActiveTransactions");
   }
653873
def transaction(self, collections, action, waitForSync = False, lockTimeout = None, params = None) :
        """"""
        payload = {
                "collections": collections,
                "action": action,
                "waitForSync": waitForSync}
        if lockTimeout is not None:
                payload["lockTimeout"] = lockTimeout
        if params is not None:
            payload["params"] = params

        self.connection.reportStart(action)

        r = self.connection.session.post(self.transactionURL, data = json.dumps(payload, default=str))

        self.connection.reportItem()

        data = r.json()

        if (r.status_code == 200 or r.status_code == 201 or r.status_code == 202) and not data.get("error") :
            return data
        else :
            raise TransactionError(data["errorMessage"], action, data)
1206135
@Override
	public void onTxCommit(Transaction tx) {
		if (!tx.isReadOnly() && enableLogging) {
			LogSeqNum lsn = new CommitRecord(txNum).writeToLog();
			VanillaDb.logMgr().flush(lsn);
		}
	}
1348641
public function processTransaction(array $transactionData, string $operation): ProcessInterface
    {
        // When hitting the process endpoint, we only need the transactionId and operation key/value pairs, and
        // optionally the transactionAmount if we are capturing a portion of the total amount.
        $transactionData = array_filter($transactionData + ['operation' => $operation], function ($k) {
            return in_array($k, ['transactionId', 'operation', 'transactionAmount']);
        }, ARRAY_FILTER_USE_KEY);

        $uri = $this->getUri('process', $this->getParameters($transactionData));
        /** @var ProcessInterface $response */
        $response = $this->performRequest((string) $uri);

        Assert::isInstanceOf($response, ProcessInterface::class, 'Invalid response');

        return $response;
    }
230673
function(transaction, _callback) {
      try {
        transaction.secret(secret);
      } catch (exception) {
        return _callback(exception);
      }

      transaction.once('error', _callback);

      transaction.once('submitted', function(message) {
        if (message.result.slice(0, 3) === 'tec'
            && options.validated !== true) {
          return formatTransactionResponseWrapper(transaction, message,
            _callback);
        }

        // Handle erred transactions that should not make it into ledger (all
        // errors that aren't tec-class). This function is called before the
        // transaction `error` listener.
        switch (message.engine_result) {
          case 'terNO_ACCOUNT':
          case 'terNO_AUTH':
          case 'terNO_LINE':
          case 'terINSUF_FEE_B':
            // The transaction needs to be aborted. Preserve the original ter-
            // class error for presentation to the client
            transaction.removeListener('error', _callback);
            transaction.once('error', function() {
              _callback(message);
            });
            transaction.abort();
            break;
        }
      });

      transaction.once('proposed', function(message) {
        if (options.validated !== true) {
          formatTransactionResponseWrapper(transaction, message, _callback);
        }
      });

      transaction.once('success', function(message) {
        if (options.validated === true) {
          formatTransactionResponseWrapper(transaction, message, _callback);
        }
      });

      if (options.saveTransaction === true) {
        transaction.on('state', function() {
          var transactionSummary = transaction.summary();
          if (transactionSummary.submitIndex !== undefined) {
            api.db.saveTransaction(transactionSummary);
          }
        });

        transaction.on('postsubmit', function() {
          api.db.saveTransaction(transaction.summary());
        });
      }

      transaction.submit();
    }
388891
void addToCommittedQueue(Session session, Object[] list) {

        synchronized (committedTransactionTimestamps) {

            // add the txList according to commit timestamp
            committedTransactions.addLast(list);

            // get session commit timestamp
            committedTransactionTimestamps.addLast(session.actionTimestamp);
/* debug 190
            if (committedTransactions.size() > 64) {
                System.out.println("******* excessive transaction queue");
            }
// debug 190 */
        }
    }
545533
public function capture($transactionId, $amount = null, $gratuity = null, $clientTransactionId = null, $directMarketData = null)
    {
        $xml = new DOMDocument();
        $hpsTransaction = $xml->createElement('hps:Transaction');
        $hpsCreditAddToBatch = $xml->createElement('hps:CreditAddToBatch');

        $hpsCreditAddToBatch->appendChild($xml->createElement('hps:GatewayTxnId', $transactionId));
        if ($amount != null) {
            $amount = sprintf("%0.2f", round($amount, 3));
            $hpsCreditAddToBatch->appendChild($xml->createElement('hps:Amt', $amount));
        }
        if ($gratuity != null) {
            $hpsCreditAddToBatch->appendChild($xml->createElement('hps:GratuityAmtInfo', $gratuity));
        }

        if ($directMarketData != null && $directMarketData->invoiceNumber != null) {
            $hpsCreditAddToBatch->appendChild($this->_hydrateDirectMarketData($directMarketData, $xml));
        }

        $hpsTransaction->appendChild($hpsCreditAddToBatch);
        $options = array();
        if ($clientTransactionId != null) {
            $options['clientTransactionId'] = $clientTransactionId;
        }
        $response = $this->doRequest($hpsTransaction, $options);
        $this->_processChargeGatewayResponse($response, 'CreditAddToBatch');

        return $this->get($transactionId);
    }
258156
function(options, callback) {
    // var self = this

    if (typeof options === 'function') {
      callback = options
      options = {}
    }

    if (options.transaction) {
      return callback(options.transaction)
    } else {
      return this.connection
        .transaction(function(transaction) {
          options.transaction = transaction
          return callback(transaction)
        })
        .then(function(result) {
          debug('commit')
          return result
        })
        .catch(function(e) {
          // TODO: do something with e.g. 'afterSave' rollback message!?!
          debug('rollback')
          throw e
        })
    }
  }
58440
def do_transaction(self, function, *args, **kwargs):
        """"""
        with self.config.db_transaction() as trans:
            function(trans, *args, **kwargs)