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