Merge "Revert "Remove old remapping hacks from Database::indexName()""
[lhc/web/wiklou.git] / includes / libs / rdbms / connectionmanager / SessionConsistentConnectionManager.php
1 <?php
2
3 namespace Wikimedia\Rdbms;
4
5 use Database;
6
7 /**
8 * Database connection manager.
9 *
10 * This manages access to master and replica databases. It also manages state that indicates whether
11 * the replica databases are possibly outdated after a write operation, and thus the master database
12 * should be used for subsequent read operations.
13 *
14 * @note: Services that access overlapping sets of database tables, or interact with logically
15 * related sets of data in the database, should share a SessionConsistentConnectionManager.
16 * Services accessing unrelated sets of information may prefer to not share a
17 * SessionConsistentConnectionManager, so they can still perform read operations against replica
18 * databases after a (unrelated, per the assumption) write operation to the master database.
19 * Generally, sharing a SessionConsistentConnectionManager improves consistency (by avoiding race
20 * conditions due to replication lag), but can reduce performance (by directing more read
21 * operations to the master database server).
22 *
23 * @since 1.29
24 *
25 * @license GPL-2.0+
26 * @author Daniel Kinzler
27 * @author Addshore
28 */
29 class SessionConsistentConnectionManager extends ConnectionManager {
30
31 /**
32 * @var bool
33 */
34 private $forceWriteConnection = false;
35
36 /**
37 * Forces all future calls to getReadConnection() to return a write connection.
38 * Use this before performing read operations that are critical for a future update.
39 *
40 * @since 1.29
41 */
42 public function prepareForUpdates() {
43 $this->forceWriteConnection = true;
44 }
45
46 /**
47 * @since 1.29
48 *
49 * @param string[]|null $groups
50 *
51 * @return Database
52 */
53 public function getReadConnection( array $groups = null ) {
54 if ( $this->forceWriteConnection ) {
55 return parent::getWriteConnection();
56 }
57
58 return parent::getReadConnection( $groups );
59 }
60
61 /**
62 * @since 1.29
63 *
64 * @return Database
65 */
66 public function getWriteConnection() {
67 $this->prepareForUpdates();
68 return parent::getWriteConnection();
69 }
70
71 /**
72 * @since 1.29
73 *
74 * @param string[]|null $groups
75 *
76 * @return DBConnRef
77 */
78 public function getReadConnectionRef( array $groups = null ) {
79 if ( $this->forceWriteConnection ) {
80 return parent::getWriteConnectionRef();
81 }
82
83 return parent::getReadConnectionRef( $groups );
84 }
85
86 /**
87 * @since 1.29
88 *
89 * @return DBConnRef
90 */
91 public function getWriteConnectionRef() {
92 $this->prepareForUpdates();
93 return parent::getWriteConnectionRef();
94 }
95
96 }