diff --git a/src/Connection/Driver.php b/src/Connection/Driver.php index 5051fd5..393bbfc 100644 --- a/src/Connection/Driver.php +++ b/src/Connection/Driver.php @@ -1,7 +1,9 @@ connection = new Connection( - $this->settings->getConnectionString(), - $this->settings->getUsername(), - $this->settings->getPassword(), - $options - ); + try { + $this->connection = new Connection( + $this->settings->getConnectionString(), + $this->settings->getUsername(), + $this->settings->getPassword(), + $options + ); + } + catch(PDOException $exception) { + $message = $exception->getMessage(); + $code = $exception->getCode(); + + if(preg_match("/^SQL(.+)\[[^]]+\] \[\d+\] (?P.+)/", $message, $matches)) { + $message = $matches["MSG_PART"]; + } + + if($code === 2002) { + $message = "Could not connect to database - is the " + . $this->settings->getDriver() + . " server running at " + . $this->settings->getHost() + . " on port " + . $this->settings->getPort() . "?"; + } + + throw new DatabaseException($message, $code, $exception); + } if($initQuery = $this->settings->getInitQuery()) { foreach(explode(";", $initQuery) as $q) { diff --git a/test/phpunit/Query/QueryTest.php b/test/phpunit/Query/QueryTest.php index c0ddbc7..338df4f 100644 --- a/test/phpunit/Query/QueryTest.php +++ b/test/phpunit/Query/QueryTest.php @@ -3,6 +3,8 @@ use Gt\Database\Connection\Driver; use Gt\Database\Connection\DefaultSettings; +use Gt\Database\Connection\Settings; +use Gt\Database\DatabaseException; use Gt\Database\Query\QueryNotFoundException; use Gt\Database\Query\SqlQuery; use PHPUnit\Framework\TestCase; @@ -33,4 +35,27 @@ public function testConstructionQueryPathExists( catch(\Exception $e) { } } -} \ No newline at end of file + + /** @dataProvider \Gt\Database\Test\Helper\Helper::queryPathExistsProvider */ + public function testExecDoesNotConnect( + string $queryName, + string $queryCollectionPath, + string $queryPath + ):void { + $host = uniqid("host."); + $port = 3306; + + $mysqlSettings = new Settings( + $queryCollectionPath, + Settings::DRIVER_MYSQL, + "DoesNotExist" . uniqid(), + $host, + $port, + "dev", + "dev_pass", + ); + self::expectException(DatabaseException::class); + self::expectExceptionMessage("Could not connect to database - is the mysql server running at $host on port $port?"); + new SqlQuery($queryPath, new Driver($mysqlSettings)); + } +}