MediaWiki  master
DatabaseMysqlBase.php
Go to the documentation of this file.
1 <?php
32 abstract class DatabaseMysqlBase extends Database {
34  protected $lastKnownSlavePos;
38  protected $lagDetectionOptions = [];
40  protected $useGTIDs = false;
41 
43  private $serverVersion = null;
44 
58  function __construct( array $params ) {
59  parent::__construct( $params );
60 
61  $this->lagDetectionMethod = isset( $params['lagDetectionMethod'] )
62  ? $params['lagDetectionMethod']
63  : 'Seconds_Behind_Master';
64  $this->lagDetectionOptions = isset( $params['lagDetectionOptions'] )
65  ? $params['lagDetectionOptions']
66  : [];
67  $this->useGTIDs = !empty( $params['useGTIDs' ] );
68  }
69 
73  function getType() {
74  return 'mysql';
75  }
76 
85  function open( $server, $user, $password, $dbName ) {
87 
88  # Close/unset connection handle
89  $this->close();
90 
91  # Debugging hack -- fake cluster
92  $realServer = $wgAllDBsAreLocalhost ? 'localhost' : $server;
93  $this->mServer = $server;
94  $this->mUser = $user;
95  $this->mPassword = $password;
96  $this->mDBname = $dbName;
97 
98  $this->installErrorHandler();
99  try {
100  $this->mConn = $this->mysqlConnect( $realServer );
101  } catch ( Exception $ex ) {
102  $this->restoreErrorHandler();
103  throw $ex;
104  }
105  $error = $this->restoreErrorHandler();
106 
107  # Always log connection errors
108  if ( !$this->mConn ) {
109  if ( !$error ) {
110  $error = $this->lastError();
111  }
112  wfLogDBError(
113  "Error connecting to {db_server}: {error}",
114  $this->getLogContext( [
115  'method' => __METHOD__,
116  'error' => $error,
117  ] )
118  );
119  wfDebug( "DB connection error\n" .
120  "Server: $server, User: $user, Password: " .
121  substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
122 
123  $this->reportConnectionError( $error );
124  }
125 
126  if ( $dbName != '' ) {
127  MediaWiki\suppressWarnings();
128  $success = $this->selectDB( $dbName );
129  MediaWiki\restoreWarnings();
130  if ( !$success ) {
131  wfLogDBError(
132  "Error selecting database {db_name} on server {db_server}",
133  $this->getLogContext( [
134  'method' => __METHOD__,
135  ] )
136  );
137  wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
138  "from client host " . wfHostname() . "\n" );
139 
140  $this->reportConnectionError( "Error selecting database $dbName" );
141  }
142  }
143 
144  // Tell the server what we're communicating with
145  if ( !$this->connectInitCharset() ) {
146  $this->reportConnectionError( "Error setting character set" );
147  }
148 
149  // Abstract over any insane MySQL defaults
150  $set = [ 'group_concat_max_len = 262144' ];
151  // Set SQL mode, default is turning them all off, can be overridden or skipped with null
152  if ( is_string( $wgSQLMode ) ) {
153  $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
154  }
155  // Set any custom settings defined by site config
156  // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
157  foreach ( $this->mSessionVars as $var => $val ) {
158  // Escape strings but not numbers to avoid MySQL complaining
159  if ( !is_int( $val ) && !is_float( $val ) ) {
160  $val = $this->addQuotes( $val );
161  }
162  $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
163  }
164 
165  if ( $set ) {
166  // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
167  $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
168  if ( !$success ) {
169  wfLogDBError(
170  'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
171  $this->getLogContext( [
172  'method' => __METHOD__,
173  ] )
174  );
175  $this->reportConnectionError(
176  'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
177  }
178  }
179 
180  $this->mOpened = true;
181 
182  return true;
183  }
184 
189  protected function connectInitCharset() {
191 
192  if ( $wgDBmysql5 ) {
193  // Tell the server we're communicating with it in UTF-8.
194  // This may engage various charset conversions.
195  return $this->mysqlSetCharset( 'utf8' );
196  } else {
197  return $this->mysqlSetCharset( 'binary' );
198  }
199  }
200 
208  abstract protected function mysqlConnect( $realServer );
209 
216  abstract protected function mysqlSetCharset( $charset );
217 
222  function freeResult( $res ) {
223  if ( $res instanceof ResultWrapper ) {
224  $res = $res->result;
225  }
226  MediaWiki\suppressWarnings();
227  $ok = $this->mysqlFreeResult( $res );
228  MediaWiki\restoreWarnings();
229  if ( !$ok ) {
230  throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
231  }
232  }
233 
240  abstract protected function mysqlFreeResult( $res );
241 
247  function fetchObject( $res ) {
248  if ( $res instanceof ResultWrapper ) {
249  $res = $res->result;
250  }
251  MediaWiki\suppressWarnings();
252  $row = $this->mysqlFetchObject( $res );
253  MediaWiki\restoreWarnings();
254 
255  $errno = $this->lastErrno();
256  // Unfortunately, mysql_fetch_object does not reset the last errno.
257  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
258  // these are the only errors mysql_fetch_object can cause.
259  // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
260  if ( $errno == 2000 || $errno == 2013 ) {
261  throw new DBUnexpectedError(
262  $this,
263  'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
264  );
265  }
266 
267  return $row;
268  }
269 
276  abstract protected function mysqlFetchObject( $res );
277 
283  function fetchRow( $res ) {
284  if ( $res instanceof ResultWrapper ) {
285  $res = $res->result;
286  }
287  MediaWiki\suppressWarnings();
288  $row = $this->mysqlFetchArray( $res );
289  MediaWiki\restoreWarnings();
290 
291  $errno = $this->lastErrno();
292  // Unfortunately, mysql_fetch_array does not reset the last errno.
293  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
294  // these are the only errors mysql_fetch_array can cause.
295  // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
296  if ( $errno == 2000 || $errno == 2013 ) {
297  throw new DBUnexpectedError(
298  $this,
299  'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
300  );
301  }
302 
303  return $row;
304  }
305 
312  abstract protected function mysqlFetchArray( $res );
313 
319  function numRows( $res ) {
320  if ( $res instanceof ResultWrapper ) {
321  $res = $res->result;
322  }
323  MediaWiki\suppressWarnings();
324  $n = $this->mysqlNumRows( $res );
325  MediaWiki\restoreWarnings();
326 
327  // Unfortunately, mysql_num_rows does not reset the last errno.
328  // We are not checking for any errors here, since
329  // these are no errors mysql_num_rows can cause.
330  // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
331  // See https://phabricator.wikimedia.org/T44430
332  return $n;
333  }
334 
341  abstract protected function mysqlNumRows( $res );
342 
347  function numFields( $res ) {
348  if ( $res instanceof ResultWrapper ) {
349  $res = $res->result;
350  }
351 
352  return $this->mysqlNumFields( $res );
353  }
354 
361  abstract protected function mysqlNumFields( $res );
362 
368  function fieldName( $res, $n ) {
369  if ( $res instanceof ResultWrapper ) {
370  $res = $res->result;
371  }
372 
373  return $this->mysqlFieldName( $res, $n );
374  }
375 
383  abstract protected function mysqlFieldName( $res, $n );
384 
391  public function fieldType( $res, $n ) {
392  if ( $res instanceof ResultWrapper ) {
393  $res = $res->result;
394  }
395 
396  return $this->mysqlFieldType( $res, $n );
397  }
398 
406  abstract protected function mysqlFieldType( $res, $n );
407 
413  function dataSeek( $res, $row ) {
414  if ( $res instanceof ResultWrapper ) {
415  $res = $res->result;
416  }
417 
418  return $this->mysqlDataSeek( $res, $row );
419  }
420 
428  abstract protected function mysqlDataSeek( $res, $row );
429 
433  function lastError() {
434  if ( $this->mConn ) {
435  # Even if it's non-zero, it can still be invalid
436  MediaWiki\suppressWarnings();
437  $error = $this->mysqlError( $this->mConn );
438  if ( !$error ) {
439  $error = $this->mysqlError();
440  }
441  MediaWiki\restoreWarnings();
442  } else {
443  $error = $this->mysqlError();
444  }
445  if ( $error ) {
446  $error .= ' (' . $this->mServer . ')';
447  }
448 
449  return $error;
450  }
451 
458  abstract protected function mysqlError( $conn = null );
459 
467  function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
468  return $this->nativeReplace( $table, $rows, $fname );
469  }
470 
483  public function estimateRowCount( $table, $vars = '*', $conds = '',
484  $fname = __METHOD__, $options = []
485  ) {
486  $options['EXPLAIN'] = true;
487  $res = $this->select( $table, $vars, $conds, $fname, $options );
488  if ( $res === false ) {
489  return false;
490  }
491  if ( !$this->numRows( $res ) ) {
492  return 0;
493  }
494 
495  $rows = 1;
496  foreach ( $res as $plan ) {
497  $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
498  }
499 
500  return (int)$rows;
501  }
502 
508  function fieldInfo( $table, $field ) {
509  $table = $this->tableName( $table );
510  $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
511  if ( !$res ) {
512  return false;
513  }
514  $n = $this->mysqlNumFields( $res->result );
515  for ( $i = 0; $i < $n; $i++ ) {
516  $meta = $this->mysqlFetchField( $res->result, $i );
517  if ( $field == $meta->name ) {
518  return new MySQLField( $meta );
519  }
520  }
521 
522  return false;
523  }
524 
532  abstract protected function mysqlFetchField( $res, $n );
533 
543  function indexInfo( $table, $index, $fname = __METHOD__ ) {
544  # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
545  # SHOW INDEX should work for 3.x and up:
546  # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
547  $table = $this->tableName( $table );
548  $index = $this->indexName( $index );
549 
550  $sql = 'SHOW INDEX FROM ' . $table;
551  $res = $this->query( $sql, $fname );
552 
553  if ( !$res ) {
554  return null;
555  }
556 
557  $result = [];
558 
559  foreach ( $res as $row ) {
560  if ( $row->Key_name == $index ) {
561  $result[] = $row;
562  }
563  }
564 
565  return empty( $result ) ? false : $result;
566  }
567 
572  function strencode( $s ) {
573  $sQuoted = $this->mysqlRealEscapeString( $s );
574 
575  if ( $sQuoted === false ) {
576  $this->ping();
577  $sQuoted = $this->mysqlRealEscapeString( $s );
578  }
579 
580  return $sQuoted;
581  }
582 
587  abstract protected function mysqlRealEscapeString( $s );
588 
595  public function addIdentifierQuotes( $s ) {
596  // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
597  // Remove NUL bytes and escape backticks by doubling
598  return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
599  }
600 
605  public function isQuotedIdentifier( $name ) {
606  return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
607  }
608 
612  function ping() {
613  $ping = $this->mysqlPing();
614  if ( $ping ) {
615  // Connection was good or lost but reconnected...
616  // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
617  return true;
618  }
619 
620  // Try a full disconnect/reconnect cycle if ping() failed
621  $this->closeConnection();
622  $this->mOpened = false;
623  $this->mConn = false;
624  $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
625 
626  return true;
627  }
628 
634  abstract protected function mysqlPing();
635 
636  function getLag() {
637  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
638  return $this->getLagFromPtHeartbeat();
639  } else {
640  return $this->getLagFromSlaveStatus();
641  }
642  }
643 
647  protected function getLagDetectionMethod() {
649  }
650 
654  protected function getLagFromSlaveStatus() {
655  $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
656  $row = $res ? $res->fetchObject() : false;
657  if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
658  return intval( $row->Seconds_Behind_Master );
659  }
660 
661  return false;
662  }
663 
667  protected function getLagFromPtHeartbeat() {
669 
670  if ( isset( $options['conds'] ) ) {
671  // Best method for multi-DC setups: use logical channel names
672  $data = $this->getHeartbeatData( $options['conds'] );
673  } else {
674  // Standard method: use master server ID (works with stock pt-heartbeat)
675  $masterInfo = $this->getMasterServerInfo();
676  if ( !$masterInfo ) {
677  wfLogDBError(
678  "Unable to query master of {db_server} for server ID",
679  $this->getLogContext( [
680  'method' => __METHOD__
681  ] )
682  );
683 
684  return false; // could not get master server ID
685  }
686 
687  $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
688  $data = $this->getHeartbeatData( $conds );
689  }
690 
691  list( $time, $nowUnix ) = $data;
692  if ( $time !== null ) {
693  // @time is in ISO format like "2015-09-25T16:48:10.000510"
694  $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
695  $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
696 
697  return max( $nowUnix - $timeUnix, 0.0 );
698  }
699 
700  wfLogDBError(
701  "Unable to find pt-heartbeat row for {db_server}",
702  $this->getLogContext( [
703  'method' => __METHOD__
704  ] )
705  );
706 
707  return false;
708  }
709 
710  protected function getMasterServerInfo() {
712  $key = $cache->makeGlobalKey(
713  'mysql',
714  'master-info',
715  // Using one key for all cluster slaves is preferable
716  $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
717  );
718 
719  return $cache->getWithSetCallback(
720  $key,
721  $cache::TTL_INDEFINITE,
722  function () use ( $cache, $key ) {
723  // Get and leave a lock key in place for a short period
724  if ( !$cache->lock( $key, 0, 10 ) ) {
725  return false; // avoid master connection spike slams
726  }
727 
728  $conn = $this->getLazyMasterHandle();
729  if ( !$conn ) {
730  return false; // something is misconfigured
731  }
732 
733  // Connect to and query the master; catch errors to avoid outages
734  try {
735  $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
736  $row = $res ? $res->fetchObject() : false;
737  $id = $row ? (int)$row->id : 0;
738  } catch ( DBError $e ) {
739  $id = 0;
740  }
741 
742  // Cache the ID if it was retrieved
743  return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
744  }
745  );
746  }
747 
753  protected function getHeartbeatData( array $conds ) {
754  $whereSQL = $this->makeList( $conds, LIST_AND );
755  // Use ORDER BY for channel based queries since that field might not be UNIQUE.
756  // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
757  // percision field is not supported in MySQL <= 5.5.
758  $res = $this->query(
759  "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
760  );
761  $row = $res ? $res->fetchObject() : false;
762 
763  return [ $row ? $row->ts : null, microtime( true ) ];
764  }
765 
766  public function getApproximateLagStatus() {
767  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
768  // Disable caching since this is fast enough and we don't wan't
769  // to be *too* pessimistic by having both the cache TTL and the
770  // pt-heartbeat interval count as lag in getSessionLagStatus()
771  return parent::getApproximateLagStatus();
772  }
773 
774  $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
775  $approxLag = $this->srvCache->get( $key );
776  if ( !$approxLag ) {
777  $approxLag = parent::getApproximateLagStatus();
778  $this->srvCache->set( $key, $approxLag, 1 );
779  }
780 
781  return $approxLag;
782  }
783 
784  function masterPosWait( DBMasterPos $pos, $timeout ) {
785  if ( !( $pos instanceof MySQLMasterPos ) ) {
786  throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
787  }
788 
789  if ( $this->getLBInfo( 'is static' ) === true ) {
790  return 0; // this is a copy of a read-only dataset with no master DB
791  } elseif ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
792  return 0; // already reached this point for sure
793  }
794 
795  // Commit any open transactions
796  $this->commit( __METHOD__, 'flush' );
797 
798  // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
799  if ( $this->useGTIDs && $pos->gtids ) {
800  // Wait on the GTID set (MariaDB only)
801  $gtidArg = implode( ',', $pos->gtids );
802  $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
803  } else {
804  // Wait on the binlog coordinates
805  $encFile = $this->addQuotes( $pos->file );
806  $encPos = intval( $pos->pos );
807  $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
808  }
809 
810  $row = $res ? $this->fetchRow( $res ) : false;
811  if ( !$row ) {
812  throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
813  }
814 
815  // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
816  $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
817  if ( $status === null ) {
818  // T126436: jobs programmed to wait on master positions might be referencing binlogs
819  // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
820  // to detect this and treat the slave as having reached the position; a proper master
821  // switchover already requires that the new master be caught up before the switch.
822  $slavePos = $this->getSlavePos();
823  if ( $slavePos && !$slavePos->channelsMatch( $pos ) ) {
824  $this->lastKnownSlavePos = $slavePos;
825  $status = 0;
826  }
827  } elseif ( $status >= 0 ) {
828  // Remember that this position was reached to save queries next time
829  $this->lastKnownSlavePos = $pos;
830  }
831 
832  return $status;
833  }
834 
840  function getSlavePos() {
841  $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
842  $row = $this->fetchObject( $res );
843 
844  if ( $row ) {
845  $pos = isset( $row->Exec_master_log_pos )
846  ? $row->Exec_master_log_pos
847  : $row->Exec_Master_Log_Pos;
848  // Also fetch the last-applied GTID set (MariaDB)
849  if ( $this->useGTIDs ) {
850  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
851  $gtidRow = $this->fetchObject( $res );
852  $gtidSet = $gtidRow ? $gtidRow->Value : '';
853  } else {
854  $gtidSet = '';
855  }
856 
857  return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
858  } else {
859  return false;
860  }
861  }
862 
868  function getMasterPos() {
869  $res = $this->query( 'SHOW MASTER STATUS', __METHOD__ );
870  $row = $this->fetchObject( $res );
871 
872  if ( $row ) {
873  // Also fetch the last-written GTID set (MariaDB)
874  if ( $this->useGTIDs ) {
875  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
876  $gtidRow = $this->fetchObject( $res );
877  $gtidSet = $gtidRow ? $gtidRow->Value : '';
878  } else {
879  $gtidSet = '';
880  }
881 
882  return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
883  } else {
884  return false;
885  }
886  }
887 
888  public function serverIsReadOnly() {
889  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
890  $row = $this->fetchObject( $res );
891 
892  return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
893  }
894 
899  function useIndexClause( $index ) {
900  return "FORCE INDEX (" . $this->indexName( $index ) . ")";
901  }
902 
906  function lowPriorityOption() {
907  return 'LOW_PRIORITY';
908  }
909 
913  public function getSoftwareLink() {
914  // MariaDB includes its name in its version string; this is how MariaDB's version of
915  // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
916  // in libmysql/libmysql.c).
917  $version = $this->getServerVersion();
918  if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
919  return '[{{int:version-db-mariadb-url}} MariaDB]';
920  }
921 
922  // Percona Server's version suffix is not very distinctive, and @@version_comment
923  // doesn't give the necessary info for source builds, so assume the server is MySQL.
924  // (Even Percona's version of mysql doesn't try to make the distinction.)
925  return '[{{int:version-db-mysql-url}} MySQL]';
926  }
927 
931  public function getServerVersion() {
932  // Not using mysql_get_server_info() or similar for consistency: in the handshake,
933  // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
934  // it off (see RPL_VERSION_HACK in include/mysql_com.h).
935  if ( $this->serverVersion === null ) {
936  $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
937  }
938  return $this->serverVersion;
939  }
940 
944  public function setSessionOptions( array $options ) {
945  if ( isset( $options['connTimeout'] ) ) {
946  $timeout = (int)$options['connTimeout'];
947  $this->query( "SET net_read_timeout=$timeout" );
948  $this->query( "SET net_write_timeout=$timeout" );
949  }
950  }
951 
957  public function streamStatementEnd( &$sql, &$newLine ) {
958  if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
959  preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
960  $this->delimiter = $m[1];
961  $newLine = '';
962  }
963 
964  return parent::streamStatementEnd( $sql, $newLine );
965  }
966 
975  public function lockIsFree( $lockName, $method ) {
976  $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
977  $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
978  $row = $this->fetchObject( $result );
979 
980  return ( $row->lockstatus == 1 );
981  }
982 
989  public function lock( $lockName, $method, $timeout = 5 ) {
990  $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
991  $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
992  $row = $this->fetchObject( $result );
993 
994  if ( $row->lockstatus == 1 ) {
995  parent::lock( $lockName, $method, $timeout ); // record
996  return true;
997  }
998 
999  wfDebug( __METHOD__ . " failed to acquire lock\n" );
1000 
1001  return false;
1002  }
1003 
1011  public function unlock( $lockName, $method ) {
1012  $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
1013  $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
1014  $row = $this->fetchObject( $result );
1015 
1016  if ( $row->lockstatus == 1 ) {
1017  parent::unlock( $lockName, $method ); // record
1018  return true;
1019  }
1020 
1021  wfDebug( __METHOD__ . " failed to release lock\n" );
1022 
1023  return false;
1024  }
1025 
1026  private function makeLockName( $lockName ) {
1027  // http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1028  // Newer version enforce a 64 char length limit.
1029  return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1030  }
1031 
1032  public function namedLocksEnqueue() {
1033  return true;
1034  }
1035 
1043  public function lockTables( $read, $write, $method, $lowPriority = true ) {
1044  $items = [];
1045 
1046  foreach ( $write as $table ) {
1047  $tbl = $this->tableName( $table ) .
1048  ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
1049  ' WRITE';
1050  $items[] = $tbl;
1051  }
1052  foreach ( $read as $table ) {
1053  $items[] = $this->tableName( $table ) . ' READ';
1054  }
1055  $sql = "LOCK TABLES " . implode( ',', $items );
1056  $this->query( $sql, $method );
1057 
1058  return true;
1059  }
1060 
1065  public function unlockTables( $method ) {
1066  $this->query( "UNLOCK TABLES", $method );
1067 
1068  return true;
1069  }
1070 
1077  public function getSearchEngine() {
1078  return 'SearchMySQL';
1079  }
1080 
1084  public function setBigSelects( $value = true ) {
1085  if ( $value === 'default' ) {
1086  if ( $this->mDefaultBigSelects === null ) {
1087  # Function hasn't been called before so it must already be set to the default
1088  return;
1089  } else {
1091  }
1092  } elseif ( $this->mDefaultBigSelects === null ) {
1093  $this->mDefaultBigSelects =
1094  (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1095  }
1096  $encValue = $value ? '1' : '0';
1097  $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1098  }
1099 
1111  function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
1112  if ( !$conds ) {
1113  throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1114  }
1115 
1116  $delTable = $this->tableName( $delTable );
1117  $joinTable = $this->tableName( $joinTable );
1118  $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1119 
1120  if ( $conds != '*' ) {
1121  $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1122  }
1123 
1124  return $this->query( $sql, $fname );
1125  }
1126 
1135  public function upsert( $table, array $rows, array $uniqueIndexes,
1136  array $set, $fname = __METHOD__
1137  ) {
1138  if ( !count( $rows ) ) {
1139  return true; // nothing to do
1140  }
1141 
1142  if ( !is_array( reset( $rows ) ) ) {
1143  $rows = [ $rows ];
1144  }
1145 
1146  $table = $this->tableName( $table );
1147  $columns = array_keys( $rows[0] );
1148 
1149  $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1150  $rowTuples = [];
1151  foreach ( $rows as $row ) {
1152  $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1153  }
1154  $sql .= implode( ',', $rowTuples );
1155  $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
1156 
1157  return (bool)$this->query( $sql, $fname );
1158  }
1159 
1165  function getServerUptime() {
1166  $vars = $this->getMysqlStatus( 'Uptime' );
1167 
1168  return (int)$vars['Uptime'];
1169  }
1170 
1176  function wasDeadlock() {
1177  return $this->lastErrno() == 1213;
1178  }
1179 
1185  function wasLockTimeout() {
1186  return $this->lastErrno() == 1205;
1187  }
1188 
1195  function wasErrorReissuable() {
1196  return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1197  }
1198 
1204  function wasReadOnlyError() {
1205  return $this->lastErrno() == 1223 ||
1206  ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1207  }
1208 
1209  function wasConnectionError( $errno ) {
1210  return $errno == 2013 || $errno == 2006;
1211  }
1212 
1224  protected function getBindingHandle() {
1225  if ( !$this->mConn ) {
1226  throw new DBUnexpectedError(
1227  $this,
1228  'DB connection was already closed or the connection dropped.'
1229  );
1230  }
1231 
1232  return $this->mConn;
1233  }
1234 
1242  function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1243  $tmp = $temporary ? 'TEMPORARY ' : '';
1244  $newName = $this->addIdentifierQuotes( $newName );
1245  $oldName = $this->addIdentifierQuotes( $oldName );
1246  $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1247 
1248  return $this->query( $query, $fname );
1249  }
1250 
1258  function listTables( $prefix = null, $fname = __METHOD__ ) {
1259  $result = $this->query( "SHOW TABLES", $fname );
1260 
1261  $endArray = [];
1262 
1263  foreach ( $result as $table ) {
1264  $vars = get_object_vars( $table );
1265  $table = array_pop( $vars );
1266 
1267  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1268  $endArray[] = $table;
1269  }
1270  }
1271 
1272  return $endArray;
1273  }
1274 
1280  public function dropTable( $tableName, $fName = __METHOD__ ) {
1281  if ( !$this->tableExists( $tableName, $fName ) ) {
1282  return false;
1283  }
1284 
1285  return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1286  }
1287 
1291  protected function getDefaultSchemaVars() {
1292  $vars = parent::getDefaultSchemaVars();
1293  $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1294  $vars['wgDBTableOptions'] = str_replace(
1295  'CHARSET=mysql4',
1296  'CHARSET=binary',
1297  $vars['wgDBTableOptions']
1298  );
1299 
1300  return $vars;
1301  }
1302 
1309  function getMysqlStatus( $which = "%" ) {
1310  $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1311  $status = [];
1312 
1313  foreach ( $res as $row ) {
1314  $status[$row->Variable_name] = $row->Value;
1315  }
1316 
1317  return $status;
1318  }
1319 
1329  public function listViews( $prefix = null, $fname = __METHOD__ ) {
1330 
1331  if ( !isset( $this->allViews ) ) {
1332 
1333  // The name of the column containing the name of the VIEW
1334  $propertyName = 'Tables_in_' . $this->mDBname;
1335 
1336  // Query for the VIEWS
1337  $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1338  $this->allViews = [];
1339  while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1340  array_push( $this->allViews, $row[$propertyName] );
1341  }
1342  }
1343 
1344  if ( is_null( $prefix ) || $prefix === '' ) {
1345  return $this->allViews;
1346  }
1347 
1348  $filteredViews = [];
1349  foreach ( $this->allViews as $viewName ) {
1350  // Does the name of this VIEW start with the table-prefix?
1351  if ( strpos( $viewName, $prefix ) === 0 ) {
1352  array_push( $filteredViews, $viewName );
1353  }
1354  }
1355 
1356  return $filteredViews;
1357  }
1358 
1367  public function isView( $name, $prefix = null ) {
1368  return in_array( $name, $this->listViews( $prefix ) );
1369  }
1370 }
1371 
1376 class MySQLField implements Field {
1380 
1381  function __construct( $info ) {
1382  $this->name = $info->name;
1383  $this->tablename = $info->table;
1384  $this->default = $info->def;
1385  $this->max_length = $info->max_length;
1386  $this->nullable = !$info->not_null;
1387  $this->is_pk = $info->primary_key;
1388  $this->is_unique = $info->unique_key;
1389  $this->is_multiple = $info->multiple_key;
1390  $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1391  $this->type = $info->type;
1392  $this->binary = isset( $info->binary ) ? $info->binary : false;
1393  $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false;
1394  $this->is_blob = isset( $info->blob ) ? $info->blob : false;
1395  $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false;
1396  $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false;
1397  }
1398 
1402  function name() {
1403  return $this->name;
1404  }
1405 
1409  function tableName() {
1410  return $this->tablename;
1411  }
1412 
1416  function type() {
1417  return $this->type;
1418  }
1419 
1423  function isNullable() {
1424  return $this->nullable;
1425  }
1426 
1427  function defaultValue() {
1428  return $this->default;
1429  }
1430 
1434  function isKey() {
1435  return $this->is_key;
1436  }
1437 
1441  function isMultipleKey() {
1442  return $this->is_multiple;
1443  }
1444 
1448  function isBinary() {
1449  return $this->binary;
1450  }
1451 
1455  function isNumeric() {
1456  return $this->is_numeric;
1457  }
1458 
1462  function isBlob() {
1463  return $this->is_blob;
1464  }
1465 
1469  function isUnsigned() {
1470  return $this->is_unsigned;
1471  }
1472 
1476  function isZerofill() {
1477  return $this->is_zerofill;
1478  }
1479 }
1480 
1489 class MySQLMasterPos implements DBMasterPos {
1491  public $file;
1493  public $pos;
1495  public $gtids = [];
1497  public $asOfTime = 0.0;
1498 
1504  function __construct( $file, $pos, $gtid = '' ) {
1505  $this->file = $file;
1506  $this->pos = $pos;
1507  $this->gtids = array_map( 'trim', explode( ',', $gtid ) );
1508  $this->asOfTime = microtime( true );
1509  }
1510 
1514  function __toString() {
1515  return "{$this->file}/{$this->pos}";
1516  }
1517 
1518  function asOfTime() {
1519  return $this->asOfTime;
1520  }
1521 
1523  if ( !( $pos instanceof self ) ) {
1524  throw new InvalidArgumentException( "Position not an instance of " . __CLASS__ );
1525  }
1526 
1527  // Prefer GTID comparisons, which work with multi-tier replication
1528  $thisPosByDomain = $this->getGtidCoordinates();
1529  $thatPosByDomain = $pos->getGtidCoordinates();
1530  if ( $thisPosByDomain && $thatPosByDomain ) {
1531  $reached = true;
1532  // Check that this has positions GTE all of those in $pos for all domains in $pos
1533  foreach ( $thatPosByDomain as $domain => $thatPos ) {
1534  $thisPos = isset( $thisPosByDomain[$domain] ) ? $thisPosByDomain[$domain] : -1;
1535  $reached = $reached && ( $thatPos <= $thisPos );
1536  }
1537 
1538  return $reached;
1539  }
1540 
1541  // Fallback to the binlog file comparisons
1542  $thisBinPos = $this->getBinlogCoordinates();
1543  $thatBinPos = $pos->getBinlogCoordinates();
1544  if ( $thisBinPos && $thatBinPos && $thisBinPos['binlog'] === $thatBinPos['binlog'] ) {
1545  return ( $thisBinPos['pos'] >= $thatBinPos['pos'] );
1546  }
1547 
1548  // Comparing totally different binlogs does not make sense
1549  return false;
1550  }
1551 
1553  if ( !( $pos instanceof self ) ) {
1554  throw new InvalidArgumentException( "Position not an instance of " . __CLASS__ );
1555  }
1556 
1557  // Prefer GTID comparisons, which work with multi-tier replication
1558  $thisPosDomains = array_keys( $this->getGtidCoordinates() );
1559  $thatPosDomains = array_keys( $pos->getGtidCoordinates() );
1560  if ( $thisPosDomains && $thatPosDomains ) {
1561  // Check that this has GTIDs for all domains in $pos
1562  return !array_diff( $thatPosDomains, $thisPosDomains );
1563  }
1564 
1565  // Fallback to the binlog file comparisons
1566  $thisBinPos = $this->getBinlogCoordinates();
1567  $thatBinPos = $pos->getBinlogCoordinates();
1568 
1569  return ( $thisBinPos && $thatBinPos && $thisBinPos['binlog'] === $thatBinPos['binlog'] );
1570  }
1571 
1578  protected function getGtidCoordinates() {
1579  $gtidInfos = [];
1580  foreach ( $this->gtids as $gtid ) {
1581  $m = [];
1582  // MariaDB style: <domain>-<server id>-<sequence number>
1583  if ( preg_match( '!^(\d+)-\d+-(\d+)$!', $gtid, $m ) ) {
1584  $gtidInfos[(int)$m[1]] = (int)$m[2];
1585  // MySQL style: <UUID domain>:<sequence number>
1586  } elseif ( preg_match( '!^(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}):(\d+)$!', $gtid, $m ) ) {
1587  $gtidInfos[$m[1]] = (int)$m[2];
1588  } else {
1589  $gtidInfos = [];
1590  break; // unrecognized GTID
1591  }
1592 
1593  }
1594 
1595  return $gtidInfos;
1596  }
1597 
1603  protected function getBinlogCoordinates() {
1604  $m = [];
1605  if ( preg_match( '!^(.+)\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1606  return [ 'binlog' => $m[1], 'pos' => [ (int)$m[2], (int)$m[3] ] ];
1607  }
1608 
1609  return false;
1610  }
1611 }
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1233
lockTables($read, $write, $method, $lowPriority=true)
indexName($index)
Get the name of an index in a given table.
Definition: Database.php:1943
mysqlFieldType($res, $n)
Get the type of the specified field in a result.
mysqlDataSeek($res, $row)
Move internal result pointer.
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
getServerUptime()
Determines how long the server has been up.
getMasterPos()
Get the position of the master from SHOW MASTER STATUS.
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1435
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the slave to catch up to a given master position.
string[] $gtids
GTID list.
fieldType($res, $n)
mysql_field_type() wrapper
streamStatementEnd(&$sql, &$newLine)
mysqlConnect($realServer)
Open a connection to a MySQL server.
$success
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
tableName($name, $format= 'quoted')
Format a table name ready for use in constructing an SQL query.
Definition: Database.php:1684
array $lagDetectionOptions
Method to detect slave lag.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
__construct($file, $pos, $gtid= '')
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
addIdentifierQuotes($s)
MySQL uses backticks for identifier quoting instead of the sql standard "double quotes".
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
string $lagDetectionMethod
Method to detect slave lag.
wfHostname()
Fetch server name for use in error reporting etc.
resource $mConn
Database connection.
Definition: Database.php:52
unlock($lockName, $method)
FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release...
wfLogDBError($text, array $context=[])
Log for database errors.
$value
isView($name, $prefix=null)
Differentiates between a TABLE and a VIEW.
upsert($table, array $rows, array $uniqueIndexes, array $set, $fname=__METHOD__)
makeList($a, $mode=LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:1518
getMysqlStatus($which="%")
Get status information from SHOW STATUS in an associative array.
Base for all database-specific classes representing information about database fields.
connectInitCharset()
Set the character set information right after connection.
mysqlFetchArray($res)
Fetch a result row as an associative and numeric array.
An object representing a master or slave position in a replicated setup.
mysqlFetchObject($res)
Fetch a result row as an object.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
replace($table, $uniqueIndexes, $rows, $fname=__METHOD__)
doQuery($sql)
The DBMS-dependent part of query()
channelsMatch(DBMasterPos $pos)
restoreErrorHandler()
Definition: Database.php:658
lock($lockName, $method, $timeout=5)
lastErrno()
Get the last error number.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1629
hasReached(DBMasterPos $pos)
close()
Closes a database connection.
Definition: Database.php:698
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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:1814
DBMasterPos class for MySQL/MariaDB.
dropTable($tableName, $fName=__METHOD__)
string[] $allViews
Definition: Database.php:178
listViews($prefix=null, $fname=__METHOD__)
Lists VIEWs in the database.
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:93
tableExists($table, $fname=__METHOD__)
Query whether a given table exists.
Definition: Database.php:1389
Base class for the more common types of database errors.
deleteJoin($delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
$GLOBALS['IP']
const LIST_AND
Definition: Defines.php:194
listTables($prefix=null, $fname=__METHOD__)
List all tables on the database.
setSessionOptions(array $options)
getSlavePos()
Get the position of the master from SHOW SLAVE STATUS.
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 as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1020
$res
Definition: database.txt:21
getHeartbeatData(array $conds)
mysqlError($conn=null)
Returns the text of the error message from previous MySQL operation.
mysqlPing()
Ping a server connection or reconnect if there is no connection.
$cache
Definition: mcc.php:33
int $pos
Binglog file position.
$params
Utility class.
duplicateTableStructure($oldName, $newName, $temporary=false, $fname=__METHOD__)
__construct(array $params)
Additional $params include:
addQuotes($s)
Adds quotes and backslashes.
Definition: Database.php:1958
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
Definition: distributors.txt:9
mysqlNumRows($res)
Get number of rows in result.
const LIST_SET
Definition: Defines.php:195
mysqlSetCharset($charset)
Set the character set of the MySQL link.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
selectDB($db)
Change the current database.
Definition: Database.php:1648
indexInfo($table, $index, $fname=__METHOD__)
Get information about an index into an object Returns false if the index does not exist...
string $file
Binlog file.
mysqlNumFields($res)
Get number of fields in result.
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:35
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
closeConnection()
Closes underlying database connection.
setBigSelects($value=true)
selectField($table, $var, $cond= '', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1048
string null $serverVersion
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:36
wasDeadlock()
Determines if the last failure was due to a deadlock.
$wgAllDBsAreLocalhost
Make all database connections secretly go to localhost.
Database abstraction object for MySQL.
MysqlMasterPos $lastKnownSlavePos
getLag()
Get slave lag.
mysqlFieldName($res, $n)
Get the name of the specified field in a result.
getServer()
Get the server hostname or IP address.
Definition: Database.php:1661
getSearchEngine()
Get search engine class.
estimateRowCount($table, $vars= '*', $conds= '', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output Takes same arguments as Dat...
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:783
wasErrorReissuable()
Determines if the last query error was something that should be dealt with by pinging the connection ...
commit($fname=__METHOD__, $flush= '')
Commits a transaction previously started using begin().
Definition: Database.php:2697
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 as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1020
float $asOfTime
UNIX timestamp.
lockIsFree($lockName, $method)
Check to see if a named lock is available.
$version
Definition: parserTests.php:94
getLBInfo($name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:256
Result wrapper for grabbing data queried by someone else.
getLogContext(array $extras=[])
Create a log context to pass to wfLogDBError or other logging functions.
Definition: Database.php:687
BagOStuff $srvCache
APC cache.
Definition: Database.php:49
mysqlFreeResult($res)
Free result memory.
nativeReplace($table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: Database.php:2111
$wgSQLMode
SQL Mode - default is turning off all modes, including strict, if set.
getLazyMasterHandle()
Definition: Database.php:291
getBindingHandle()
Get the underlying binding handle, mConn.
installErrorHandler()
Definition: Database.php:649
fieldInfo($table, $field)
reportConnectionError($error= 'Unknown error')
Definition: Database.php:739
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2044
mysqlFetchField($res, $n)
Get column information from a result.
bool $useGTIDs
bool Whether to use GTID methods
$wgDBmysql5
Set to true to engage MySQL 4.1/5.0 charset-related features; for now will just cause sending of 'SET...
open($server, $user, $password, $dbName)
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310