diff --git a/src/Connection.php b/src/Connection.php index d21764ca..8dfc9cfa 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -276,14 +276,10 @@ public function rollbackSavepoint(string $name) /** @inheritdoc */ public function ping(): bool { - try { - $this->connected || $this->connect(); - return $this->driver->ping(); - - } catch (DriverException $e) { - $this->reconnect(); + if (!$this->connected) { return false; } + return $this->driver->ping(); } diff --git a/src/Drivers/Sqlsrv/SqlsrvDriver.php b/src/Drivers/Sqlsrv/SqlsrvDriver.php index ff1fba43..202bafeb 100644 --- a/src/Drivers/Sqlsrv/SqlsrvDriver.php +++ b/src/Drivers/Sqlsrv/SqlsrvDriver.php @@ -166,7 +166,12 @@ public function getServerVersion(): string public function ping(): bool { - return sqlsrv_begin_transaction($this->connection); + try { + $this->query('SELECT 1'); + return true; + } catch (DriverException $e) { + return false; + } } diff --git a/src/IConnection.php b/src/IConnection.php index cbd8abd6..27def4ab 100644 --- a/src/IConnection.php +++ b/src/IConnection.php @@ -122,7 +122,11 @@ public function rollbackSavepoint(string $name); /** - * Pings a database connection and tries to reconnect it if it is broken. + * Pings a database connection and returns true if the connection is alive. + * @example + * if (!$connection->ping()) { + * $connection->reconnect(); + * } * @return bool */ public function ping(): bool; diff --git a/tests/cases/integration/connection.phpt b/tests/cases/integration/connection.phpt index ddd21a2d..ee7a87a3 100644 --- a/tests/cases/integration/connection.phpt +++ b/tests/cases/integration/connection.phpt @@ -19,8 +19,11 @@ class ConnectionTest extends IntegrationTestCase public function testPing() { Assert::false($this->connection->getDriver()->isConnected()); - $this->connection->ping(); + Assert::false($this->connection->ping()); + Assert::false($this->connection->getDriver()->isConnected()); + $this->connection->connect(); Assert::true($this->connection->getDriver()->isConnected()); + Assert::true($this->connection->ping()); } @@ -41,8 +44,6 @@ class ConnectionTest extends IntegrationTestCase Assert::same([ 'connect', 'disconnect', - 'connect', - 'disconnect', ], $log); }