3 * Object caching using a SQL database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Class to store objects in the database
29 class SqlBagOStuff
extends BagOStuff
{
41 var $lastExpireAll = 0;
42 var $purgePeriod = 100;
44 var $tableName = 'objectcache';
47 * Constructor. Parameters are:
48 * - server: A server info structure in the format required by each
49 * element in $wgDBServers.
51 * - purgePeriod: The average number of object cache requests in between
52 * garbage collection operations, where expired entries
53 * are removed from the database. Or in other words, the
54 * reciprocal of the probability of purging on any given
55 * request. If this is set to zero, purging will never be
58 * - tableName: The table name to use, default is "objectcache".
60 * - shards: The number of tables to use for data storage. If this is
61 * more than 1, table names will be formed in the style
62 * objectcacheNNN where NNN is the shard index, between 0 and
63 * shards-1. The number of digits will be the minimum number
64 * required to hold the largest shard index. Data will be
65 * distributed across all tables by key hash. This is for
66 * MySQL bugs 61735 and 61736.
68 * @param $params array
70 public function __construct( $params ) {
71 if ( isset( $params['server'] ) ) {
72 $this->serverInfo
= $params['server'];
73 $this->serverInfo
['load'] = 1;
75 if ( isset( $params['purgePeriod'] ) ) {
76 $this->purgePeriod
= intval( $params['purgePeriod'] );
78 if ( isset( $params['tableName'] ) ) {
79 $this->tableName
= $params['tableName'];
81 if ( isset( $params['shards'] ) ) {
82 $this->shards
= intval( $params['shards'] );
87 * @return DatabaseBase
89 protected function getDB() {
90 if ( !isset( $this->db
) ) {
91 # If server connection info was given, use that
92 if ( $this->serverInfo
) {
93 $this->lb
= new LoadBalancer( array(
94 'servers' => array( $this->serverInfo
) ) );
95 $this->db
= $this->lb
->getConnection( DB_MASTER
);
96 $this->db
->clearFlag( DBO_TRX
);
98 # We must keep a separate connection to MySQL in order to avoid deadlocks
99 # However, SQLite has an opposite behaviour.
100 # @todo Investigate behaviour for other databases
101 if ( wfGetDB( DB_MASTER
)->getType() == 'sqlite' ) {
102 $this->db
= wfGetDB( DB_MASTER
);
104 $this->lb
= wfGetLBFactory()->newMainLB();
105 $this->db
= $this->lb
->getConnection( DB_MASTER
);
106 $this->db
->clearFlag( DBO_TRX
);
115 * Get the table name for a given key
118 protected function getTableByKey( $key ) {
119 if ( $this->shards
> 1 ) {
120 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
121 return $this->getTableByShard( $hash %
$this->shards
);
123 return $this->tableName
;
128 * Get the table name for a given shard index
131 protected function getTableByShard( $index ) {
132 if ( $this->shards
> 1 ) {
133 $decimals = strlen( $this->shards
- 1 );
134 return $this->tableName
.
135 sprintf( "%0{$decimals}d", $index );
137 return $this->tableName
;
141 public function get( $key ) {
142 # expire old entries if any
143 $this->garbageCollect();
144 $db = $this->getDB();
145 $tableName = $this->getTableByKey( $key );
146 $row = $db->selectRow( $tableName, array( 'value', 'exptime' ),
147 array( 'keyname' => $key ), __METHOD__
);
150 $this->debug( 'get: no matching rows' );
154 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
156 if ( $this->isExpired( $row->exptime
) ) {
157 $this->debug( "get: key has expired, deleting" );
159 $db->begin( __METHOD__
);
160 # Put the expiry time in the WHERE condition to avoid deleting a
161 # newly-inserted value
162 $db->delete( $tableName,
165 'exptime' => $row->exptime
167 $db->commit( __METHOD__
);
168 } catch ( DBQueryError
$e ) {
169 $this->handleWriteError( $e );
175 return $this->unserialize( $db->decodeBlob( $row->value
) );
178 public function set( $key, $value, $exptime = 0 ) {
179 $db = $this->getDB();
180 $exptime = intval( $exptime );
182 if ( $exptime < 0 ) {
186 if ( $exptime == 0 ) {
187 $encExpiry = $this->getMaxDateTime();
189 if ( $exptime < 3.16e8
) { # ~10 years
193 $encExpiry = $db->timestamp( $exptime );
196 $db->begin( __METHOD__
);
197 // (bug 24425) use a replace if the db supports it instead of
198 // delete/insert to avoid clashes with conflicting keynames
200 $this->getTableByKey( $key ),
204 'value' => $db->encodeBlob( $this->serialize( $value ) ),
205 'exptime' => $encExpiry
207 $db->commit( __METHOD__
);
208 } catch ( DBQueryError
$e ) {
209 $this->handleWriteError( $e );
217 public function delete( $key, $time = 0 ) {
218 $db = $this->getDB();
221 $db->begin( __METHOD__
);
223 $this->getTableByKey( $key ),
224 array( 'keyname' => $key ),
226 $db->commit( __METHOD__
);
227 } catch ( DBQueryError
$e ) {
228 $this->handleWriteError( $e );
236 public function incr( $key, $step = 1 ) {
237 $db = $this->getDB();
238 $tableName = $this->getTableByKey( $key );
239 $step = intval( $step );
242 $db->begin( __METHOD__
);
243 $row = $db->selectRow(
245 array( 'value', 'exptime' ),
246 array( 'keyname' => $key ),
248 array( 'FOR UPDATE' ) );
249 if ( $row === false ) {
251 $db->commit( __METHOD__
);
255 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
256 if ( $this->isExpired( $row->exptime
) ) {
257 // Expired, do not reinsert
258 $db->commit( __METHOD__
);
263 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
264 $newValue = $oldValue +
$step;
265 $db->insert( $tableName,
268 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
269 'exptime' => $row->exptime
270 ), __METHOD__
, 'IGNORE' );
272 if ( $db->affectedRows() == 0 ) {
273 // Race condition. See bug 28611
276 $db->commit( __METHOD__
);
277 } catch ( DBQueryError
$e ) {
278 $this->handleWriteError( $e );
286 public function keys() {
287 $db = $this->getDB();
290 for ( $i = 0; $i < $this->shards
; $i++
) {
291 $res = $db->select( $this->getTableByShard( $i ),
292 array( 'keyname' ), false, __METHOD__
);
293 foreach ( $res as $row ) {
294 $result[] = $row->keyname
;
301 protected function isExpired( $exptime ) {
302 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
305 protected function getMaxDateTime() {
306 if ( time() > 0x7fffffff ) {
307 return $this->getDB()->timestamp( 1 << 62 );
309 return $this->getDB()->timestamp( 0x7fffffff );
313 protected function garbageCollect() {
314 if ( !$this->purgePeriod
) {
318 // Only purge on one in every $this->purgePeriod requests.
319 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
323 // Avoid repeating the delete within a few seconds
324 if ( $now > ( $this->lastExpireAll +
1 ) ) {
325 $this->lastExpireAll
= $now;
330 public function expireAll() {
331 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
335 * Delete objects from the database which expire before a certain date.
338 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
339 $db = $this->getDB();
340 $dbTimestamp = $db->timestamp( $timestamp );
341 $totalSeconds = false;
342 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
345 for ( $i = 0; $i < $this->shards
; $i++
) {
349 if ( $maxExpTime !== false ) {
350 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
353 $this->getTableByShard( $i ),
354 array( 'keyname', 'exptime' ),
357 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
358 if ( !$rows->numRows() ) {
362 $row = $rows->current();
363 $minExpTime = $row->exptime
;
364 if ( $totalSeconds === false ) {
365 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
366 - wfTimestamp( TS_UNIX
, $minExpTime );
368 foreach ( $rows as $row ) {
369 $keys[] = $row->keyname
;
370 $maxExpTime = $row->exptime
;
373 $db->begin( __METHOD__
);
375 $this->getTableByShard( $i ),
377 'exptime >= ' . $db->addQuotes( $minExpTime ),
378 'exptime < ' . $db->addQuotes( $dbTimestamp ),
382 $db->commit( __METHOD__
);
384 if ( $progressCallback ) {
385 if ( intval( $totalSeconds ) === 0 ) {
388 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
389 - wfTimestamp( TS_UNIX
, $maxExpTime );
390 if ( $remainingSeconds > $totalSeconds ) {
391 $totalSeconds = $remainingSeconds;
393 $percent = ( $i +
$remainingSeconds / $totalSeconds )
394 / $this->shards
* 100;
396 call_user_func( $progressCallback, $percent );
400 } catch ( DBQueryError
$e ) {
401 $this->handleWriteError( $e );
406 public function deleteAll() {
407 $db = $this->getDB();
410 for ( $i = 0; $i < $this->shards
; $i++
) {
411 $db->begin( __METHOD__
);
412 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
413 $db->commit( __METHOD__
);
415 } catch ( DBQueryError
$e ) {
416 $this->handleWriteError( $e );
421 * Serialize an object and, if possible, compress the representation.
422 * On typical message and page data, this can provide a 3X decrease
423 * in storage requirements.
428 protected function serialize( &$data ) {
429 $serial = serialize( $data );
431 if ( function_exists( 'gzdeflate' ) ) {
432 return gzdeflate( $serial );
439 * Unserialize and, if necessary, decompress an object.
440 * @param $serial string
443 protected function unserialize( $serial ) {
444 if ( function_exists( 'gzinflate' ) ) {
445 wfSuppressWarnings();
446 $decomp = gzinflate( $serial );
449 if ( false !== $decomp ) {
454 $ret = unserialize( $serial );
460 * Handle a DBQueryError which occurred during a write operation.
461 * Ignore errors which are due to a read-only database, rethrow others.
463 protected function handleWriteError( $exception ) {
464 $db = $this->getDB();
466 if ( !$db->wasReadOnlyError() ) {
471 $db->rollback( __METHOD__
);
472 } catch ( DBQueryError
$e ) {
475 wfDebug( __METHOD__
. ": ignoring query error\n" );
476 $db->ignoreErrors( false );
480 * Create shard tables. For use from eval.php.
482 public function createTables() {
483 $db = $this->getDB();
484 if ( $db->getType() !== 'mysql'
485 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
487 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
490 for ( $i = 0; $i < $this->shards
; $i++
) {
491 $db->begin( __METHOD__
);
493 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
494 ' LIKE ' . $db->tableName( 'objectcache' ),
496 $db->commit( __METHOD__
);
502 * Backwards compatibility alias
504 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }