MediaWiki REL1_28
SqlBagOStuff.php
Go to the documentation of this file.
1<?php
24use \MediaWiki\MediaWikiServices;
25use \Wikimedia\WaitConditionLoop;
26
32class SqlBagOStuff extends BagOStuff {
34 protected $serverInfos;
36 protected $serverTags;
38 protected $numServers;
40 protected $lastExpireAll = 0;
42 protected $purgePeriod = 100;
44 protected $shards = 1;
46 protected $tableName = 'objectcache';
48 protected $replicaOnly = false;
50 protected $syncTimeout = 3;
51
53 protected $separateMainLB;
55 protected $conns;
57 protected $connFailureTimes = [];
59 protected $connFailureErrors = [];
60
97 public function __construct( $params ) {
98 parent::__construct( $params );
99
102
103 if ( isset( $params['servers'] ) ) {
104 $this->serverInfos = [];
105 $this->serverTags = [];
106 $this->numServers = count( $params['servers'] );
107 $index = 0;
108 foreach ( $params['servers'] as $tag => $info ) {
109 $this->serverInfos[$index] = $info;
110 if ( is_string( $tag ) ) {
111 $this->serverTags[$index] = $tag;
112 } else {
113 $this->serverTags[$index] = isset( $info['host'] ) ? $info['host'] : "#$index";
114 }
115 ++$index;
116 }
117 } elseif ( isset( $params['server'] ) ) {
118 $this->serverInfos = [ $params['server'] ];
119 $this->numServers = count( $this->serverInfos );
120 } else {
121 // Default to using the main wiki's database servers
122 $this->serverInfos = false;
123 $this->numServers = 1;
125 }
126 if ( isset( $params['purgePeriod'] ) ) {
127 $this->purgePeriod = intval( $params['purgePeriod'] );
128 }
129 if ( isset( $params['tableName'] ) ) {
130 $this->tableName = $params['tableName'];
131 }
132 if ( isset( $params['shards'] ) ) {
133 $this->shards = intval( $params['shards'] );
134 }
135 if ( isset( $params['syncTimeout'] ) ) {
136 $this->syncTimeout = $params['syncTimeout'];
137 }
138 $this->replicaOnly = !empty( $params['slaveOnly'] );
139 }
140
141 protected function getSeparateMainLB() {
143
144 if ( $wgDBtype === 'mysql' && $this->usesMainDB() ) {
145 if ( !$this->separateMainLB ) {
146 // We must keep a separate connection to MySQL in order to avoid deadlocks
147 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
148 $this->separateMainLB = $lbFactory->newMainLB();
149 }
151 } else {
152 // However, SQLite has an opposite behavior. And PostgreSQL needs to know
153 // if we are in transaction or not (@TODO: find some PostgreSQL work-around).
154 return null;
155 }
156 }
157
165 protected function getDB( $serverIndex ) {
166 if ( !isset( $this->conns[$serverIndex] ) ) {
167 if ( $serverIndex >= $this->numServers ) {
168 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
169 }
170
171 # Don't keep timing out trying to connect for each call if the DB is down
172 if ( isset( $this->connFailureErrors[$serverIndex] )
173 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
174 ) {
175 throw $this->connFailureErrors[$serverIndex];
176 }
177
178 # If server connection info was given, use that
179 if ( $this->serverInfos ) {
180 $info = $this->serverInfos[$serverIndex];
181 $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
182 $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
183 $this->logger->debug( __CLASS__ . ": connecting to $host" );
184 // Use a blank trx profiler to ignore expections as this is a cache
185 $info['trxProfiler'] = new TransactionProfiler();
186 $db = Database::factory( $type, $info );
187 $db->clearFlag( DBO_TRX );
188 } else {
189 $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
190 if ( $this->getSeparateMainLB() ) {
191 $db = $this->getSeparateMainLB()->getConnection( $index );
192 $db->clearFlag( DBO_TRX ); // auto-commit mode
193 } else {
194 $db = wfGetDB( $index );
195 // Can't mess with transaction rounds (DBO_TRX) :(
196 }
197 }
198 $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
199 $this->conns[$serverIndex] = $db;
200 }
201
202 return $this->conns[$serverIndex];
203 }
204
210 protected function getTableByKey( $key ) {
211 if ( $this->shards > 1 ) {
212 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
213 $tableIndex = $hash % $this->shards;
214 } else {
215 $tableIndex = 0;
216 }
217 if ( $this->numServers > 1 ) {
218 $sortedServers = $this->serverTags;
219 ArrayUtils::consistentHashSort( $sortedServers, $key );
220 reset( $sortedServers );
221 $serverIndex = key( $sortedServers );
222 } else {
223 $serverIndex = 0;
224 }
225 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
226 }
227
233 protected function getTableNameByShard( $index ) {
234 if ( $this->shards > 1 ) {
235 $decimals = strlen( $this->shards - 1 );
236 return $this->tableName .
237 sprintf( "%0{$decimals}d", $index );
238 } else {
239 return $this->tableName;
240 }
241 }
242
243 protected function doGet( $key, $flags = 0 ) {
244 $casToken = null;
245
246 return $this->getWithToken( $key, $casToken, $flags );
247 }
248
249 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
250 $values = $this->getMulti( [ $key ] );
251 if ( array_key_exists( $key, $values ) ) {
252 $casToken = $values[$key];
253 return $values[$key];
254 }
255 return false;
256 }
257
258 public function getMulti( array $keys, $flags = 0 ) {
259 $values = []; // array of (key => value)
260
261 $keysByTable = [];
262 foreach ( $keys as $key ) {
263 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
264 $keysByTable[$serverIndex][$tableName][] = $key;
265 }
266
267 $this->garbageCollect(); // expire old entries if any
268
269 $dataRows = [];
270 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
271 try {
272 $db = $this->getDB( $serverIndex );
273 foreach ( $serverKeys as $tableName => $tableKeys ) {
274 $res = $db->select( $tableName,
275 [ 'keyname', 'value', 'exptime' ],
276 [ 'keyname' => $tableKeys ],
277 __METHOD__,
278 // Approximate write-on-the-fly BagOStuff API via blocking.
279 // This approximation fails if a ROLLBACK happens (which is rare).
280 // We do not want to flush the TRX as that can break callers.
281 $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
282 );
283 if ( $res === false ) {
284 continue;
285 }
286 foreach ( $res as $row ) {
287 $row->serverIndex = $serverIndex;
288 $row->tableName = $tableName;
289 $dataRows[$row->keyname] = $row;
290 }
291 }
292 } catch ( DBError $e ) {
293 $this->handleReadError( $e, $serverIndex );
294 }
295 }
296
297 foreach ( $keys as $key ) {
298 if ( isset( $dataRows[$key] ) ) { // HIT?
299 $row = $dataRows[$key];
300 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
301 $db = null;
302 try {
303 $db = $this->getDB( $row->serverIndex );
304 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
305 $this->debug( "get: key has expired" );
306 } else { // HIT
307 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
308 }
309 } catch ( DBQueryError $e ) {
310 $this->handleWriteError( $e, $db, $row->serverIndex );
311 }
312 } else { // MISS
313 $this->debug( 'get: no matching rows' );
314 }
315 }
316
317 return $values;
318 }
319
320 public function setMulti( array $data, $expiry = 0 ) {
321 $keysByTable = [];
322 foreach ( $data as $key => $value ) {
323 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
324 $keysByTable[$serverIndex][$tableName][] = $key;
325 }
326
327 $this->garbageCollect(); // expire old entries if any
328
329 $result = true;
330 $exptime = (int)$expiry;
331 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
332 $db = null;
333 try {
334 $db = $this->getDB( $serverIndex );
335 } catch ( DBError $e ) {
336 $this->handleWriteError( $e, $db, $serverIndex );
337 $result = false;
338 continue;
339 }
340
341 if ( $exptime < 0 ) {
342 $exptime = 0;
343 }
344
345 if ( $exptime == 0 ) {
346 $encExpiry = $this->getMaxDateTime( $db );
347 } else {
348 $exptime = $this->convertExpiry( $exptime );
349 $encExpiry = $db->timestamp( $exptime );
350 }
351 foreach ( $serverKeys as $tableName => $tableKeys ) {
352 $rows = [];
353 foreach ( $tableKeys as $key ) {
354 $rows[] = [
355 'keyname' => $key,
356 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
357 'exptime' => $encExpiry,
358 ];
359 }
360
361 try {
362 $db->replace(
364 [ 'keyname' ],
365 $rows,
366 __METHOD__
367 );
368 } catch ( DBError $e ) {
369 $this->handleWriteError( $e, $db, $serverIndex );
370 $result = false;
371 }
372
373 }
374
375 }
376
377 return $result;
378 }
379
380 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
381 $ok = $this->setMulti( [ $key => $value ], $exptime );
382 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
383 $ok = $this->waitForReplication() && $ok;
384 }
385
386 return $ok;
387 }
388
389 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
390 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
391 $db = null;
392 try {
393 $db = $this->getDB( $serverIndex );
394 $exptime = intval( $exptime );
395
396 if ( $exptime < 0 ) {
397 $exptime = 0;
398 }
399
400 if ( $exptime == 0 ) {
401 $encExpiry = $this->getMaxDateTime( $db );
402 } else {
403 $exptime = $this->convertExpiry( $exptime );
404 $encExpiry = $db->timestamp( $exptime );
405 }
406 // (bug 24425) use a replace if the db supports it instead of
407 // delete/insert to avoid clashes with conflicting keynames
408 $db->update(
410 [
411 'keyname' => $key,
412 'value' => $db->encodeBlob( $this->serialize( $value ) ),
413 'exptime' => $encExpiry
414 ],
415 [
416 'keyname' => $key,
417 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
418 ],
419 __METHOD__
420 );
421 } catch ( DBQueryError $e ) {
422 $this->handleWriteError( $e, $db, $serverIndex );
423
424 return false;
425 }
426
427 return (bool)$db->affectedRows();
428 }
429
430 public function delete( $key ) {
431 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
432 $db = null;
433 try {
434 $db = $this->getDB( $serverIndex );
435 $db->delete(
437 [ 'keyname' => $key ],
438 __METHOD__ );
439 } catch ( DBError $e ) {
440 $this->handleWriteError( $e, $db, $serverIndex );
441 return false;
442 }
443
444 return true;
445 }
446
447 public function incr( $key, $step = 1 ) {
448 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
449 $db = null;
450 try {
451 $db = $this->getDB( $serverIndex );
452 $step = intval( $step );
453 $row = $db->selectRow(
455 [ 'value', 'exptime' ],
456 [ 'keyname' => $key ],
457 __METHOD__,
458 [ 'FOR UPDATE' ] );
459 if ( $row === false ) {
460 // Missing
461
462 return null;
463 }
464 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
465 if ( $this->isExpired( $db, $row->exptime ) ) {
466 // Expired, do not reinsert
467
468 return null;
469 }
470
471 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
472 $newValue = $oldValue + $step;
473 $db->insert( $tableName,
474 [
475 'keyname' => $key,
476 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
477 'exptime' => $row->exptime
478 ], __METHOD__, 'IGNORE' );
479
480 if ( $db->affectedRows() == 0 ) {
481 // Race condition. See bug 28611
482 $newValue = null;
483 }
484 } catch ( DBError $e ) {
485 $this->handleWriteError( $e, $db, $serverIndex );
486 return null;
487 }
488
489 return $newValue;
490 }
491
492 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
493 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts );
494 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
495 $ok = $this->waitForReplication() && $ok;
496 }
497
498 return $ok;
499 }
500
501 public function changeTTL( $key, $expiry = 0 ) {
502 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
503 $db = null;
504 try {
505 $db = $this->getDB( $serverIndex );
506 $db->update(
508 [ 'exptime' => $db->timestamp( $this->convertExpiry( $expiry ) ) ],
509 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
510 __METHOD__
511 );
512 if ( $db->affectedRows() == 0 ) {
513 return false;
514 }
515 } catch ( DBError $e ) {
516 $this->handleWriteError( $e, $db, $serverIndex );
517 return false;
518 }
519
520 return true;
521 }
522
528 protected function isExpired( $db, $exptime ) {
529 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
530 }
531
536 protected function getMaxDateTime( $db ) {
537 if ( time() > 0x7fffffff ) {
538 return $db->timestamp( 1 << 62 );
539 } else {
540 return $db->timestamp( 0x7fffffff );
541 }
542 }
543
544 protected function garbageCollect() {
545 if ( !$this->purgePeriod || $this->replicaOnly ) {
546 // Disabled
547 return;
548 }
549 // Only purge on one in every $this->purgePeriod requests.
550 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
551 return;
552 }
553 $now = time();
554 // Avoid repeating the delete within a few seconds
555 if ( $now > ( $this->lastExpireAll + 1 ) ) {
556 $this->lastExpireAll = $now;
557 $this->expireAll();
558 }
559 }
560
561 public function expireAll() {
563 }
564
571 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
572 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
573 $db = null;
574 try {
575 $db = $this->getDB( $serverIndex );
576 $dbTimestamp = $db->timestamp( $timestamp );
577 $totalSeconds = false;
578 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
579 for ( $i = 0; $i < $this->shards; $i++ ) {
580 $maxExpTime = false;
581 while ( true ) {
582 $conds = $baseConds;
583 if ( $maxExpTime !== false ) {
584 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
585 }
586 $rows = $db->select(
587 $this->getTableNameByShard( $i ),
588 [ 'keyname', 'exptime' ],
589 $conds,
590 __METHOD__,
591 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
592 if ( $rows === false || !$rows->numRows() ) {
593 break;
594 }
595 $keys = [];
596 $row = $rows->current();
597 $minExpTime = $row->exptime;
598 if ( $totalSeconds === false ) {
599 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
600 - wfTimestamp( TS_UNIX, $minExpTime );
601 }
602 foreach ( $rows as $row ) {
603 $keys[] = $row->keyname;
604 $maxExpTime = $row->exptime;
605 }
606
607 $db->delete(
608 $this->getTableNameByShard( $i ),
609 [
610 'exptime >= ' . $db->addQuotes( $minExpTime ),
611 'exptime < ' . $db->addQuotes( $dbTimestamp ),
612 'keyname' => $keys
613 ],
614 __METHOD__ );
615
616 if ( $progressCallback ) {
617 if ( intval( $totalSeconds ) === 0 ) {
618 $percent = 0;
619 } else {
620 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
621 - wfTimestamp( TS_UNIX, $maxExpTime );
622 if ( $remainingSeconds > $totalSeconds ) {
623 $totalSeconds = $remainingSeconds;
624 }
625 $processedSeconds = $totalSeconds - $remainingSeconds;
626 $percent = ( $i + $processedSeconds / $totalSeconds )
627 / $this->shards * 100;
628 }
629 $percent = ( $percent / $this->numServers )
630 + ( $serverIndex / $this->numServers * 100 );
631 call_user_func( $progressCallback, $percent );
632 }
633 }
634 }
635 } catch ( DBError $e ) {
636 $this->handleWriteError( $e, $db, $serverIndex );
637 return false;
638 }
639 }
640 return true;
641 }
642
648 public function deleteAll() {
649 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
650 $db = null;
651 try {
652 $db = $this->getDB( $serverIndex );
653 for ( $i = 0; $i < $this->shards; $i++ ) {
654 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
655 }
656 } catch ( DBError $e ) {
657 $this->handleWriteError( $e, $db, $serverIndex );
658 return false;
659 }
660 }
661 return true;
662 }
663
672 protected function serialize( &$data ) {
673 $serial = serialize( $data );
674
675 if ( function_exists( 'gzdeflate' ) ) {
676 return gzdeflate( $serial );
677 } else {
678 return $serial;
679 }
680 }
681
687 protected function unserialize( $serial ) {
688 if ( function_exists( 'gzinflate' ) ) {
689 MediaWiki\suppressWarnings();
690 $decomp = gzinflate( $serial );
691 MediaWiki\restoreWarnings();
692
693 if ( false !== $decomp ) {
694 $serial = $decomp;
695 }
696 }
697
698 $ret = unserialize( $serial );
699
700 return $ret;
701 }
702
709 protected function handleReadError( DBError $exception, $serverIndex ) {
710 if ( $exception instanceof DBConnectionError ) {
711 $this->markServerDown( $exception, $serverIndex );
712 }
713 $this->logger->error( "DBError: {$exception->getMessage()}" );
714 if ( $exception instanceof DBConnectionError ) {
716 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
717 } else {
719 $this->logger->debug( __METHOD__ . ": ignoring query error" );
720 }
721 }
722
731 protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
732 if ( !$db ) {
733 $this->markServerDown( $exception, $serverIndex );
734 } elseif ( $db->wasReadOnlyError() ) {
735 if ( $db->trxLevel() && $this->usesMainDB() ) {
736 // Errors like deadlocks and connection drops already cause rollback.
737 // For consistency, we have no choice but to throw an error and trigger
738 // complete rollback if the main DB is also being used as the cache DB.
739 throw $exception;
740 }
741 }
742
743 $this->logger->error( "DBError: {$exception->getMessage()}" );
744 if ( $exception instanceof DBConnectionError ) {
746 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
747 } else {
749 $this->logger->debug( __METHOD__ . ": ignoring query error" );
750 }
751 }
752
759 protected function markServerDown( DBError $exception, $serverIndex ) {
760 unset( $this->conns[$serverIndex] ); // bug T103435
761
762 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
763 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
764 unset( $this->connFailureTimes[$serverIndex] );
765 unset( $this->connFailureErrors[$serverIndex] );
766 } else {
767 $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
768 return;
769 }
770 }
771 $now = time();
772 $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
773 $this->connFailureTimes[$serverIndex] = $now;
774 $this->connFailureErrors[$serverIndex] = $exception;
775 }
776
780 public function createTables() {
781 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
782 $db = $this->getDB( $serverIndex );
783 if ( $db->getType() !== 'mysql' ) {
784 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
785 }
786
787 for ( $i = 0; $i < $this->shards; $i++ ) {
788 $db->query(
789 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
790 ' LIKE ' . $db->tableName( 'objectcache' ),
791 __METHOD__ );
792 }
793 }
794 }
795
799 protected function usesMainDB() {
800 return !$this->serverInfos;
801 }
802
803 protected function waitForReplication() {
804 if ( !$this->usesMainDB() ) {
805 // Custom DB server list; probably doesn't use replication
806 return true;
807 }
808
809 $lb = $this->getSeparateMainLB()
810 ?: MediaWikiServices::getInstance()->getDBLoadBalancer();
811
812 if ( $lb->getServerCount() <= 1 ) {
813 return true; // no replica DBs
814 }
815
816 // Main LB is used; wait for any replica DBs to catch up
817 $masterPos = $lb->getMasterPos();
818
819 $loop = new WaitConditionLoop(
820 function () use ( $lb, $masterPos ) {
821 return $lb->waitForAll( $masterPos, 1 );
822 },
825 );
826
827 return ( $loop->invoke() === $loop::CONDITION_REACHED );
828 }
829}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
serialize()
$wgDBtype
Database type.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static consistentHashSort(&$array, $key, $separator="\000")
Sort the given array in a pseudo-random order which depends only on the given key and each element va...
interface is intended to be more or less compatible with the PHP memcached client.
Definition BagOStuff.php:47
const ERR_UNEXPECTED
Definition BagOStuff.php:80
convertExpiry( $exptime)
Convert an optionally relative time to an absolute time.
callable[] $busyCallbacks
Definition BagOStuff.php:71
debug( $text)
setLastError( $err)
Set the "last error" registry.
mergeViaCas( $key, $callback, $exptime=0, $attempts=10)
const ERR_UNREACHABLE
Definition BagOStuff.php:79
Database error base class.
Definition DBError.php:26
Database connection, tracking, load balancing, and transaction manager for a cluster.
MediaWiki exception.
Class to store objects in the database.
getDB( $serverIndex)
Get a connection to the specified database.
doGet( $key, $flags=0)
string[] $serverTags
(server index => tag/host name)
LoadBalancer null $separateMainLB
createTables()
Create shard tables.
getTableByKey( $key)
Get the server index and table name for a given key.
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
array[] $serverInfos
(server index => server config)
deleteAll()
Delete content of shard tables in every server.
__construct( $params)
Constructor.
getWithToken( $key, &$casToken, $flags=0)
isExpired( $db, $exptime)
changeTTL( $key, $expiry=0)
Reset the TTL on a key if it exists.
handleWriteError(DBError $exception, IDatabase $db=null, $serverIndex)
Handle a DBQueryError which occurred during a write operation.
array $connFailureTimes
UNIX timestamps.
array $connFailureErrors
Exceptions.
deleteObjectsExpiringBefore( $timestamp, $progressCallback=false)
Delete objects from the database which expire before a certain date.
cas( $casToken, $key, $value, $exptime=0)
Check and set an item.
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
serialize(&$data)
Serialize an object and, if possible, compress the representation.
markServerDown(DBError $exception, $serverIndex)
Mark a server down due to a DBConnectionError exception.
unserialize( $serial)
Unserialize and, if necessary, decompress an object.
string $tableName
getTableNameByShard( $index)
Get the table name for a given shard index.
incr( $key, $step=1)
Increase stored value of $key by $value while preserving its TTL.
handleReadError(DBError $exception, $serverIndex)
Handle a DBError which occurred during a read operation.
setMulti(array $data, $expiry=0)
Batch insertion.
Helper class that detects high-contention DB queries via profiling calls.
$res
Definition database.txt:21
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
Definition design.txt:26
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
$lbFactory
the array() calling protocol came about after MediaWiki 1.4rc1.
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition hooks.txt:2568
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1937
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2710
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:1949
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition hooks.txt:1033
returning false will NOT prevent logging $e
Definition hooks.txt:2110
if( $limit) $timestamp
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:34
const DB_REPLICA
Definition defines.php:22
const DB_MASTER
Definition defines.php:23
const DBO_TRX
Definition defines.php:9
$params
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition defines.php:6