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
{
40 var $lastExpireAll = 0;
41 var $purgePeriod = 100;
43 var $tableName = 'objectcache';
45 protected $connFailureTime = 0; // UNIX timestamp
46 protected $connFailureError; // exception
49 * Constructor. Parameters are:
50 * - server: A server info structure in the format required by each
51 * element in $wgDBServers.
53 * - purgePeriod: The average number of object cache requests in between
54 * garbage collection operations, where expired entries
55 * are removed from the database. Or in other words, the
56 * reciprocal of the probability of purging on any given
57 * request. If this is set to zero, purging will never be
60 * - tableName: The table name to use, default is "objectcache".
62 * - shards: The number of tables to use for data storage. If this is
63 * more than 1, table names will be formed in the style
64 * objectcacheNNN where NNN is the shard index, between 0 and
65 * shards-1. The number of digits will be the minimum number
66 * required to hold the largest shard index. Data will be
67 * distributed across all tables by key hash. This is for
68 * MySQL bugs 61735 and 61736.
70 * @param $params array
72 public function __construct( $params ) {
73 if ( isset( $params['server'] ) ) {
74 $this->serverInfo
= $params['server'];
75 $this->serverInfo
['load'] = 1;
77 if ( isset( $params['purgePeriod'] ) ) {
78 $this->purgePeriod
= intval( $params['purgePeriod'] );
80 if ( isset( $params['tableName'] ) ) {
81 $this->tableName
= $params['tableName'];
83 if ( isset( $params['shards'] ) ) {
84 $this->shards
= intval( $params['shards'] );
90 * @return DatabaseBase
92 protected function getDB() {
93 global $wgDebugDBTransactions;
95 # Don't keep timing out trying to connect for each call if the DB is down
96 if ( $this->connFailureError
&& ( time() - $this->connFailureTime
) < 60 ) {
97 throw $this->connFailureError
;
100 if ( !isset( $this->db
) ) {
101 # If server connection info was given, use that
102 if ( $this->serverInfo
) {
103 if ( $wgDebugDBTransactions ) {
104 wfDebug( sprintf( "Using provided serverInfo for SqlBagOStuff\n" ) );
106 $this->lb
= new LoadBalancer( array(
107 'servers' => array( $this->serverInfo
) ) );
108 $this->db
= $this->lb
->getConnection( DB_MASTER
);
109 $this->db
->clearFlag( DBO_TRX
);
112 * We must keep a separate connection to MySQL in order to avoid deadlocks
113 * However, SQLite has an opposite behaviour. And PostgreSQL needs to know
114 * if we are in transaction or no
116 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
117 $this->lb
= wfGetLBFactory()->newMainLB();
118 $this->db
= $this->lb
->getConnection( DB_MASTER
);
119 $this->db
->clearFlag( DBO_TRX
); // auto-commit mode
121 $this->db
= wfGetDB( DB_MASTER
);
124 if ( $wgDebugDBTransactions ) {
125 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $this->db
) );
133 * Get the table name for a given key
137 protected function getTableByKey( $key ) {
138 if ( $this->shards
> 1 ) {
139 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
140 return $this->getTableByShard( $hash %
$this->shards
);
142 return $this->tableName
;
147 * Get the table name for a given shard index
151 protected function getTableByShard( $index ) {
152 if ( $this->shards
> 1 ) {
153 $decimals = strlen( $this->shards
- 1 );
154 return $this->tableName
.
155 sprintf( "%0{$decimals}d", $index );
157 return $this->tableName
;
165 public function get( $key ) {
166 $values = $this->getMulti( array( $key ) );
167 return array_key_exists( $key, $values ) ?
$values[$key] : false;
174 public function getMulti( array $keys ) {
175 $values = array(); // array of (key => value)
178 $db = $this->getDB();
179 $keysByTableName = array();
180 foreach ( $keys as $key ) {
181 $tableName = $this->getTableByKey( $key );
182 if ( !isset( $keysByTableName[$tableName] ) ) {
183 $keysByTableName[$tableName] = array();
185 $keysByTableName[$tableName][] = $key;
188 $this->garbageCollect(); // expire old entries if any
191 foreach ( $keysByTableName as $tableName => $tableKeys ) {
192 $res = $db->select( $tableName,
193 array( 'keyname', 'value', 'exptime' ),
194 array( 'keyname' => $tableKeys ),
196 foreach ( $res as $row ) {
197 $dataRows[$row->keyname
] = $row;
201 foreach ( $keys as $key ) {
202 if ( isset( $dataRows[$key] ) ) { // HIT?
203 $row = $dataRows[$key];
204 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
205 if ( $this->isExpired( $row->exptime
) ) { // MISS
206 $this->debug( "get: key has expired, deleting" );
208 $db->begin( __METHOD__
);
209 # Put the expiry time in the WHERE condition to avoid deleting a
210 # newly-inserted value
211 $db->delete( $this->getTableByKey( $key ),
212 array( 'keyname' => $key, 'exptime' => $row->exptime
),
214 $db->commit( __METHOD__
);
215 } catch ( DBQueryError
$e ) {
216 $this->handleWriteError( $e );
218 $values[$key] = false;
220 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
223 $values[$key] = false;
224 $this->debug( 'get: no matching rows' );
227 } catch ( DBError
$e ) {
228 $this->handleReadError( $e );
236 * @param $value mixed
237 * @param $exptime int
240 public function set( $key, $value, $exptime = 0 ) {
242 $db = $this->getDB();
243 $exptime = intval( $exptime );
245 if ( $exptime < 0 ) {
249 if ( $exptime == 0 ) {
250 $encExpiry = $this->getMaxDateTime();
252 if ( $exptime < 3.16e8
) { # ~10 years
256 $encExpiry = $db->timestamp( $exptime );
258 $db->begin( __METHOD__
);
259 // (bug 24425) use a replace if the db supports it instead of
260 // delete/insert to avoid clashes with conflicting keynames
262 $this->getTableByKey( $key ),
266 'value' => $db->encodeBlob( $this->serialize( $value ) ),
267 'exptime' => $encExpiry
269 $db->commit( __METHOD__
);
270 } catch ( DBError
$e ) {
271 $this->handleWriteError( $e );
283 public function delete( $key, $time = 0 ) {
285 $db = $this->getDB();
286 $db->begin( __METHOD__
);
288 $this->getTableByKey( $key ),
289 array( 'keyname' => $key ),
291 $db->commit( __METHOD__
);
292 } catch ( DBError
$e ) {
293 $this->handleWriteError( $e );
305 public function incr( $key, $step = 1 ) {
307 $db = $this->getDB();
308 $tableName = $this->getTableByKey( $key );
309 $step = intval( $step );
310 $db->begin( __METHOD__
);
311 $row = $db->selectRow(
313 array( 'value', 'exptime' ),
314 array( 'keyname' => $key ),
316 array( 'FOR UPDATE' ) );
317 if ( $row === false ) {
319 $db->commit( __METHOD__
);
323 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
324 if ( $this->isExpired( $row->exptime
) ) {
325 // Expired, do not reinsert
326 $db->commit( __METHOD__
);
331 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
332 $newValue = $oldValue +
$step;
333 $db->insert( $tableName,
336 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
337 'exptime' => $row->exptime
338 ), __METHOD__
, 'IGNORE' );
340 if ( $db->affectedRows() == 0 ) {
341 // Race condition. See bug 28611
344 $db->commit( __METHOD__
);
345 } catch ( DBError
$e ) {
346 $this->handleWriteError( $e );
356 public function keys() {
360 $db = $this->getDB();
361 for ( $i = 0; $i < $this->shards
; $i++
) {
362 $res = $db->select( $this->getTableByShard( $i ),
363 array( 'keyname' ), false, __METHOD__
);
364 foreach ( $res as $row ) {
365 $result[] = $row->keyname
;
368 } catch ( DBError
$e ) {
369 $this->handleReadError( $e );
376 * @param $exptime string
379 protected function isExpired( $exptime ) {
380 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
386 protected function getMaxDateTime() {
387 if ( time() > 0x7fffffff ) {
388 return $this->getDB()->timestamp( 1 << 62 );
390 return $this->getDB()->timestamp( 0x7fffffff );
394 protected function garbageCollect() {
395 if ( !$this->purgePeriod
) {
399 // Only purge on one in every $this->purgePeriod requests.
400 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
404 // Avoid repeating the delete within a few seconds
405 if ( $now > ( $this->lastExpireAll +
1 ) ) {
406 $this->lastExpireAll
= $now;
411 public function expireAll() {
412 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
416 * Delete objects from the database which expire before a certain date.
417 * @param $timestamp string
418 * @param $progressCallback bool|callback
421 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
423 $db = $this->getDB();
424 $dbTimestamp = $db->timestamp( $timestamp );
425 $totalSeconds = false;
426 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
427 for ( $i = 0; $i < $this->shards
; $i++
) {
431 if ( $maxExpTime !== false ) {
432 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
435 $this->getTableByShard( $i ),
436 array( 'keyname', 'exptime' ),
439 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
440 if ( !$rows->numRows() ) {
444 $row = $rows->current();
445 $minExpTime = $row->exptime
;
446 if ( $totalSeconds === false ) {
447 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
448 - wfTimestamp( TS_UNIX
, $minExpTime );
450 foreach ( $rows as $row ) {
451 $keys[] = $row->keyname
;
452 $maxExpTime = $row->exptime
;
455 $db->begin( __METHOD__
);
457 $this->getTableByShard( $i ),
459 'exptime >= ' . $db->addQuotes( $minExpTime ),
460 'exptime < ' . $db->addQuotes( $dbTimestamp ),
464 $db->commit( __METHOD__
);
466 if ( $progressCallback ) {
467 if ( intval( $totalSeconds ) === 0 ) {
470 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
471 - wfTimestamp( TS_UNIX
, $maxExpTime );
472 if ( $remainingSeconds > $totalSeconds ) {
473 $totalSeconds = $remainingSeconds;
475 $percent = ( $i +
$remainingSeconds / $totalSeconds )
476 / $this->shards
* 100;
478 call_user_func( $progressCallback, $percent );
482 } catch ( DBError
$e ) {
483 $this->handleWriteError( $e );
490 public function deleteAll() {
492 $db = $this->getDB();
493 for ( $i = 0; $i < $this->shards
; $i++
) {
494 $db->begin( __METHOD__
);
495 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
496 $db->commit( __METHOD__
);
498 } catch ( DBError
$e ) {
499 $this->handleWriteError( $e );
507 * Serialize an object and, if possible, compress the representation.
508 * On typical message and page data, this can provide a 3X decrease
509 * in storage requirements.
514 protected function serialize( &$data ) {
515 $serial = serialize( $data );
517 if ( function_exists( 'gzdeflate' ) ) {
518 return gzdeflate( $serial );
525 * Unserialize and, if necessary, decompress an object.
526 * @param $serial string
529 protected function unserialize( $serial ) {
530 if ( function_exists( 'gzinflate' ) ) {
531 wfSuppressWarnings();
532 $decomp = gzinflate( $serial );
535 if ( false !== $decomp ) {
540 $ret = unserialize( $serial );
546 * Handle a DBError which occurred during a read operation.
548 protected function handleReadError( DBError
$exception ) {
549 if ( $exception instanceof DBConnectionError
) {
550 $this->connFailureTime
= time();
551 $this->connFailureError
= $exception;
553 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
555 wfDebug( __METHOD__
. ": ignoring query error\n" );
557 wfDebug( __METHOD__
. ": ignoring connection error\n" );
562 * Handle a DBQueryError which occurred during a write operation.
564 protected function handleWriteError( DBError
$exception ) {
565 if ( $exception instanceof DBConnectionError
) {
566 $this->connFailureTime
= time();
567 $this->connFailureError
= $exception;
569 if ( $this->db
&& $this->db
->wasReadOnlyError() ) {
571 $this->db
->rollback( __METHOD__
);
572 } catch ( DBError
$e ) {}
574 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
576 wfDebug( __METHOD__
. ": ignoring query error\n" );
578 wfDebug( __METHOD__
. ": ignoring connection error\n" );
583 * Create shard tables. For use from eval.php.
585 public function createTables() {
586 $db = $this->getDB();
587 if ( $db->getType() !== 'mysql'
588 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
590 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
593 for ( $i = 0; $i < $this->shards
; $i++
) {
594 $db->begin( __METHOD__
);
596 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
597 ' LIKE ' . $db->tableName( 'objectcache' ),
599 $db->commit( __METHOD__
);
605 * Backwards compatibility alias
607 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }