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
96 protected function getTableByKey( $key ) {
97 if ( $this->shards
> 1 ) {
98 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
99 return $this->getTableByShard( $hash %
$this->shards
);
101 return $this->tableName
;
106 * Get the table name for a given shard index
108 protected function getTableByShard( $index ) {
109 if ( $this->shards
> 1 ) {
110 $decimals = strlen( $this->shards
- 1 );
111 return $this->tableName
.
112 sprintf( "%0{$decimals}d", $index );
114 return $this->tableName
;
118 public function get( $key ) {
119 # expire old entries if any
120 $this->garbageCollect();
121 $db = $this->getDB();
122 $tableName = $this->getTableByKey( $key );
123 $row = $db->selectRow( $tableName, array( 'value', 'exptime' ),
124 array( 'keyname' => $key ), __METHOD__
);
127 $this->debug( 'get: no matching rows' );
131 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
133 if ( $this->isExpired( $row->exptime
) ) {
134 $this->debug( "get: key has expired, deleting" );
137 # Put the expiry time in the WHERE condition to avoid deleting a
138 # newly-inserted value
139 $db->delete( $tableName,
142 'exptime' => $row->exptime
145 } catch ( DBQueryError
$e ) {
146 $this->handleWriteError( $e );
152 return $this->unserialize( $db->decodeBlob( $row->value
) );
155 public function set( $key, $value, $exptime = 0 ) {
156 $db = $this->getDB();
157 $exptime = intval( $exptime );
159 if ( $exptime < 0 ) {
163 if ( $exptime == 0 ) {
164 $encExpiry = $this->getMaxDateTime();
166 if ( $exptime < 3.16e8
) { # ~10 years
170 $encExpiry = $db->timestamp( $exptime );
174 // (bug 24425) use a replace if the db supports it instead of
175 // delete/insert to avoid clashes with conflicting keynames
177 $this->getTableByKey( $key ),
181 'value' => $db->encodeBlob( $this->serialize( $value ) ),
182 'exptime' => $encExpiry
185 } catch ( DBQueryError
$e ) {
186 $this->handleWriteError( $e );
194 public function delete( $key, $time = 0 ) {
195 $db = $this->getDB();
200 $this->getTableByKey( $key ),
201 array( 'keyname' => $key ),
204 } catch ( DBQueryError
$e ) {
205 $this->handleWriteError( $e );
213 public function incr( $key, $step = 1 ) {
214 $db = $this->getDB();
215 $tableName = $this->getTableByKey( $key );
216 $step = intval( $step );
220 $row = $db->selectRow(
222 array( 'value', 'exptime' ),
223 array( 'keyname' => $key ),
225 array( 'FOR UPDATE' ) );
226 if ( $row === false ) {
232 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
233 if ( $this->isExpired( $row->exptime
) ) {
234 // Expired, do not reinsert
240 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
241 $newValue = $oldValue +
$step;
242 $db->insert( $tableName,
245 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
246 'exptime' => $row->exptime
247 ), __METHOD__
, 'IGNORE' );
249 if ( $db->affectedRows() == 0 ) {
250 // Race condition. See bug 28611
254 } catch ( DBQueryError
$e ) {
255 $this->handleWriteError( $e );
263 public function keys() {
264 $db = $this->getDB();
267 for ( $i = 0; $i < $this->shards
; $i++
) {
268 $res = $db->select( $this->getTableByShard( $i ),
269 array( 'keyname' ), false, __METHOD__
);
270 foreach ( $res as $row ) {
271 $result[] = $row->keyname
;
278 protected function isExpired( $exptime ) {
279 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
282 protected function getMaxDateTime() {
283 if ( time() > 0x7fffffff ) {
284 return $this->getDB()->timestamp( 1 << 62 );
286 return $this->getDB()->timestamp( 0x7fffffff );
290 protected function garbageCollect() {
291 if ( !$this->purgePeriod
) {
295 // Only purge on one in every $this->purgePeriod requests.
296 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
300 // Avoid repeating the delete within a few seconds
301 if ( $now > ( $this->lastExpireAll +
1 ) ) {
302 $this->lastExpireAll
= $now;
307 public function expireAll() {
308 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
312 * Delete objects from the database which expire before a certain date.
314 public function deleteObjectsExpiringBefore( $timestamp ) {
315 $db = $this->getDB();
316 $dbTimestamp = $db->timestamp( $timestamp );
319 for ( $i = 0; $i < $this->shards
; $i++
) {
322 $this->getTableByShard( $i ),
323 array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) ),
327 } catch ( DBQueryError
$e ) {
328 $this->handleWriteError( $e );
333 public function deleteAll() {
334 $db = $this->getDB();
337 for ( $i = 0; $i < $this->shards
; $i++
) {
339 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
342 } catch ( DBQueryError
$e ) {
343 $this->handleWriteError( $e );
348 * Serialize an object and, if possible, compress the representation.
349 * On typical message and page data, this can provide a 3X decrease
350 * in storage requirements.
355 protected function serialize( &$data ) {
356 $serial = serialize( $data );
358 if ( function_exists( 'gzdeflate' ) ) {
359 return gzdeflate( $serial );
366 * Unserialize and, if necessary, decompress an object.
367 * @param $serial string
370 protected function unserialize( $serial ) {
371 if ( function_exists( 'gzinflate' ) ) {
372 wfSuppressWarnings();
373 $decomp = gzinflate( $serial );
376 if ( false !== $decomp ) {
381 $ret = unserialize( $serial );
387 * Handle a DBQueryError which occurred during a write operation.
388 * Ignore errors which are due to a read-only database, rethrow others.
390 protected function handleWriteError( $exception ) {
391 $db = $this->getDB();
393 if ( !$db->wasReadOnlyError() ) {
399 } catch ( DBQueryError
$e ) {
402 wfDebug( __METHOD__
. ": ignoring query error\n" );
403 $db->ignoreErrors( false );
407 * Create shard tables. For use from eval.php.
409 public function createTables() {
410 $db = $this->getDB();
411 if ( $db->getType() !== 'mysql'
412 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
414 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
417 for ( $i = 0; $i < $this->shards
; $i++
) {
420 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
421 ' LIKE ' . $db->tableName( 'objectcache' ),
429 * Backwards compatibility alias
431 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }