Skip to content

Commit 11d3b5f

Browse files
oshmyheliukBohdan Korablov
authored andcommitted
MAGECLOUD-1520: Initial builds failing (#137)
* MAGECLOUD-1520: Initial builds failing * MAGECLOUD-1520: Initial builds failing * MAGECLOUD-1520: Initial builds failing * MAGECLOUD-1520: Initial builds failing * MAGECLOUD-1520: Initial builds failing
1 parent 5b40a62 commit 11d3b5f

File tree

2 files changed

+56
-8
lines changed

2 files changed

+56
-8
lines changed

src/DB/Connection.php

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
*/
1414
class Connection implements ConnectionInterface
1515
{
16+
const MYSQL_ERROR_CODE_SERVER_GONE_AWAY = 2006;
17+
1618
/**
1719
* @var \PDO
1820
*/
@@ -130,19 +132,44 @@ public function bindValues(\PDOStatement $statement, array $bindings)
130132
*/
131133
public function getPdo(): \PDO
132134
{
133-
if (null === $this->pdo) {
134-
$environment = $this->environment;
135-
136-
$this->pdo = new \PDO(
137-
sprintf('mysql:dbname=%s;host=%s', $environment->getDbName(), $environment->getDbHost()),
138-
$environment->getDbUser(),
139-
$environment->getDbPassword()
140-
);
135+
$this->connect();
136+
137+
try {
138+
$this->pdo->query('SELECT 1');
139+
} catch (\Exception $e) {
140+
if ($this->pdo->errorInfo()[1] !== self::MYSQL_ERROR_CODE_SERVER_GONE_AWAY) {
141+
throw $e;
142+
}
143+
144+
$this->logger->notice('Lost connection to Mysql server. Reconnecting.');
145+
$this->pdo = null;
146+
$this->connect();
141147
}
142148

143149
return $this->pdo;
144150
}
145151

152+
/**
153+
* Create PDO connection.
154+
*/
155+
private function connect()
156+
{
157+
if ($this->pdo instanceof \PDO) {
158+
return;
159+
}
160+
161+
$environment = $this->environment;
162+
163+
$this->pdo = new \PDO(
164+
sprintf('mysql:dbname=%s;host=%s', $environment->getDbName(), $environment->getDbHost()),
165+
$environment->getDbUser(),
166+
$environment->getDbPassword(),
167+
[
168+
\PDO::ATTR_PERSISTENT => true
169+
]
170+
);
171+
}
172+
146173
/**
147174
* @param string $query
148175
* @param array $bindings

src/Test/Unit/DB/ConnectionTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,4 +107,25 @@ public function testGetPdo()
107107
{
108108
$this->assertSame($this->pdoMock, $this->connection->getPdo());
109109
}
110+
111+
/**
112+
* @expectedException \Exception
113+
* @expectedExceptionMessage Some exception
114+
*/
115+
public function testGetPdoWithException()
116+
{
117+
$this->pdoMock->expects($this->once())
118+
->method('query')
119+
->with('SELECT 1')
120+
->willThrowException(new \Exception('Some exception'));
121+
$this->pdoMock->expects($this->once())
122+
->method('errorInfo')
123+
->willReturn([
124+
'HY000',
125+
2000,
126+
'Some message'
127+
]);
128+
129+
$this->connection->getPdo();
130+
}
110131
}

0 commit comments

Comments
 (0)