18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Appendix A<br />

Slave servers<br />

<strong>Drupal</strong> also supports Master/slave database replication. Certain select queries can<br />

be run against a slave server to offload the work to separate servers, allowing the site<br />

to scale better. However, most sites do not have a slave server configured, so how do<br />

we write code that will work properly either way?<br />

<strong>Drupal</strong> lets us do so by specifying "targets". The third parameter to db_query() or<br />

db_select() is an array of options that tweak the behavior of the query. We saw the<br />

fetch key earlier. The other key of interest is target, which specifies which database<br />

variant the system should try. Legal values are default (which is the default) and<br />

slave. If "slave" is specified, <strong>Drupal</strong> will try to run the query against a slave server. If<br />

one is not available, though, it will silently fall back to using the default server. Using<br />

our previous example:<br />

$result = db_query("SELECT name, filename FROM {system} WHERE type =<br />

:type AND status = :status", array(':type' => 'module', ':status' =><br />

1), array('fetch' => PDO::FETCH_ASSOC, 'target' => 'slave'));<br />

The way we handle the query is otherwise identical.<br />

So why don't all Select queries use the slave server? Data on a slave server is always<br />

a little behind the master server, by a fraction of a second or as much as a minute or<br />

two depending on the configuration and traffic. Not all Select queries can handle<br />

their data being slightly stale and there's no reliable way to detect automatically<br />

which are which, so by default all queries use the master server.<br />

However, there is another trick up our sleeve which we can use. After writing data,<br />

we can call db_ignore_slave(). That will make a note in the active session to<br />

disable the slave server for the current user only for a configurable period of time.<br />

(The default is five minutes.) That way, Select queries run on subsequent page<br />

requests by that user will always get the most up-to-date data but other users will<br />

get the old data until the slave servers catch up. That can be very useful, for instance,<br />

when a user posts a comment. They want to see the comment immediately but it's<br />

OK if other users don't see it for 20-30 seconds.<br />

[ 373 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!