3 namespace Wikimedia\Rdbms
;
9 * Database connection manager.
11 * This manages access to master and slave databases. It also manages state that indicates whether
12 * the slave databases are possibly outdated after a write operation, and thus the master database
13 * should be used for subsequent read operations.
15 * @note: Services that access overlapping sets of database tables, or interact with logically
16 * related sets of data in the database, should share a SessionConsistentConnectionManager.
17 * Services accessing unrelated sets of information may prefer to not share a
18 * SessionConsistentConnectionManager, so they can still perform read operations against slave
19 * databases after a (unrelated, per the assumption) write operation to the master database.
20 * Generally, sharing a SessionConsistentConnectionManager improves consistency (by avoiding race
21 * conditions due to replication lag), but can reduce performance (by directing more read
22 * operations to the master database server).
27 * @author Daniel Kinzler
30 class SessionConsistentConnectionManager
extends ConnectionManager
{
35 private $forceWriteConnection = false;
38 * Forces all future calls to getReadConnection() to return a write connection.
39 * Use this before performing read operations that are critical for a future update.
40 * Calling beginAtomicSection() implies a call to prepareForUpdates().
44 public function prepareForUpdates() {
45 $this->forceWriteConnection
= true;
51 * @param string[]|null $groups
55 public function getReadConnection( array $groups = null ) {
56 if ( $this->forceWriteConnection
) {
57 return parent
::getWriteConnection();
60 return parent
::getReadConnection( $groups );
68 public function getWriteConnection() {
69 $this->prepareForUpdates();
70 return parent
::getWriteConnection();
76 * @param string[]|null $groups
80 public function getReadConnectionRef( array $groups = null ) {
81 if ( $this->forceWriteConnection
) {
82 return parent
::getWriteConnectionRef();
85 return parent
::getReadConnectionRef( $groups );
93 public function getWriteConnectionRef() {
94 $this->prepareForUpdates();
95 return parent
::getWriteConnectionRef();
99 * Begins an atomic section and returns a database connection to the master DB, for updating.
103 * @note: This causes all future calls to getReadConnection() to return a connection
104 * to the master DB, even after commitAtomicSection() or rollbackAtomicSection() have
107 * @param string $fname
111 public function beginAtomicSection( $fname ) {
112 // Once we have written to master, do not read from replica.
113 $this->prepareForUpdates();
115 return parent
::beginAtomicSection( $fname );