diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index 4f54c1980830..9c803d0c1372 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -342,6 +342,13 @@ public function __construct(array $params) if (class_exists($queryClass)) { $this->queryClass = $queryClass; } + + if ($this->failover !== []) { + // If there is a failover database, connect now to do failover. + // Otherwise, Query Builder creates SQL statement with the main database config + // (DBPrefix) even when the main database is down. + $this->initialize(); + } } /** diff --git a/tests/system/Database/BaseConnectionTest.php b/tests/system/Database/BaseConnectionTest.php index 9bb8ddee1499..781588dd78e8 100644 --- a/tests/system/Database/BaseConnectionTest.php +++ b/tests/system/Database/BaseConnectionTest.php @@ -105,8 +105,11 @@ public function testCanConnectToFailoverWhenNoConnectionAvailable() $options = $this->options; $options['failover'] = [$this->failoverOptions]; - $db = new MockConnection($options); - $db->shouldReturn('connect', [false, 345])->initialize(); + $db = new class ($options) extends MockConnection { + protected $returnValues = [ + 'connect' => [false, 345], + ]; + }; $this->assertSame(345, $db->getConnection()); $this->assertSame('failover', $db->username); diff --git a/tests/system/Database/Live/ConnectTest.php b/tests/system/Database/Live/ConnectTest.php index 743b5450cca3..1757f91cb676 100644 --- a/tests/system/Database/Live/ConnectTest.php +++ b/tests/system/Database/Live/ConnectTest.php @@ -95,14 +95,22 @@ public function testConnectWorksWithGroupName() public function testConnectWithFailover() { $this->tests['failover'][] = $this->tests; - unset($this->tests['failover'][0]['failover']); + // Change main's DBPrefix + $this->tests['DBPrefix'] = 'main_'; + + if ($this->tests['DBDriver'] === 'SQLite3') { + // Change main's database path to fail to connect + $this->tests['database'] = '/does/not/exists/test.db'; + } + $this->tests['username'] = 'wrong'; $db1 = Database::connect($this->tests); - $this->assertSame($this->tests['failover'][0]['DBDriver'], $this->getPrivateProperty($db1, 'DBDriver')); + $this->assertSame($this->tests['failover'][0]['DBPrefix'], $this->getPrivateProperty($db1, 'DBPrefix')); + $this->assertGreaterThanOrEqual(0, count($db1->listTables())); } }