Skip to content

Transaction level not working when use closure #2851

Open
@florianJacques

Description

@florianJacques

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;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @GromNaN@florianJacques

        Issue actions

          Transaction level not working when use closure · Issue #2851 · mongodb/laravel-mongodb