Skip to content
Merged
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
35 changes: 29 additions & 6 deletions src/Connection/Driver.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php
namespace Gt\Database\Connection;

use Gt\Database\DatabaseException;
use PDO;
use PDOException;

class Driver {
/** @noinspection PhpUnused */
Expand Down Expand Up @@ -54,12 +56,33 @@ protected function connect():void {
$options[PDO::MYSQL_ATTR_LOCAL_INFILE] = true;
}

$this->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<MSG_PART>.+)/", $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) {
Expand Down
27 changes: 26 additions & 1 deletion test/phpunit/Query/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -33,4 +35,27 @@ public function testConstructionQueryPathExists(
catch(\Exception $e) {
}
}
}

/** @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));
}
}
Loading