Removing the obsolete messages "sysoptitle", "sysoptext", "developertitle" and "devel...
[lhc/web/wiklou.git] / docs / database.txt
1 Some information about database access in MediaWiki.
2 By Tim Starling, January 2006.
3
4 ------------------------------------------------------------------------
5 API
6 ------------------------------------------------------------------------
7
8 For a database API reference, please see the auto-generated
9 documentation:
10
11 http://wikipedia.sourceforge.net/doc/MediaWiki/Database.html
12
13 To make a read query, something like this usually suffices:
14
15 $dbr =& wfGetDB( DB_SLAVE );
16 $res = $dbr->select( /* ...see docs... */ );
17 while ( $row = $dbr->fetchObject( $res ) ) {
18 ...
19 }
20 $dbr->freeResult( $res );
21
22 Note the assignment operator in the while condition.
23
24 For a write query, use something like:
25
26 $dbw =& wfGetDB( DB_MASTER );
27 $dbw->insert( /* ...see docs... */ );
28
29 We use the convention $dbr for read and $dbw for write to help you keep
30 track of whether the database object is a slave (read-only) or a master
31 (read/write). If you write to a slave, the world will explode. Or to be
32 precise, a subsequent write query which succeeded on the master may fail
33 when replicated to the slave due to a unique key collision. Replication
34 on the slave will stop and it may take hours to repair the database and
35 get it back online. Setting read_only in my.cnf on the slave will avoid
36 this scenario, but given the dire consequences, we prefer to have as
37 many checks as possible.
38
39 We provide a query() function for raw SQL, but the wrapper functions
40 like select() and insert() are usually more convenient. They take care
41 of things like table prefixes and escaping for you. If you really need
42 to make your own SQL, please read the documentation for tableName() and
43 addQuotes(). You will need both of them.
44
45
46 ------------------------------------------------------------------------
47 Basic query optimisation
48 ------------------------------------------------------------------------
49
50 MediaWiki developers who need to write DB queries should have some
51 understanding of databases and the performance issues associated with
52 them. Patches containing unacceptably slow features will not be
53 accepted. Unindexed queries are generally not welcome in MediaWiki,
54 except in special pages derived from QueryPage. It's a common pitfall
55 for new developers to submit code containing SQL queries which examine
56 huge numbers of rows. Remember that COUNT(*) is O(N), counting rows in a
57 table is like counting beans in a bucket.
58
59
60 ------------------------------------------------------------------------
61 Replication
62 ------------------------------------------------------------------------
63
64 The largest installation of MediaWiki, Wikimedia, uses a large set of
65 slave MySQL servers replicating writes made to a master MySQL server. It
66 is important to understand the issues associated with this setup if you
67 want to write code destined for Wikipedia.
68
69 It's often the case that the best algorithm to use for a given task
70 depends on whether or not replication is in use. Due to our unabashed
71 Wikipedia-centrism, we often just use the replication-friendly version,
72 but if you like, you can use $wgLoadBalancer->getServerCount() > 1 to
73 check to see if replication is in use.
74
75 === Lag ===
76
77 Lag primarily occurs when large write queries are sent to the master.
78 Writes on the master are executed in parallel, but they are executed in
79 serial when they are replicated to the slaves. The master writes the
80 query to the binlog when the transaction is committed. The slaves poll
81 the binlog and start executing the query as soon as it appears. They can
82 service reads while they are performing a write query, but will not read
83 anything more from the binlog and thus will perform no more writes. This
84 means that if the write query runs for a long time, the slaves will lag
85 behind the master for the time it takes for the write query to complete.
86
87 Lag can be exacerbated by high read load. MediaWiki's load balancer will
88 stop sending reads to a slave when it is lagged by more than 30 seconds.
89 If the load ratios are set incorrectly, or if there is too much load
90 generally, this may lead to a slave permanently hovering around 30
91 seconds lag.
92
93 If all slaves are lagged by more than 30 seconds, MediaWiki will stop
94 writing to the database. All edits and other write operations will be
95 refused, with an error returned to the user. This gives the slaves a
96 chance to catch up. Before we had this mechanism, the slaves would
97 regularly lag by several minutes, making review of recent edits
98 difficult.
99
100 In addition to this, MediaWiki attempts to ensure that the user sees
101 events occuring on the wiki in chronological order. A few seconds of lag
102 can be tolerated, as long as the user sees a consistent picture from
103 subsequent requests. This is done by saving the master binlog position
104 in the session, and then at the start of each request, waiting for the
105 slave to catch up to that position before doing any reads from it. If
106 this wait times out, reads are allowed anyway, but the request is
107 considered to be in "lagged slave mode". Lagged slave mode can be
108 checked by calling $wgLoadBalancer->getLaggedSlaveMode(). The only
109 practical consequence at present is a warning displayed in the page
110 footer.
111
112 === Lag avoidance ===
113
114 To avoid excessive lag, queries which write large numbers of rows should
115 be split up, generally to write one row at a time. Multi-row INSERT ...
116 SELECT queries are the worst offenders should be avoided altogether.
117 Instead do the select first and then the insert.
118
119 === Working with lag ===
120
121 Despite our best efforts, it's not practical to guarantee a low-lag
122 environment. Lag will usually be less than one second, but may
123 occasionally be up to 30 seconds. For scalability, it's very important
124 to keep load on the master low, so simply sending all your queries to
125 the master is not the answer. So when you have a genuine need for
126 up-to-date data, the following approach is advised:
127
128 1) Do a quick query to the master for a sequence number or timestamp 2)
129 Run the full query on the slave and check if it matches the data you got
130 from the master 3) If it doesn't, run the full query on the master
131
132 To avoid swamping the master every time the slaves lag, use of this
133 approach should be kept to a minimum. In most cases you should just read
134 from the slave and let the user deal with the delay.
135
136
137 ------------------------------------------------------------------------
138 Lock contention
139 ------------------------------------------------------------------------
140
141 Due to the high write rate on Wikipedia (and some other wikis),
142 MediaWiki developers need to be very careful to structure their writes
143 to avoid long-lasting locks. By default, MediaWiki opens a transaction
144 at the first query, and commits it before the output is sent. Locks will
145 be held from the time when the query is done until the commit. So you
146 can reduce lock time by doing as much processing as possible before you
147 do your write queries. Update operations which do not require database
148 access can be delayed until after the commit by adding an object to
149 $wgPostCommitUpdateList.
150
151 Often this approach is not good enough, and it becomes necessary to
152 enclose small groups of queries in their own transaction. Use the
153 following syntax:
154
155 $dbw =& wfGetDB( DB_MASTER );
156 $dbw->immediateBegin();
157 /* Do queries */
158 $dbw->immediateCommit();
159
160 There are functions called begin() and commit() but they don't do what
161 you would expect. Don't use them.
162
163 Use of locking reads (e.g. the FOR UPDATE clause) is not advised. They
164 are poorly implemented in InnoDB and will cause regular deadlock errors.
165 It's also surprisingly easy to cripple the wiki with lock contention. If
166 you must use them, define a new flag for $wgAntiLockFlags which allows
167 them to be turned off, because we'll almost certainly need to do so on
168 the Wikimedia cluster.
169
170 Instead of locking reads, combine your existence checks into your write
171 queries, by using an appropriate condition in the WHERE clause of an
172 UPDATE, or by using unique indexes in combination with INSERT IGNORE.
173 Then use the affected row count to see if the query succeeded.
174