3e9aaff1958cc3c1586bebf038cf12ed905ba310
4 * Class to store objects in the database
8 class SqlBagOStuff
extends BagOStuff
{
20 var $lastExpireAll = 0;
21 var $purgePeriod = 100;
23 var $tableName = 'objectcache';
26 * Constructor. Parameters are:
27 * - server: A server info structure in the format required by each
28 * element in $wgDBServers.
30 * - purgePeriod: The average number of object cache requests in between
31 * garbage collection operations, where expired entries
32 * are removed from the database. Or in other words, the
33 * reciprocal of the probability of purging on any given
34 * request. If this is set to zero, purging will never be
37 * - tableName: The table name to use, default is "objectcache".
39 * - shards: The number of tables to use for data storage. If this is
40 * more than 1, table names will be formed in the style
41 * objectcacheNNN where NNN is the shard index, between 0 and
42 * shards-1. The number of digits will be the minimum number
43 * required to hold the largest shard index. Data will be
44 * distributed across all tables by key hash. This is for
45 * MySQL bugs 61735 and 61736.
47 * @param $params array
49 public function __construct( $params ) {
50 if ( isset( $params['server'] ) ) {
51 $this->serverInfo
= $params['server'];
52 $this->serverInfo
['load'] = 1;
54 if ( isset( $params['purgePeriod'] ) ) {
55 $this->purgePeriod
= intval( $params['purgePeriod'] );
57 if ( isset( $params['tableName'] ) ) {
58 $this->tableName
= $params['tableName'];
60 if ( isset( $params['shards'] ) ) {
61 $this->shards
= intval( $params['shards'] );
66 * @return DatabaseBase
68 protected function getDB() {
69 if ( !isset( $this->db
) ) {
70 # If server connection info was given, use that
71 if ( $this->serverInfo
) {
72 $this->lb
= new LoadBalancer( array(
73 'servers' => array( $this->serverInfo
) ) );
74 $this->db
= $this->lb
->getConnection( DB_MASTER
);
75 $this->db
->clearFlag( DBO_TRX
);
77 # We must keep a separate connection to MySQL in order to avoid deadlocks
78 # However, SQLite has an opposite behaviour.
79 # @todo Investigate behaviour for other databases
80 if ( wfGetDB( DB_MASTER
)->getType() == 'sqlite' ) {
81 $this->db
= wfGetDB( DB_MASTER
);
83 $this->lb
= wfGetLBFactory()->newMainLB();
84 $this->db
= $this->lb
->getConnection( DB_MASTER
);
85 $this->db
->clearFlag( DBO_TRX
);
94 * Get the table name for a given key
97 protected function getTableByKey( $key ) {
98 if ( $this->shards
> 1 ) {
99 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
100 return $this->getTableByShard( $hash %
$this->shards
);
102 return $this->tableName
;
107 * Get the table name for a given shard index
110 protected function getTableByShard( $index ) {
111 if ( $this->shards
> 1 ) {
112 $decimals = strlen( $this->shards
- 1 );
113 return $this->tableName
.
114 sprintf( "%0{$decimals}d", $index );
116 return $this->tableName
;
120 public function get( $key ) {
121 $values = $this->getBatch( array( $key ) );
122 return $values[$key];
125 public function getBatch( array $keys ) {
126 $values = array(); // array of (key => value)
128 $keysByTableName = array();
129 foreach ( $keys as $key ) {
130 $tableName = $this->getTableByKey( $key );
131 if ( !isset( $keysByTableName[$tableName] ) ) {
132 $keysByTableName[$tableName] = array();
134 $keysByTableName[$tableName][] = $key;
137 $db = $this->getDB();
138 $this->garbageCollect(); // expire old entries if any
141 foreach ( $keysByTableName as $tableName => $tableKeys ) {
142 $res = $db->select( $tableName,
143 array( 'keyname', 'value', 'exptime' ),
144 array( 'keyname' => $tableKeys ),
146 foreach ( $res as $row ) {
147 $dataRows[$row->keyname
] = $row;
151 foreach ( $keys as $key ) {
152 if ( isset( $dataRows[$key] ) ) { // HIT?
153 $row = $dataRows[$key];
154 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
155 if ( $this->isExpired( $row->exptime
) ) { // MISS
156 $this->debug( "get: key has expired, deleting" );
158 $db->begin( __METHOD__
);
159 # Put the expiry time in the WHERE condition to avoid deleting a
160 # newly-inserted value
161 $db->delete( $this->getTableByKey( $key ),
162 array( 'keyname' => $key, 'exptime' => $row->exptime
),
164 $db->commit( __METHOD__
);
165 } catch ( DBQueryError
$e ) {
166 $this->handleWriteError( $e );
168 $values[$key] = false;
170 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
173 $values[$key] = false;
174 $this->debug( 'get: no matching rows' );
181 public function set( $key, $value, $exptime = 0 ) {
182 $db = $this->getDB();
183 $exptime = intval( $exptime );
185 if ( $exptime < 0 ) {
189 if ( $exptime == 0 ) {
190 $encExpiry = $this->getMaxDateTime();
192 if ( $exptime < 3.16e8
) { # ~10 years
196 $encExpiry = $db->timestamp( $exptime );
199 $db->begin( __METHOD__
);
200 // (bug 24425) use a replace if the db supports it instead of
201 // delete/insert to avoid clashes with conflicting keynames
203 $this->getTableByKey( $key ),
207 'value' => $db->encodeBlob( $this->serialize( $value ) ),
208 'exptime' => $encExpiry
210 $db->commit( __METHOD__
);
211 } catch ( DBQueryError
$e ) {
212 $this->handleWriteError( $e );
220 public function delete( $key, $time = 0 ) {
221 $db = $this->getDB();
224 $db->begin( __METHOD__
);
226 $this->getTableByKey( $key ),
227 array( 'keyname' => $key ),
229 $db->commit( __METHOD__
);
230 } catch ( DBQueryError
$e ) {
231 $this->handleWriteError( $e );
239 public function incr( $key, $step = 1 ) {
240 $db = $this->getDB();
241 $tableName = $this->getTableByKey( $key );
242 $step = intval( $step );
245 $db->begin( __METHOD__
);
246 $row = $db->selectRow(
248 array( 'value', 'exptime' ),
249 array( 'keyname' => $key ),
251 array( 'FOR UPDATE' ) );
252 if ( $row === false ) {
254 $db->commit( __METHOD__
);
258 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
259 if ( $this->isExpired( $row->exptime
) ) {
260 // Expired, do not reinsert
261 $db->commit( __METHOD__
);
266 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
267 $newValue = $oldValue +
$step;
268 $db->insert( $tableName,
271 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
272 'exptime' => $row->exptime
273 ), __METHOD__
, 'IGNORE' );
275 if ( $db->affectedRows() == 0 ) {
276 // Race condition. See bug 28611
279 $db->commit( __METHOD__
);
280 } catch ( DBQueryError
$e ) {
281 $this->handleWriteError( $e );
289 public function keys() {
290 $db = $this->getDB();
293 for ( $i = 0; $i < $this->shards
; $i++
) {
294 $res = $db->select( $this->getTableByShard( $i ),
295 array( 'keyname' ), false, __METHOD__
);
296 foreach ( $res as $row ) {
297 $result[] = $row->keyname
;
304 protected function isExpired( $exptime ) {
305 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
308 protected function getMaxDateTime() {
309 if ( time() > 0x7fffffff ) {
310 return $this->getDB()->timestamp( 1 << 62 );
312 return $this->getDB()->timestamp( 0x7fffffff );
316 protected function garbageCollect() {
317 if ( !$this->purgePeriod
) {
321 // Only purge on one in every $this->purgePeriod requests.
322 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
326 // Avoid repeating the delete within a few seconds
327 if ( $now > ( $this->lastExpireAll +
1 ) ) {
328 $this->lastExpireAll
= $now;
333 public function expireAll() {
334 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
338 * Delete objects from the database which expire before a certain date.
341 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
342 $db = $this->getDB();
343 $dbTimestamp = $db->timestamp( $timestamp );
344 $totalSeconds = false;
345 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
348 for ( $i = 0; $i < $this->shards
; $i++
) {
352 if ( $maxExpTime !== false ) {
353 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
356 $this->getTableByShard( $i ),
357 array( 'keyname', 'exptime' ),
360 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
361 if ( !$rows->numRows() ) {
365 $row = $rows->current();
366 $minExpTime = $row->exptime
;
367 if ( $totalSeconds === false ) {
368 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
369 - wfTimestamp( TS_UNIX
, $minExpTime );
371 foreach ( $rows as $row ) {
372 $keys[] = $row->keyname
;
373 $maxExpTime = $row->exptime
;
376 $db->begin( __METHOD__
);
378 $this->getTableByShard( $i ),
380 'exptime >= ' . $db->addQuotes( $minExpTime ),
381 'exptime < ' . $db->addQuotes( $dbTimestamp ),
385 $db->commit( __METHOD__
);
387 if ( $progressCallback ) {
388 if ( intval( $totalSeconds ) === 0 ) {
391 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
392 - wfTimestamp( TS_UNIX
, $maxExpTime );
393 if ( $remainingSeconds > $totalSeconds ) {
394 $totalSeconds = $remainingSeconds;
396 $percent = ( $i +
$remainingSeconds / $totalSeconds )
397 / $this->shards
* 100;
399 call_user_func( $progressCallback, $percent );
403 } catch ( DBQueryError
$e ) {
404 $this->handleWriteError( $e );
409 public function deleteAll() {
410 $db = $this->getDB();
413 for ( $i = 0; $i < $this->shards
; $i++
) {
414 $db->begin( __METHOD__
);
415 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
416 $db->commit( __METHOD__
);
418 } catch ( DBQueryError
$e ) {
419 $this->handleWriteError( $e );
424 * Serialize an object and, if possible, compress the representation.
425 * On typical message and page data, this can provide a 3X decrease
426 * in storage requirements.
431 protected function serialize( &$data ) {
432 $serial = serialize( $data );
434 if ( function_exists( 'gzdeflate' ) ) {
435 return gzdeflate( $serial );
442 * Unserialize and, if necessary, decompress an object.
443 * @param $serial string
446 protected function unserialize( $serial ) {
447 if ( function_exists( 'gzinflate' ) ) {
448 wfSuppressWarnings();
449 $decomp = gzinflate( $serial );
452 if ( false !== $decomp ) {
457 $ret = unserialize( $serial );
463 * Handle a DBQueryError which occurred during a write operation.
464 * Ignore errors which are due to a read-only database, rethrow others.
466 protected function handleWriteError( $exception ) {
467 $db = $this->getDB();
469 if ( !$db->wasReadOnlyError() ) {
474 $db->rollback( __METHOD__
);
475 } catch ( DBQueryError
$e ) {
478 wfDebug( __METHOD__
. ": ignoring query error\n" );
479 $db->ignoreErrors( false );
483 * Create shard tables. For use from eval.php.
485 public function createTables() {
486 $db = $this->getDB();
487 if ( $db->getType() !== 'mysql'
488 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
490 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
493 for ( $i = 0; $i < $this->shards
; $i++
) {
494 $db->begin( __METHOD__
);
496 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
497 ' LIKE ' . $db->tableName( 'objectcache' ),
499 $db->commit( __METHOD__
);
505 * Backwards compatibility alias
507 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }