Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transaction level not working when use closure #2851

Open
florianJacques opened this issue Apr 12, 2024 · 0 comments
Open

Transaction level not working when use closure #2851

florianJacques opened this issue Apr 12, 2024 · 0 comments

Comments

@florianJacques
Copy link

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants