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 global $wgDebugDBTransactions;
91 if ( !isset( $this->db
) ) {
92 # If server connection info was given, use that
93 if ( $this->serverInfo
) {
94 if ( $wgDebugDBTransactions ) {
95 wfDebug( sprintf( "Using provided serverInfo for SqlBagOStuff\n" ) );
97 $this->lb
= new LoadBalancer( array(
98 'servers' => array( $this->serverInfo
) ) );
99 $this->db
= $this->lb
->getConnection( DB_MASTER
);
100 $this->db
->clearFlag( DBO_TRX
);
103 * We must keep a separate connection to MySQL in order to avoid deadlocks
104 * However, SQLite has an opposite behaviour. And PostgreSQL needs to know
105 * if we are in transaction or no
107 if ( wfGetDB( DB_MASTER
)->getType() == 'mysql' ) {
108 $this->lb
= wfGetLBFactory()->newMainLB();
109 $this->db
= $this->lb
->getConnection( DB_MASTER
);
110 $this->db
->clearFlag( DBO_TRX
);
112 $this->db
= wfGetDB( DB_MASTER
);
115 if ( $wgDebugDBTransactions ) {
116 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $this->db
) );
124 * Get the table name for a given key
128 protected function getTableByKey( $key ) {
129 if ( $this->shards
> 1 ) {
130 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
131 return $this->getTableByShard( $hash %
$this->shards
);
133 return $this->tableName
;
138 * Get the table name for a given shard index
142 protected function getTableByShard( $index ) {
143 if ( $this->shards
> 1 ) {
144 $decimals = strlen( $this->shards
- 1 );
145 return $this->tableName
.
146 sprintf( "%0{$decimals}d", $index );
148 return $this->tableName
;
156 public function get( $key ) {
157 $values = $this->getMulti( array( $key ) );
158 return $values[$key];
165 public function getMulti( array $keys ) {
166 $values = array(); // array of (key => value)
168 $keysByTableName = array();
169 foreach ( $keys as $key ) {
170 $tableName = $this->getTableByKey( $key );
171 if ( !isset( $keysByTableName[$tableName] ) ) {
172 $keysByTableName[$tableName] = array();
174 $keysByTableName[$tableName][] = $key;
177 $db = $this->getDB();
178 $this->garbageCollect(); // expire old entries if any
181 foreach ( $keysByTableName as $tableName => $tableKeys ) {
182 $res = $db->select( $tableName,
183 array( 'keyname', 'value', 'exptime' ),
184 array( 'keyname' => $tableKeys ),
186 foreach ( $res as $row ) {
187 $dataRows[$row->keyname
] = $row;
191 foreach ( $keys as $key ) {
192 if ( isset( $dataRows[$key] ) ) { // HIT?
193 $row = $dataRows[$key];
194 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
195 if ( $this->isExpired( $row->exptime
) ) { // MISS
196 $this->debug( "get: key has expired, deleting" );
198 $db->begin( __METHOD__
);
199 # Put the expiry time in the WHERE condition to avoid deleting a
200 # newly-inserted value
201 $db->delete( $this->getTableByKey( $key ),
202 array( 'keyname' => $key, 'exptime' => $row->exptime
),
204 $db->commit( __METHOD__
);
205 } catch ( DBQueryError
$e ) {
206 $this->handleWriteError( $e );
208 $values[$key] = false;
210 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
213 $values[$key] = false;
214 $this->debug( 'get: no matching rows' );
223 * @param $value mixed
224 * @param $exptime int
227 public function set( $key, $value, $exptime = 0 ) {
228 $db = $this->getDB();
229 $exptime = intval( $exptime );
231 if ( $exptime < 0 ) {
235 if ( $exptime == 0 ) {
236 $encExpiry = $this->getMaxDateTime();
238 if ( $exptime < 3.16e8
) { # ~10 years
242 $encExpiry = $db->timestamp( $exptime );
245 $db->begin( __METHOD__
);
246 // (bug 24425) use a replace if the db supports it instead of
247 // delete/insert to avoid clashes with conflicting keynames
249 $this->getTableByKey( $key ),
253 'value' => $db->encodeBlob( $this->serialize( $value ) ),
254 'exptime' => $encExpiry
256 $db->commit( __METHOD__
);
257 } catch ( DBQueryError
$e ) {
258 $this->handleWriteError( $e );
271 public function delete( $key, $time = 0 ) {
272 $db = $this->getDB();
275 $db->begin( __METHOD__
);
277 $this->getTableByKey( $key ),
278 array( 'keyname' => $key ),
280 $db->commit( __METHOD__
);
281 } catch ( DBQueryError
$e ) {
282 $this->handleWriteError( $e );
295 public function incr( $key, $step = 1 ) {
296 $db = $this->getDB();
297 $tableName = $this->getTableByKey( $key );
298 $step = intval( $step );
301 $db->begin( __METHOD__
);
302 $row = $db->selectRow(
304 array( 'value', 'exptime' ),
305 array( 'keyname' => $key ),
307 array( 'FOR UPDATE' ) );
308 if ( $row === false ) {
310 $db->commit( __METHOD__
);
314 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
315 if ( $this->isExpired( $row->exptime
) ) {
316 // Expired, do not reinsert
317 $db->commit( __METHOD__
);
322 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
323 $newValue = $oldValue +
$step;
324 $db->insert( $tableName,
327 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
328 'exptime' => $row->exptime
329 ), __METHOD__
, 'IGNORE' );
331 if ( $db->affectedRows() == 0 ) {
332 // Race condition. See bug 28611
335 $db->commit( __METHOD__
);
336 } catch ( DBQueryError
$e ) {
337 $this->handleWriteError( $e );
348 public function keys() {
349 $db = $this->getDB();
352 for ( $i = 0; $i < $this->shards
; $i++
) {
353 $res = $db->select( $this->getTableByShard( $i ),
354 array( 'keyname' ), false, __METHOD__
);
355 foreach ( $res as $row ) {
356 $result[] = $row->keyname
;
364 * @param $exptime string
367 protected function isExpired( $exptime ) {
368 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
374 protected function getMaxDateTime() {
375 if ( time() > 0x7fffffff ) {
376 return $this->getDB()->timestamp( 1 << 62 );
378 return $this->getDB()->timestamp( 0x7fffffff );
382 protected function garbageCollect() {
383 if ( !$this->purgePeriod
) {
387 // Only purge on one in every $this->purgePeriod requests.
388 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
392 // Avoid repeating the delete within a few seconds
393 if ( $now > ( $this->lastExpireAll +
1 ) ) {
394 $this->lastExpireAll
= $now;
399 public function expireAll() {
400 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
404 * Delete objects from the database which expire before a certain date.
405 * @param $timestamp string
406 * @param $progressCallback bool|callback
409 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
410 $db = $this->getDB();
411 $dbTimestamp = $db->timestamp( $timestamp );
412 $totalSeconds = false;
413 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
416 for ( $i = 0; $i < $this->shards
; $i++
) {
420 if ( $maxExpTime !== false ) {
421 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
424 $this->getTableByShard( $i ),
425 array( 'keyname', 'exptime' ),
428 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
429 if ( !$rows->numRows() ) {
433 $row = $rows->current();
434 $minExpTime = $row->exptime
;
435 if ( $totalSeconds === false ) {
436 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
437 - wfTimestamp( TS_UNIX
, $minExpTime );
439 foreach ( $rows as $row ) {
440 $keys[] = $row->keyname
;
441 $maxExpTime = $row->exptime
;
444 $db->begin( __METHOD__
);
446 $this->getTableByShard( $i ),
448 'exptime >= ' . $db->addQuotes( $minExpTime ),
449 'exptime < ' . $db->addQuotes( $dbTimestamp ),
453 $db->commit( __METHOD__
);
455 if ( $progressCallback ) {
456 if ( intval( $totalSeconds ) === 0 ) {
459 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
460 - wfTimestamp( TS_UNIX
, $maxExpTime );
461 if ( $remainingSeconds > $totalSeconds ) {
462 $totalSeconds = $remainingSeconds;
464 $percent = ( $i +
$remainingSeconds / $totalSeconds )
465 / $this->shards
* 100;
467 call_user_func( $progressCallback, $percent );
471 } catch ( DBQueryError
$e ) {
472 $this->handleWriteError( $e );
477 public function deleteAll() {
478 $db = $this->getDB();
481 for ( $i = 0; $i < $this->shards
; $i++
) {
482 $db->begin( __METHOD__
);
483 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
484 $db->commit( __METHOD__
);
486 } catch ( DBQueryError
$e ) {
487 $this->handleWriteError( $e );
492 * Serialize an object and, if possible, compress the representation.
493 * On typical message and page data, this can provide a 3X decrease
494 * in storage requirements.
499 protected function serialize( &$data ) {
500 $serial = serialize( $data );
502 if ( function_exists( 'gzdeflate' ) ) {
503 return gzdeflate( $serial );
510 * Unserialize and, if necessary, decompress an object.
511 * @param $serial string
514 protected function unserialize( $serial ) {
515 if ( function_exists( 'gzinflate' ) ) {
516 wfSuppressWarnings();
517 $decomp = gzinflate( $serial );
520 if ( false !== $decomp ) {
525 $ret = unserialize( $serial );
531 * Handle a DBQueryError which occurred during a write operation.
532 * Ignore errors which are due to a read-only database, rethrow others.
534 protected function handleWriteError( $exception ) {
535 $db = $this->getDB();
537 if ( !$db->wasReadOnlyError() ) {
542 $db->rollback( __METHOD__
);
543 } catch ( DBQueryError
$e ) {
546 wfDebug( __METHOD__
. ": ignoring query error\n" );
547 $db->ignoreErrors( false );
551 * Create shard tables. For use from eval.php.
553 public function createTables() {
554 $db = $this->getDB();
555 if ( $db->getType() !== 'mysql'
556 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
558 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
561 for ( $i = 0; $i < $this->shards
; $i++
) {
562 $db->begin( __METHOD__
);
564 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
565 ' LIKE ' . $db->tableName( 'objectcache' ),
567 $db->commit( __METHOD__
);
573 * Backwards compatibility alias
575 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }