Skip to content

Commit

Permalink
Merge pull request #5816 from kenjis/fix-db-failover
Browse files Browse the repository at this point in the history
fix: failover's DBPrefix not working
  • Loading branch information
kenjis authored Mar 25, 2022
2 parents 503e6be + 5a45612 commit 93cd7c6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
7 changes: 7 additions & 0 deletions system/Database/BaseConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

/**
Expand Down
7 changes: 5 additions & 2 deletions tests/system/Database/BaseConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 10 additions & 2 deletions tests/system/Database/Live/ConnectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
}
}

0 comments on commit 93cd7c6

Please sign in to comment.