Skip to content

Commit

Permalink
Add support for host failover with PostgreSQL
Browse files Browse the repository at this point in the history
Since version 10, PostgreSQL allows to specify serveral hosts in the
connnection string, and can, if the connection option
target_session_atts=read-write is added, automatically choose the primary
(writable) node in a cluster. If the primary changes (due to a failover or
switchover), the client connection will be retried for the next host until a
writable primary is found again.

To leverage this, add the "dbfailover" option to dboptions. If it is set, add
"target_session_attr=read-write" to the connection string. This, in conjunction
with specifying several hosts in $CFG->dbhost config variable makes it possible
to point Moodle at a high-available PostgreSQL cluster and let it follow
failovers automatically.
  • Loading branch information
mbanck-ntap committed Jan 20, 2021
1 parent c381757 commit 4add781
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/dml/pgsql_native_moodle_database.php
Expand Up @@ -172,6 +172,18 @@ public function raw_connect(string $dbhost, string $dbuser, string $dbpass, stri
$connection .= " connect_timeout=".$this->dboptions['connecttimeout'];
}

if (!empty($this->dboptions['dbfailover'])) {
// Failover handling has been requested. However, we only add the
// "target_session_attrs=read-write" option to the connection if
// there is more than one host specified in $CFG->dbhost, because
// otherwise this option has no effect and would then be added to
// possible read-only standbys as well.
$myhosts = explode(',', $this->dbhost);
if (count($myhosts) > 1) {
$connection .= " target_session_attrs=read-write";
}
}

if (empty($this->dboptions['dbhandlesoptions'])) {
// ALTER USER and ALTER DATABASE are overridden by these settings.
$options = array('--client_encoding=utf8', '--standard_conforming_strings=on');
Expand Down

0 comments on commit 4add781

Please sign in to comment.