Hi,

How to set up master-slave database configuration with Drupal 8? Any advice would be highly appreciated.

Thanks

Comments

adrian1231’s picture

Many years later and still no one has an answer to this question. I am in the process of trying to figure that out right now. I will post the answer here when I do.

jaypan’s picture

Please do - it's something I'd be interested in reading more about.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
adrian1231’s picture

I used the following configuration in my settings.php file and it worked:

$databases['default']['default'] = array (
   'database'=>'drupaldb',
   'username'=>'masteruser',
   'host'=>'database-master.com'
   ...
);
$databases['default']['replica'][] = array (
   'database'=>'drupaldb',
   'username'=>'slaveuser',
   'host'=>'database-slave.com'
   ...
);
jaypan’s picture

Nice, thanks for the update.


Contact me to contract me for D7 -> D10/11 migrations.
Or anything really. I'm friendly, and open to work or conversation.
Bober’s picture

Does this configuration splits read and writes to DB ?

mmjvb’s picture

The documentation actually says that the replica should be an array or replicas.
See https://stackoverflow.com/questions/49918991/use-mysql-master-slave-bala...
& https://www.drupal.org/docs/8/api/database-api/database-configuration

Wonder what you mean with it works. Can you elaborate on your usage?

@Bober No, AFAIK there is no functionality in Drupal using it. You would need to use the replica service. You might want to google on master/slave as well as primary/replica. You can also find some test in ./web/core/tests/Drupal/KernelTests/Core/Database testing the replica.

mubasshir khan’s picture

@adrian1231 I have also added this configuration in my settings.php file but how to test it is working and how to check that all select core query is using my slave database not master database.

Actually I need to write query only with master database and all select query even related to my custom module or any default core module execute with only slave database so please tell me how to achieve this. I really need it.

donpwinston’s picture

I'm doing it with Drupal 7 at the moment. In process of converting large custom Drupal 7 app to Drupal 9. I used the standard MySQL way of setting up master/slave DBs. It works in both directions:

my.cnf (master/slave server1)

[mysqld]

...
#skip-networking
log-bin=mysql-bin
relay_log=relay-bin
relay-log-purge	= 1
expire_logs_days = 10
max_binlog_size = 500M
log-slave-updates
sync_binlog = 1
replicate-wild-ignore-table = mysql.%
replicate-wild-ignore-table=bnc%.cache%
replicate-wild-ignore-table=bnc%.search%
replicate-wild-ignore-table=bnc%.watchdog%
replicate-ignore-table=bnc.temp_search_sids
replicate-ignore-table=bnc.temp_search_results
# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id = 1
auto_increment_increment = 2
auto_increment_offset = 1
slave-skip-errors=1062
...

my.cnf (master/slave server2)

[mysqld]
...
#skip-networking
log-bin=mysql-bin
relay_log=relay-bin
relay-log-purge	= 1
expire_logs_days = 10
slave_sql_verify_checksum = 0
max_binlog_size = 500M
log-slave-updates
sync_binlog = 1
replicate-wild-ignore-table = mysql.%
replicate-wild-ignore-table=bnc%.cache%
replicate-wild-ignore-table=bnc%.search%
replicate-wild-ignore-table=bnc%.watchdog%
replicate-ignore-table=bnc.temp_search_sids
replicate-ignore-table=bnc.temp_search_results
# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id = 2
auto_increment_increment = 2
auto_increment_offset = 2
slave-skip-errors=1062
...

Login to mysql on master/slave server1 and server2 and execute the following:

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'xxxxx' IDENTIFIED BY 'yyyyy';
FLUSH PRIVILEGES;

quit

Restart database

On master/slave server2 execute the following:

STOP SLAVE;
CHANGE MASTER TO
MASTER_HOST='master/slave server1',
MASTER_USER='repl',
MASTER_PASSWORD='yyyyyyy',
MASTER_PORT=3306,
MASTER_CONNECT_RETRY=60,
MASTER_SSL=1;
START SLAVE;

On master/slave server1 execute the following:

STOP SLAVE;
CHANGE MASTER TO
MASTER_HOST='maser/slave server2',
MASTER_USER='repl',
MASTER_PASSWORD='yyyyyyyy',
MASTER_PORT=3306,
MASTER_CONNECT_RETRY=60,
MASTER_SSL=1;
START SLAVE;
One important note. Set up auto incrementing of node ids so they are odd numbers on master/slave server1 and even numbers on master/slave server 2.

Simpler is always better.

mubasshir khan’s picture

@donpwinston Thanks for the update.

Actually, I need to what configuration is required in Drupal 8 end, so that master/ slave DB can work means, all insert query will execute through master database and all select query will execute through slave end.

simanta’s picture

In Drupal 8 Master-Slave database setup can be configured using the suggestion provided in link: https://www.drupal.org/docs/8/api/database-api/database-configuration. While checking setup in local environment, this approach is not working as per expectation. So there is an alternative snippet which actually worked and tested on Drupal version 8.8.0.

// Master database
$connect_db[] = [
  'database' => 'databasename',
  'username' => 'sqlusername',
  'password' => 'sqlpassword',
  'prefix' => '',
  'host' => 'masterhostname',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
];
// Salve database
$connect_db[] = [
  'database' => 'databasename',
  'username' => 'sqlusername',
  'password' => 'sqlpassword',
  'prefix' => '',
  'host' => 'slavehostname',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
  'readonly' => TRUE,
];
foreach($connect_db as $conn) {
  $dsn = "mysql:host=".$conn['host'].";port=".$conn['port'].";dbname=".$conn['database'];
  try{
    $pdo = new PDO($dsn, $conn['username'], $conn['password']);
    $databases['default']['default'] = $conn;
    break;
  }
  catch (PDOException $e) {
    //Do nothing
  }
}
mubasshir khan’s picture

@Simanta Can you tell me how to tested it over Drupal 8 means can you give me brief explain please  i really need it.

vaibhavdeep’s picture

To apply the slave or replica server, we have to focus on views and db_static. In Views -> ADVANCED Tab -> Query settings -> "check" the Use Slave Server(D7) and Use Secondary Server(D8) checkbox to apply the slave/replica server.

For db_query():

$result = db_query("SELECT nid, title FROM {node}", array(), array(
  'target' => 'replica',
  'fetch' => PDO::FETCH_ASSOC,
));

Changes in settings.php file

$databases['default']['default'] = array (
   'database'=>'drupaldb',
   'username'=>'masteruser',
   'host'=>'database-master.com'
   ...
);
$databases['default']['replica'] = array (
   'database'=>'drupaldb',
   'username'=>'slaveuser',
   'host'=>'database-slave.com'
   ...
);

Thanks

jeetmail72’s picture

I am trying to run the SELECT query on the replica database but not working. Please look at my configuration:

settings.php

$databases['default']['default'] = [
  'database' => 'drupal9',
  'username' => 'root',
  'password' => 'root@123456',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
];
$databases['default']['replica'] = [
  'database' => 'test',
  'username' => 'root',
  'password' => 'root@123456',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
];

In controller:

Working:

  

$connection = \Drupal\Core\Database\Database::getConnection('replica');
$result = $connection->query('SELECT * FROM employee');
while ($row = $result->fetchAssoc()) {
  echo '<pre>'; print_r($row); echo '</pre>';
}

Not working:
 

    $result = $connection->query('SELECT * FROM employee', [], ['target' => 'replica']);
    while ($row = $result->fetchAssoc()) {
      echo '<pre>'; print_r($row); echo '</pre>';
    }

Why above code is not working?

mmjvb’s picture

See https://www.drupal.org/node/2993033

  public function query($query, array $args = [], $options = []) {
    // Use default values if not already set.
    $options += $this->defaultOptions();
    assert(!isset($options['target']), 'Passing "target" option to query() has n
o effect. See https://www.drupal.org/node/2993033');
jeetmail72’s picture

Thanks @mmjvb

Now it is working as below:

    $connection = \Drupal::service('database.replica');
    $result = $connection->query('SELECT * FROM employee', [], [
      'fetch' => \PDO::FETCH_ASSOC,
    ]);
    while ($row = $result->fetchAssoc()) {
      echo '<pre>'; print_r($row); echo '</pre>';
    }