Skip to content

Commit 93cd7c6

Browse files
authored
Merge pull request #5816 from kenjis/fix-db-failover
fix: failover's DBPrefix not working
2 parents 503e6be + 5a45612 commit 93cd7c6

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

system/Database/BaseConnection.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,13 @@ public function __construct(array $params)
342342
if (class_exists($queryClass)) {
343343
$this->queryClass = $queryClass;
344344
}
345+
346+
if ($this->failover !== []) {
347+
// If there is a failover database, connect now to do failover.
348+
// Otherwise, Query Builder creates SQL statement with the main database config
349+
// (DBPrefix) even when the main database is down.
350+
$this->initialize();
351+
}
345352
}
346353

347354
/**

tests/system/Database/BaseConnectionTest.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,11 @@ public function testCanConnectToFailoverWhenNoConnectionAvailable()
105105
$options = $this->options;
106106
$options['failover'] = [$this->failoverOptions];
107107

108-
$db = new MockConnection($options);
109-
$db->shouldReturn('connect', [false, 345])->initialize();
108+
$db = new class ($options) extends MockConnection {
109+
protected $returnValues = [
110+
'connect' => [false, 345],
111+
];
112+
};
110113

111114
$this->assertSame(345, $db->getConnection());
112115
$this->assertSame('failover', $db->username);

tests/system/Database/Live/ConnectTest.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,14 +95,22 @@ public function testConnectWorksWithGroupName()
9595
public function testConnectWithFailover()
9696
{
9797
$this->tests['failover'][] = $this->tests;
98-
9998
unset($this->tests['failover'][0]['failover']);
10099

100+
// Change main's DBPrefix
101+
$this->tests['DBPrefix'] = 'main_';
102+
103+
if ($this->tests['DBDriver'] === 'SQLite3') {
104+
// Change main's database path to fail to connect
105+
$this->tests['database'] = '/does/not/exists/test.db';
106+
}
107+
101108
$this->tests['username'] = 'wrong';
102109

103110
$db1 = Database::connect($this->tests);
104111

105-
$this->assertSame($this->tests['failover'][0]['DBDriver'], $this->getPrivateProperty($db1, 'DBDriver'));
112+
$this->assertSame($this->tests['failover'][0]['DBPrefix'], $this->getPrivateProperty($db1, 'DBPrefix'));
113+
106114
$this->assertGreaterThanOrEqual(0, count($db1->listTables()));
107115
}
108116
}

0 commit comments

Comments
 (0)