mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Home Page:https://www.mongodb.com/compatibility/mongodb-laravel-integration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Transaction level not working when use closure

florianJacques opened this issue · comments

The transaction level remains at 0 when we use laravel automatic transactions.

 $connection->transaction(function () use ($connection) {
    dump($connection->transactionLevel());
});

Display 0.

Here's a suggested fix

/**
 * Static transaction function realize the with_transaction functionality provided by MongoDB.
 *
 * @param  int $attempts
 */
public function transaction(Closure $callback, $attempts = 1, array $options = []): mixed
{
    $attemptsLeft   = $attempts;
    $callbackResult = null;
    $throwable      = null;

    $callbackFunction = function (Session $session) use ($callback, &$attemptsLeft, &$callbackResult, &$throwable) {
        $attemptsLeft--;

        $this->transactions = 1;

        if ($attemptsLeft < 0) {
            $session->abortTransaction();
            $this->transactions = 0;

            return;
        }

        // Catch, store, and re-throw any exception thrown during execution
        // of the callable. The last exception is re-thrown if the transaction
        // was aborted because the number of callback attempts has been exceeded.
        try {
            $callbackResult = $callback($this);
        } catch (Throwable $throwable) {
            throw $throwable;
        } finally {
            $this->transactions = 0;
        }
    };

    with_transaction($this->getSessionOrCreate(), $callbackFunction, $options);

    if ($attemptsLeft < 0 && $throwable) {
        throw $throwable;
    }

    return $callbackResult;
}