Skip to content

Commit

Permalink
Rollback nested transaction on destruct
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Dec 3, 2023
1 parent 1d0fa1e commit 45104d7
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/NestedTransaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Amp\DeferredFuture;
use Amp\Sql\Result;
use Amp\Sql\SqlException;
use Amp\Sql\Statement;
use Amp\Sql\Transaction;
use Amp\Sql\TransactionError;
Expand Down Expand Up @@ -95,6 +96,37 @@ public function __construct(
}
}

public function __destruct()
{
if ($this->onClose->isComplete()) {
return;
}

$this->onClose->complete();

if ($this->executor->isClosed()) {
return;
}

$busy = &$this->busy;
$transaction = $this->transaction;
$executor = $this->executor;
$identifier = $this->identifier;
EventLoop::queue(static function () use (&$busy, $transaction, $executor, $identifier): void {
try {
while ($busy) {
$busy->getFuture()->await();
}

if ($transaction->isActive() && !$executor->isClosed()) {
$executor->rollbackTo($identifier);
}
} catch (SqlException) {
// Ignore failure if connection closes during query.
}
});
}

public function query(string $sql): Result
{
$this->awaitPendingNestedTransaction();
Expand Down Expand Up @@ -157,7 +189,7 @@ public function isClosed(): bool
*/
public function close(): void
{
if ($this->active) {
if ($this->active && $this->transaction->isActive() && !$this->executor->isClosed()) {
$this->rollback();
}
}
Expand Down

0 comments on commit 45104d7

Please sign in to comment.