Skip to content
Merged

1.x #706

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/Database/PDO.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Utopia\Database;

use InvalidArgumentException;
use Utopia\CLI\Console;

/**
* A PDO wrapper that forwards method calls to the internal PDO instance.
Expand Down Expand Up @@ -41,7 +42,27 @@ public function __construct(
*/
public function __call(string $method, array $args): mixed
{
return $this->pdo->{$method}(...$args);
try {
return $this->pdo->{$method}(...$args);
} catch (\Throwable $e) {
if (Connection::hasError($e)) {
Console::warning('[Database] ' . $e->getMessage());
Console::warning('[Database] Lost connection detected. Reconnecting...');

$inTransaction = $this->pdo->inTransaction();

// Attempt to reconnect
$this->reconnect();

// If we weren't in a transaction, also retry the query
// In a transaction we can't retry as the state is attached to the previous connection
if (!$inTransaction) {
return $this->pdo->{$method}(...$args);
}
}

throw $e;
}
Comment on lines +45 to +65
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid unsafe retries; guard inTransaction() and never retry commit/rollBack.

  • Don’t retry stateful methods like commit/rollBack; risk of double-commit or inconsistent state.
  • inTransaction() can itself throw on a dead handle; default conservatively (no retry) if it does.

Apply this diff inside the catch block:

         } catch (\Throwable $e) {
             if (Connection::hasError($e)) {
                 Console::warning('[Database] ' . $e->getMessage());
                 Console::warning('[Database] Lost connection detected. Reconnecting...');
-
-                $inTransaction = $this->pdo->inTransaction();
+                // Methods we will never retry to avoid duplicating side effects.
+                $methodLower = \strtolower($method);
+                $isRetryableMethod = !\in_array($methodLower, ['commit', 'rollback'], true);
+
+                // Safely detect transaction state; if uncertain, treat as in-transaction (no retry).
+                $inTransaction = true;
+                try {
+                    $inTransaction = $this->pdo->inTransaction();
+                } catch (\Throwable $_) {
+                    // keep $inTransaction = true
+                }
 
                 // Attempt to reconnect
                 $this->reconnect();
 
                 // If we weren't in a transaction, also retry the query
                 // In a transaction we can't retry as the state is attached to the previous connection
-                if (!$inTransaction) {
+                if ($isRetryableMethod && !$inTransaction) {
                     return $this->pdo->{$method}(...$args);
                 }
             }
 
             throw $e;
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
return $this->pdo->{$method}(...$args);
} catch (\Throwable $e) {
if (Connection::hasError($e)) {
Console::warning('[Database] ' . $e->getMessage());
Console::warning('[Database] Lost connection detected. Reconnecting...');
$inTransaction = $this->pdo->inTransaction();
// Attempt to reconnect
$this->reconnect();
// If we weren't in a transaction, also retry the query
// In a transaction we can't retry as the state is attached to the previous connection
if (!$inTransaction) {
return $this->pdo->{$method}(...$args);
}
}
throw $e;
}
try {
return $this->pdo->{$method}(...$args);
} catch (\Throwable $e) {
if (Connection::hasError($e)) {
Console::warning('[Database] ' . $e->getMessage());
Console::warning('[Database] Lost connection detected. Reconnecting...');
// Methods we will never retry to avoid duplicating side effects.
$methodLower = \strtolower($method);
$isRetryableMethod = !\in_array($methodLower, ['commit', 'rollback'], true);
// Safely detect transaction state; if uncertain, treat as in-transaction (no retry).
$inTransaction = true;
try {
$inTransaction = $this->pdo->inTransaction();
} catch (\Throwable $_) {
// keep $inTransaction = true
}
// Attempt to reconnect
$this->reconnect();
// If we weren't in a transaction, also retry the query
// In a transaction we can't retry as the state is attached to the previous connection
if ($isRetryableMethod && !$inTransaction) {
return $this->pdo->{$method}(...$args);
}
}
throw $e;
}

}

/**
Expand Down
76 changes: 38 additions & 38 deletions tests/unit/PDOTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,44 +41,44 @@ public function testMethodCallIsForwardedToPDO(): void
$this->assertSame($pdoStatementMock, $result);
}

// public function testLostConnectionRetriesCall(): void
// {
// $dsn = 'sqlite::memory:';
// $pdoWrapper = $this->getMockBuilder(PDO::class)
// ->setConstructorArgs([$dsn, null, null, []])
// ->onlyMethods(['reconnect'])
// ->getMock();
//
// $pdoMock = $this->getMockBuilder(\PDO::class)
// ->disableOriginalConstructor()
// ->getMock();
// $pdoStatementMock = $this->getMockBuilder(\PDOStatement::class)
// ->disableOriginalConstructor()
// ->getMock();
//
// $pdoMock->expects($this->exactly(2))
// ->method('query')
// ->with('SELECT 1')
// ->will($this->onConsecutiveCalls(
// $this->throwException(new \Exception("Lost connection")),
// $pdoStatementMock
// ));
//
// $reflection = new ReflectionClass($pdoWrapper);
// $pdoProperty = $reflection->getProperty('pdo');
// $pdoProperty->setAccessible(true);
// $pdoProperty->setValue($pdoWrapper, $pdoMock);
//
// $pdoWrapper->expects($this->once())
// ->method('reconnect')
// ->willReturnCallback(function () use ($pdoWrapper, $pdoMock, $pdoProperty) {
// $pdoProperty->setValue($pdoWrapper, $pdoMock);
// });
//
// $result = $pdoWrapper->query('SELECT 1');
//
// $this->assertSame($pdoStatementMock, $result);
// }
public function testLostConnectionRetriesCall(): void
{
$dsn = 'sqlite::memory:';
$pdoWrapper = $this->getMockBuilder(PDO::class)
->setConstructorArgs([$dsn, null, null, []])
->onlyMethods(['reconnect'])
->getMock();

$pdoMock = $this->getMockBuilder(\PDO::class)
->disableOriginalConstructor()
->getMock();
$pdoStatementMock = $this->getMockBuilder(\PDOStatement::class)
->disableOriginalConstructor()
->getMock();

$pdoMock->expects($this->exactly(2))
->method('query')
->with('SELECT 1')
->will($this->onConsecutiveCalls(
$this->throwException(new \Exception("Lost connection")),
$pdoStatementMock
));

$reflection = new ReflectionClass($pdoWrapper);
$pdoProperty = $reflection->getProperty('pdo');
$pdoProperty->setAccessible(true);
$pdoProperty->setValue($pdoWrapper, $pdoMock);

$pdoWrapper->expects($this->once())
->method('reconnect')
->willReturnCallback(function () use ($pdoWrapper, $pdoMock, $pdoProperty) {
$pdoProperty->setValue($pdoWrapper, $pdoMock);
});

$result = $pdoWrapper->query('SELECT 1');

$this->assertSame($pdoStatementMock, $result);
}

public function testNonLostConnectionExceptionIsRethrown(): void
{
Expand Down