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
127 protected function getTableByKey( $key ) {
128 if ( $this->shards
> 1 ) {
129 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
130 return $this->getTableByShard( $hash %
$this->shards
);
132 return $this->tableName
;
137 * Get the table name for a given shard index
140 protected function getTableByShard( $index ) {
141 if ( $this->shards
> 1 ) {
142 $decimals = strlen( $this->shards
- 1 );
143 return $this->tableName
.
144 sprintf( "%0{$decimals}d", $index );
146 return $this->tableName
;
150 public function get( $key ) {
151 $values = $this->getMulti( array( $key ) );
152 return $values[$key];
155 public function getMulti( array $keys ) {
156 $values = array(); // array of (key => value)
158 $keysByTableName = array();
159 foreach ( $keys as $key ) {
160 $tableName = $this->getTableByKey( $key );
161 if ( !isset( $keysByTableName[$tableName] ) ) {
162 $keysByTableName[$tableName] = array();
164 $keysByTableName[$tableName][] = $key;
167 $db = $this->getDB();
168 $this->garbageCollect(); // expire old entries if any
171 foreach ( $keysByTableName as $tableName => $tableKeys ) {
172 $res = $db->select( $tableName,
173 array( 'keyname', 'value', 'exptime' ),
174 array( 'keyname' => $tableKeys ),
176 foreach ( $res as $row ) {
177 $dataRows[$row->keyname
] = $row;
181 foreach ( $keys as $key ) {
182 if ( isset( $dataRows[$key] ) ) { // HIT?
183 $row = $dataRows[$key];
184 $this->debug( "get: retrieved data; expiry time is " . $row->exptime
);
185 if ( $this->isExpired( $row->exptime
) ) { // MISS
186 $this->debug( "get: key has expired, deleting" );
188 $db->begin( __METHOD__
);
189 # Put the expiry time in the WHERE condition to avoid deleting a
190 # newly-inserted value
191 $db->delete( $this->getTableByKey( $key ),
192 array( 'keyname' => $key, 'exptime' => $row->exptime
),
194 $db->commit( __METHOD__
);
195 } catch ( DBQueryError
$e ) {
196 $this->handleWriteError( $e );
198 $values[$key] = false;
200 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value
) );
203 $values[$key] = false;
204 $this->debug( 'get: no matching rows' );
211 public function set( $key, $value, $exptime = 0 ) {
212 $db = $this->getDB();
213 $exptime = intval( $exptime );
215 if ( $exptime < 0 ) {
219 if ( $exptime == 0 ) {
220 $encExpiry = $this->getMaxDateTime();
222 if ( $exptime < 3.16e8
) { # ~10 years
226 $encExpiry = $db->timestamp( $exptime );
229 $db->begin( __METHOD__
);
230 // (bug 24425) use a replace if the db supports it instead of
231 // delete/insert to avoid clashes with conflicting keynames
233 $this->getTableByKey( $key ),
237 'value' => $db->encodeBlob( $this->serialize( $value ) ),
238 'exptime' => $encExpiry
240 $db->commit( __METHOD__
);
241 } catch ( DBQueryError
$e ) {
242 $this->handleWriteError( $e );
250 public function delete( $key, $time = 0 ) {
251 $db = $this->getDB();
254 $db->begin( __METHOD__
);
256 $this->getTableByKey( $key ),
257 array( 'keyname' => $key ),
259 $db->commit( __METHOD__
);
260 } catch ( DBQueryError
$e ) {
261 $this->handleWriteError( $e );
269 public function incr( $key, $step = 1 ) {
270 $db = $this->getDB();
271 $tableName = $this->getTableByKey( $key );
272 $step = intval( $step );
275 $db->begin( __METHOD__
);
276 $row = $db->selectRow(
278 array( 'value', 'exptime' ),
279 array( 'keyname' => $key ),
281 array( 'FOR UPDATE' ) );
282 if ( $row === false ) {
284 $db->commit( __METHOD__
);
288 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__
);
289 if ( $this->isExpired( $row->exptime
) ) {
290 // Expired, do not reinsert
291 $db->commit( __METHOD__
);
296 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value
) ) );
297 $newValue = $oldValue +
$step;
298 $db->insert( $tableName,
301 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
302 'exptime' => $row->exptime
303 ), __METHOD__
, 'IGNORE' );
305 if ( $db->affectedRows() == 0 ) {
306 // Race condition. See bug 28611
309 $db->commit( __METHOD__
);
310 } catch ( DBQueryError
$e ) {
311 $this->handleWriteError( $e );
319 public function keys() {
320 $db = $this->getDB();
323 for ( $i = 0; $i < $this->shards
; $i++
) {
324 $res = $db->select( $this->getTableByShard( $i ),
325 array( 'keyname' ), false, __METHOD__
);
326 foreach ( $res as $row ) {
327 $result[] = $row->keyname
;
334 protected function isExpired( $exptime ) {
335 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX
, $exptime ) < time();
338 protected function getMaxDateTime() {
339 if ( time() > 0x7fffffff ) {
340 return $this->getDB()->timestamp( 1 << 62 );
342 return $this->getDB()->timestamp( 0x7fffffff );
346 protected function garbageCollect() {
347 if ( !$this->purgePeriod
) {
351 // Only purge on one in every $this->purgePeriod requests.
352 if ( $this->purgePeriod
!== 1 && mt_rand( 0, $this->purgePeriod
- 1 ) ) {
356 // Avoid repeating the delete within a few seconds
357 if ( $now > ( $this->lastExpireAll +
1 ) ) {
358 $this->lastExpireAll
= $now;
363 public function expireAll() {
364 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
368 * Delete objects from the database which expire before a certain date.
371 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
372 $db = $this->getDB();
373 $dbTimestamp = $db->timestamp( $timestamp );
374 $totalSeconds = false;
375 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
378 for ( $i = 0; $i < $this->shards
; $i++
) {
382 if ( $maxExpTime !== false ) {
383 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
386 $this->getTableByShard( $i ),
387 array( 'keyname', 'exptime' ),
390 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
391 if ( !$rows->numRows() ) {
395 $row = $rows->current();
396 $minExpTime = $row->exptime
;
397 if ( $totalSeconds === false ) {
398 $totalSeconds = wfTimestamp( TS_UNIX
, $timestamp )
399 - wfTimestamp( TS_UNIX
, $minExpTime );
401 foreach ( $rows as $row ) {
402 $keys[] = $row->keyname
;
403 $maxExpTime = $row->exptime
;
406 $db->begin( __METHOD__
);
408 $this->getTableByShard( $i ),
410 'exptime >= ' . $db->addQuotes( $minExpTime ),
411 'exptime < ' . $db->addQuotes( $dbTimestamp ),
415 $db->commit( __METHOD__
);
417 if ( $progressCallback ) {
418 if ( intval( $totalSeconds ) === 0 ) {
421 $remainingSeconds = wfTimestamp( TS_UNIX
, $timestamp )
422 - wfTimestamp( TS_UNIX
, $maxExpTime );
423 if ( $remainingSeconds > $totalSeconds ) {
424 $totalSeconds = $remainingSeconds;
426 $percent = ( $i +
$remainingSeconds / $totalSeconds )
427 / $this->shards
* 100;
429 call_user_func( $progressCallback, $percent );
433 } catch ( DBQueryError
$e ) {
434 $this->handleWriteError( $e );
439 public function deleteAll() {
440 $db = $this->getDB();
443 for ( $i = 0; $i < $this->shards
; $i++
) {
444 $db->begin( __METHOD__
);
445 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__
);
446 $db->commit( __METHOD__
);
448 } catch ( DBQueryError
$e ) {
449 $this->handleWriteError( $e );
454 * Serialize an object and, if possible, compress the representation.
455 * On typical message and page data, this can provide a 3X decrease
456 * in storage requirements.
461 protected function serialize( &$data ) {
462 $serial = serialize( $data );
464 if ( function_exists( 'gzdeflate' ) ) {
465 return gzdeflate( $serial );
472 * Unserialize and, if necessary, decompress an object.
473 * @param $serial string
476 protected function unserialize( $serial ) {
477 if ( function_exists( 'gzinflate' ) ) {
478 wfSuppressWarnings();
479 $decomp = gzinflate( $serial );
482 if ( false !== $decomp ) {
487 $ret = unserialize( $serial );
493 * Handle a DBQueryError which occurred during a write operation.
494 * Ignore errors which are due to a read-only database, rethrow others.
496 protected function handleWriteError( $exception ) {
497 $db = $this->getDB();
499 if ( !$db->wasReadOnlyError() ) {
504 $db->rollback( __METHOD__
);
505 } catch ( DBQueryError
$e ) {
508 wfDebug( __METHOD__
. ": ignoring query error\n" );
509 $db->ignoreErrors( false );
513 * Create shard tables. For use from eval.php.
515 public function createTables() {
516 $db = $this->getDB();
517 if ( $db->getType() !== 'mysql'
518 ||
version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
520 throw new MWException( __METHOD__
. ' is not supported on this DB server' );
523 for ( $i = 0; $i < $this->shards
; $i++
) {
524 $db->begin( __METHOD__
);
526 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
527 ' LIKE ' . $db->tableName( 'objectcache' ),
529 $db->commit( __METHOD__
);
535 * Backwards compatibility alias
537 class MediaWikiBagOStuff
extends SqlBagOStuff
{ }