Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: failover's DBPrefix not working #5816

Merged
merged 2 commits into from
Mar 25, 2022
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
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();
MGatner marked this conversation as resolved.
Show resolved Hide resolved
}
}

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