4dfa5743ddbe9c0e862bdbbd70c51b0c86b07954
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 # expire old entries if any
122 $this->garbageCollect();
123 $db = $this->getDB();
124 $tableName = $this->getTableByKey( $key );
125 $row = $db->selectRow( $tableName, array( 'value', 'exptime' ),
126 array( 'keyname' => $key ), __METHOD__
);
129 $this->debug( 'get: no matching rows' );
133 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
135 if ( $this->isExpired( $row->exptime
) ) {
136 $this->debug( "get: key has expired, deleting" );
138 $db->begin( __METHOD__
);
139 # Put the expiry time in the WHERE condition to avoid deleting a
140 # newly-inserted value
141 $db->delete( $tableName,
144 'exptime' => $row->exptime
146 $db->commit( __METHOD__
);
147 } catch ( DBQueryError
$e ) {
148 $this->handleWriteError( $e );
154 return $this->unserialize( $db->decodeBlob( $row->value
) );
157 public function set( $key, $value, $exptime = 0 ) {
158 $db = $this->getDB();
159 $exptime = intval( $exptime );
161 if ( $exptime < 0 ) {
165 if ( $exptime == 0 ) {
166 $encExpiry = $this->getMaxDateTime();
168 if ( $exptime < 3.16e8
) { # ~10 years
172 $encExpiry = $db->timestamp( $exptime );
175 $db->begin( __METHOD__
);
176 // (bug 24425) use a replace if the db supports it instead of
177 // delete/insert to avoid clashes with conflicting keynames
179 $this->getTableByKey( $key ),
183 'value' => $db->encodeBlob( $this->serialize( $value ) ),
184 'exptime' => $encExpiry
186 $db->commit( __METHOD__
);
187 } catch ( DBQueryError
$e ) {
188 $this->handleWriteError( $e );
196 public function delete( $key, $time = 0 ) {
197 $db = $this->getDB();
200 $db->begin( __METHOD__
);
202 $this->getTableByKey( $key ),
203 array( 'keyname' => $key ),
205 $db->commit( __METHOD__
);
206 } catch ( DBQueryError
$e ) {
207 $this->handleWriteError( $e );
215 public function incr( $key, $step = 1 ) {
216 $db = $this->getDB();
217 $tableName = $this->getTableByKey( $key );
218 $step = intval( $step );
221 $db->begin( __METHOD__
);
222 $row = $db->selectRow(
224 array( 'value', 'exptime' ),
225 array( 'keyname' => $key ),
227 array( 'FOR UPDATE' ) );
228 if ( $row === false ) {
230 $db->commit( __METHOD__
);
234 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
235 if ( $this->isExpired( $row->exptime
) ) {
236 // Expired, do not reinsert
237 $db->commit( __METHOD__
);
242 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
243 $newValue = $oldValue +
$step;
244 $db->insert( $tableName,
247 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
248 'exptime' => $row->exptime
249 ), __METHOD__
, 'IGNORE' );
251 if ( $db->affectedRows() == 0 ) {
252 // Race condition. See bug 28611
255 $db->commit( __METHOD__
);
256 } catch ( DBQueryError
$e ) {
257 $this->handleWriteError( $e );
265 public function keys() {
266 $db = $this->getDB();
269 for ( $i = 0; $i < $this->shards
; $i++
) {
270 $res = $db->select( $this->getTableByShard( $i ),
271 array( 'keyname' ), false, __METHOD__
);
272 foreach ( $res as $row ) {
273 $result[] = $row->keyname
;
280 protected function isExpired( $exptime ) {
281 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
284 protected function getMaxDateTime() {
285 if ( time() > 0x7fffffff ) {
286 return $this->getDB()->timestamp( 1 << 62 );
288 return $this->getDB()->timestamp( 0x7fffffff );
292 protected function garbageCollect() {
293 if ( !$this->purgePeriod
) {
297 // Only purge on one in every $this->purgePeriod requests.
298 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
302 // Avoid repeating the delete within a few seconds
303 if ( $now > ( $this->lastExpireAll +
1 ) ) {
304 $this->lastExpireAll
= $now;
309 public function expireAll() {
310 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
314 * Delete objects from the database which expire before a certain date.
317 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
318 $db = $this->getDB();
319 $dbTimestamp = $db->timestamp( $timestamp );
320 $totalSeconds = false;
321 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
324 for ( $i = 0; $i < $this->shards
; $i++
) {
328 if ( $maxExpTime !== false ) {
329 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
332 $this->getTableByShard( $i ),
333 array( 'keyname', 'exptime' ),
336 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
337 if ( !$rows->numRows() ) {
341 $row = $rows->current();
342 $minExpTime = $row->exptime
;
343 if ( $totalSeconds === false ) {
344 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
345 - wfTimestamp( TS_UNIX
, $minExpTime );
347 foreach ( $rows as $row ) {
348 $keys[] = $row->keyname
;
349 $maxExpTime = $row->exptime
;
352 $db->begin( __METHOD__
);
354 $this->getTableByShard( $i ),
356 'exptime >= ' . $db->addQuotes( $minExpTime ),
357 'exptime < ' . $db->addQuotes( $dbTimestamp ),
361 $db->commit( __METHOD__
);
363 if ( $progressCallback ) {
364 if ( intval( $totalSeconds ) === 0 ) {
367 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
368 - wfTimestamp( TS_UNIX
, $maxExpTime );
369 if ( $remainingSeconds > $totalSeconds ) {
370 $totalSeconds = $remainingSeconds;
372 $percent = ( $i +
$remainingSeconds / $totalSeconds )
373 / $this->shards
* 100;
375 call_user_func( $progressCallback, $percent );
379 } catch ( DBQueryError
$e ) {
380 $this->handleWriteError( $e );
385 public function deleteAll() {
386 $db = $this->getDB();
389 for ( $i = 0; $i < $this->shards
; $i++
) {
390 $db->begin( __METHOD__
);
391 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
392 $db->commit( __METHOD__
);
394 } catch ( DBQueryError
$e ) {
395 $this->handleWriteError( $e );
400 * Serialize an object and, if possible, compress the representation.
401 * On typical message and page data, this can provide a 3X decrease
402 * in storage requirements.
407 protected function serialize( &$data ) {
408 $serial = serialize( $data );
410 if ( function_exists( 'gzdeflate' ) ) {
411 return gzdeflate( $serial );
418 * Unserialize and, if necessary, decompress an object.
419 * @param $serial string
422 protected function unserialize( $serial ) {
423 if ( function_exists( 'gzinflate' ) ) {
424 wfSuppressWarnings();
425 $decomp = gzinflate( $serial );
428 if ( false !== $decomp ) {
433 $ret = unserialize( $serial );
439 * Handle a DBQueryError which occurred during a write operation.
440 * Ignore errors which are due to a read-only database, rethrow others.
442 protected function handleWriteError( $exception ) {
443 $db = $this->getDB();
445 if ( !$db->wasReadOnlyError() ) {
450 $db->rollback( __METHOD__
);
451 } catch ( DBQueryError
$e ) {
454 wfDebug( __METHOD__
. ": ignoring query error\n" );
455 $db->ignoreErrors( false );
459 * Create shard tables. For use from eval.php.
461 public function createTables() {
462 $db = $this->getDB();
463 if ( $db->getType() !== 'mysql'
464 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
466 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
469 for ( $i = 0; $i < $this->shards
; $i++
) {
470 $db->begin( __METHOD__
);
472 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
473 ' LIKE ' . $db->tableName( 'objectcache' ),
475 $db->commit( __METHOD__
);
481 * Backwards compatibility alias
483 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }