Skip to content

Commit

Permalink
Restore connection if closed by timeout (#349)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov authored Aug 23, 2024
1 parent 883758a commit 06226eb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- Chg #339: Replace call of `SchemaInterface::getRawTableName()` to `QuoterInterface::getRawTableName()` (@Tigrov)
- Enh #342: Add JSON overlaps condition builder (@Tigrov)
- Enh #344: Update `bit` type according to main PR yiisoft/db#860 (@Tigrov)
- Bug #349: Restore connection if closed by connection timeout (@Tigrov)

## 1.2.0 March 21, 2024

Expand Down
19 changes: 19 additions & 0 deletions src/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
namespace Yiisoft\Db\Mysql;

use Yiisoft\Db\Driver\Pdo\AbstractPdoCommand;
use Yiisoft\Db\Exception\IntegrityException;

use function str_starts_with;

/**
* Implements a database command that can be executed with a PDO (PHP Data Object) database connection for MySQL,
Expand Down Expand Up @@ -40,6 +43,22 @@ public function insertWithReturningPks(string $table, array $columns): bool|arra
return $result;
}

protected function queryInternal(int $queryMode): mixed
{
try {
return parent::queryInternal($queryMode);
} catch (IntegrityException $e) {
if (str_starts_with($e->getMessage(), 'SQLSTATE[HY000]: General error: 2006 ')) {
$this->db->close();
$this->cancel();

return parent::queryInternal($queryMode);
}

throw $e;
}
}

public function showDatabases(): array
{
$sql = <<<SQL
Expand Down
20 changes: 20 additions & 0 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ public function testTransactionIsolation(): void

/* should not be any exception so far */
$this->assertTrue(true);

$db->close();
}

/**
Expand Down Expand Up @@ -119,5 +121,23 @@ static function (ConnectionInterface $db) {
)->queryScalar();

$this->assertSame('1', $profilesCount, 'profile should be inserted in transaction shortcut');

$db->close();
}

/** @link https://github.com/yiisoft/db-mysql/issues/348 */
public function testRestartConnectionOnTimeout(): void
{
$db = $this->getConnection();

$db->createCommand('SET SESSION wait_timeout = 1')->execute();

sleep(1);

$result = $db->createCommand("SELECT '1'")->queryScalar();

$this->assertSame('1', $result);

$db->close();
}
}

0 comments on commit 06226eb

Please sign in to comment.