MediaWiki  1.29.1
DatabaseMysqlBase.php
Go to the documentation of this file.
1 <?php
23 namespace Wikimedia\Rdbms;
24 
25 use DateTime;
26 use DateTimeZone;
28 use InvalidArgumentException;
29 use Exception;
30 use stdClass;
31 
40 abstract class DatabaseMysqlBase extends Database {
46  protected $lagDetectionOptions = [];
48  protected $useGTIDs = false;
50  protected $sslKeyPath;
52  protected $sslCertPath;
54  protected $sslCAPath;
56  protected $sslCiphers;
58  protected $sqlMode;
60  protected $utf8Mode;
61 
63  private $serverVersion = null;
64 
82  function __construct( array $params ) {
83  $this->lagDetectionMethod = isset( $params['lagDetectionMethod'] )
84  ? $params['lagDetectionMethod']
85  : 'Seconds_Behind_Master';
86  $this->lagDetectionOptions = isset( $params['lagDetectionOptions'] )
87  ? $params['lagDetectionOptions']
88  : [];
89  $this->useGTIDs = !empty( $params['useGTIDs' ] );
90  foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
91  $var = "ssl{$name}";
92  if ( isset( $params[$var] ) ) {
93  $this->$var = $params[$var];
94  }
95  }
96  $this->sqlMode = isset( $params['sqlMode'] ) ? $params['sqlMode'] : '';
97  $this->utf8Mode = !empty( $params['utf8Mode'] );
98 
99  parent::__construct( $params );
100  }
101 
105  public function getType() {
106  return 'mysql';
107  }
108 
117  public function open( $server, $user, $password, $dbName ) {
118  # Close/unset connection handle
119  $this->close();
120 
121  $this->mServer = $server;
122  $this->mUser = $user;
123  $this->mPassword = $password;
124  $this->mDBname = $dbName;
125 
126  $this->installErrorHandler();
127  try {
128  $this->mConn = $this->mysqlConnect( $this->mServer );
129  } catch ( Exception $ex ) {
130  $this->restoreErrorHandler();
131  throw $ex;
132  }
133  $error = $this->restoreErrorHandler();
134 
135  # Always log connection errors
136  if ( !$this->mConn ) {
137  if ( !$error ) {
138  $error = $this->lastError();
139  }
140  $this->connLogger->error(
141  "Error connecting to {db_server}: {error}",
142  $this->getLogContext( [
143  'method' => __METHOD__,
144  'error' => $error,
145  ] )
146  );
147  $this->connLogger->debug( "DB connection error\n" .
148  "Server: $server, User: $user, Password: " .
149  substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
150 
151  $this->reportConnectionError( $error );
152  }
153 
154  if ( $dbName != '' ) {
155  MediaWiki\suppressWarnings();
156  $success = $this->selectDB( $dbName );
157  MediaWiki\restoreWarnings();
158  if ( !$success ) {
159  $this->queryLogger->error(
160  "Error selecting database {db_name} on server {db_server}",
161  $this->getLogContext( [
162  'method' => __METHOD__,
163  ] )
164  );
165  $this->queryLogger->debug(
166  "Error selecting database $dbName on server {$this->mServer}" );
167 
168  $this->reportConnectionError( "Error selecting database $dbName" );
169  }
170  }
171 
172  // Tell the server what we're communicating with
173  if ( !$this->connectInitCharset() ) {
174  $this->reportConnectionError( "Error setting character set" );
175  }
176 
177  // Abstract over any insane MySQL defaults
178  $set = [ 'group_concat_max_len = 262144' ];
179  // Set SQL mode, default is turning them all off, can be overridden or skipped with null
180  if ( is_string( $this->sqlMode ) ) {
181  $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
182  }
183  // Set any custom settings defined by site config
184  // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
185  foreach ( $this->mSessionVars as $var => $val ) {
186  // Escape strings but not numbers to avoid MySQL complaining
187  if ( !is_int( $val ) && !is_float( $val ) ) {
188  $val = $this->addQuotes( $val );
189  }
190  $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
191  }
192 
193  if ( $set ) {
194  // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
195  $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
196  if ( !$success ) {
197  $this->queryLogger->error(
198  'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
199  $this->getLogContext( [
200  'method' => __METHOD__,
201  ] )
202  );
203  $this->reportConnectionError(
204  'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
205  }
206  }
207 
208  $this->mOpened = true;
209 
210  return true;
211  }
212 
217  protected function connectInitCharset() {
218  if ( $this->utf8Mode ) {
219  // Tell the server we're communicating with it in UTF-8.
220  // This may engage various charset conversions.
221  return $this->mysqlSetCharset( 'utf8' );
222  } else {
223  return $this->mysqlSetCharset( 'binary' );
224  }
225  }
226 
234  abstract protected function mysqlConnect( $realServer );
235 
242  abstract protected function mysqlSetCharset( $charset );
243 
248  public function freeResult( $res ) {
249  if ( $res instanceof ResultWrapper ) {
250  $res = $res->result;
251  }
252  MediaWiki\suppressWarnings();
253  $ok = $this->mysqlFreeResult( $res );
254  MediaWiki\restoreWarnings();
255  if ( !$ok ) {
256  throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
257  }
258  }
259 
266  abstract protected function mysqlFreeResult( $res );
267 
273  public function fetchObject( $res ) {
274  if ( $res instanceof ResultWrapper ) {
275  $res = $res->result;
276  }
277  MediaWiki\suppressWarnings();
278  $row = $this->mysqlFetchObject( $res );
279  MediaWiki\restoreWarnings();
280 
281  $errno = $this->lastErrno();
282  // Unfortunately, mysql_fetch_object does not reset the last errno.
283  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
284  // these are the only errors mysql_fetch_object can cause.
285  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
286  if ( $errno == 2000 || $errno == 2013 ) {
287  throw new DBUnexpectedError(
288  $this,
289  'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
290  );
291  }
292 
293  return $row;
294  }
295 
302  abstract protected function mysqlFetchObject( $res );
303 
309  public function fetchRow( $res ) {
310  if ( $res instanceof ResultWrapper ) {
311  $res = $res->result;
312  }
313  MediaWiki\suppressWarnings();
314  $row = $this->mysqlFetchArray( $res );
315  MediaWiki\restoreWarnings();
316 
317  $errno = $this->lastErrno();
318  // Unfortunately, mysql_fetch_array does not reset the last errno.
319  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
320  // these are the only errors mysql_fetch_array can cause.
321  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
322  if ( $errno == 2000 || $errno == 2013 ) {
323  throw new DBUnexpectedError(
324  $this,
325  'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
326  );
327  }
328 
329  return $row;
330  }
331 
338  abstract protected function mysqlFetchArray( $res );
339 
345  function numRows( $res ) {
346  if ( $res instanceof ResultWrapper ) {
347  $res = $res->result;
348  }
349  MediaWiki\suppressWarnings();
350  $n = $this->mysqlNumRows( $res );
351  MediaWiki\restoreWarnings();
352 
353  // Unfortunately, mysql_num_rows does not reset the last errno.
354  // We are not checking for any errors here, since
355  // these are no errors mysql_num_rows can cause.
356  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
357  // See https://phabricator.wikimedia.org/T44430
358  return $n;
359  }
360 
367  abstract protected function mysqlNumRows( $res );
368 
373  public function numFields( $res ) {
374  if ( $res instanceof ResultWrapper ) {
375  $res = $res->result;
376  }
377 
378  return $this->mysqlNumFields( $res );
379  }
380 
387  abstract protected function mysqlNumFields( $res );
388 
394  public function fieldName( $res, $n ) {
395  if ( $res instanceof ResultWrapper ) {
396  $res = $res->result;
397  }
398 
399  return $this->mysqlFieldName( $res, $n );
400  }
401 
409  abstract protected function mysqlFieldName( $res, $n );
410 
417  public function fieldType( $res, $n ) {
418  if ( $res instanceof ResultWrapper ) {
419  $res = $res->result;
420  }
421 
422  return $this->mysqlFieldType( $res, $n );
423  }
424 
432  abstract protected function mysqlFieldType( $res, $n );
433 
439  public function dataSeek( $res, $row ) {
440  if ( $res instanceof ResultWrapper ) {
441  $res = $res->result;
442  }
443 
444  return $this->mysqlDataSeek( $res, $row );
445  }
446 
454  abstract protected function mysqlDataSeek( $res, $row );
455 
459  public function lastError() {
460  if ( $this->mConn ) {
461  # Even if it's non-zero, it can still be invalid
462  MediaWiki\suppressWarnings();
463  $error = $this->mysqlError( $this->mConn );
464  if ( !$error ) {
465  $error = $this->mysqlError();
466  }
467  MediaWiki\restoreWarnings();
468  } else {
469  $error = $this->mysqlError();
470  }
471  if ( $error ) {
472  $error .= ' (' . $this->mServer . ')';
473  }
474 
475  return $error;
476  }
477 
484  abstract protected function mysqlError( $conn = null );
485 
493  public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
494  return $this->nativeReplace( $table, $rows, $fname );
495  }
496 
509  public function estimateRowCount( $table, $vars = '*', $conds = '',
510  $fname = __METHOD__, $options = []
511  ) {
512  $options['EXPLAIN'] = true;
513  $res = $this->select( $table, $vars, $conds, $fname, $options );
514  if ( $res === false ) {
515  return false;
516  }
517  if ( !$this->numRows( $res ) ) {
518  return 0;
519  }
520 
521  $rows = 1;
522  foreach ( $res as $plan ) {
523  $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
524  }
525 
526  return (int)$rows;
527  }
528 
529  public function tableExists( $table, $fname = __METHOD__ ) {
530  $table = $this->tableName( $table, 'raw' );
531  if ( isset( $this->mSessionTempTables[$table] ) ) {
532  return true; // already known to exist and won't show in SHOW TABLES anyway
533  }
534 
535  // We can't use buildLike() here, because it specifies an escape character
536  // other than the backslash, which is the only one supported by SHOW TABLES
537  $encLike = $this->escapeLikeInternal( $table, '\\' );
538 
539  return $this->query( "SHOW TABLES LIKE '$encLike'", $fname )->numRows() > 0;
540  }
541 
547  public function fieldInfo( $table, $field ) {
548  $table = $this->tableName( $table );
549  $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
550  if ( !$res ) {
551  return false;
552  }
553  $n = $this->mysqlNumFields( $res->result );
554  for ( $i = 0; $i < $n; $i++ ) {
555  $meta = $this->mysqlFetchField( $res->result, $i );
556  if ( $field == $meta->name ) {
557  return new MySQLField( $meta );
558  }
559  }
560 
561  return false;
562  }
563 
571  abstract protected function mysqlFetchField( $res, $n );
572 
582  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
583  # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
584  # SHOW INDEX should work for 3.x and up:
585  # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
586  $table = $this->tableName( $table );
587  $index = $this->indexName( $index );
588 
589  $sql = 'SHOW INDEX FROM ' . $table;
590  $res = $this->query( $sql, $fname );
591 
592  if ( !$res ) {
593  return null;
594  }
595 
596  $result = [];
597 
598  foreach ( $res as $row ) {
599  if ( $row->Key_name == $index ) {
600  $result[] = $row;
601  }
602  }
603 
604  return empty( $result ) ? false : $result;
605  }
606 
611  public function strencode( $s ) {
612  return $this->mysqlRealEscapeString( $s );
613  }
614 
619  abstract protected function mysqlRealEscapeString( $s );
620 
621  public function addQuotes( $s ) {
622  if ( is_bool( $s ) ) {
623  // Parent would transform to int, which does not play nice with MySQL type juggling.
624  // When searching for an int in a string column, the strings are cast to int, which
625  // means false would match any string not starting with a number.
626  $s = (string)(int)$s;
627  }
628  return parent::addQuotes( $s );
629  }
630 
637  public function addIdentifierQuotes( $s ) {
638  // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
639  // Remove NUL bytes and escape backticks by doubling
640  return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
641  }
642 
647  public function isQuotedIdentifier( $name ) {
648  return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
649  }
650 
651  public function getLag() {
652  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
653  return $this->getLagFromPtHeartbeat();
654  } else {
655  return $this->getLagFromSlaveStatus();
656  }
657  }
658 
662  protected function getLagDetectionMethod() {
664  }
665 
669  protected function getLagFromSlaveStatus() {
670  $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
671  $row = $res ? $res->fetchObject() : false;
672  if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
673  return intval( $row->Seconds_Behind_Master );
674  }
675 
676  return false;
677  }
678 
682  protected function getLagFromPtHeartbeat() {
684 
685  if ( isset( $options['conds'] ) ) {
686  // Best method for multi-DC setups: use logical channel names
687  $data = $this->getHeartbeatData( $options['conds'] );
688  } else {
689  // Standard method: use master server ID (works with stock pt-heartbeat)
690  $masterInfo = $this->getMasterServerInfo();
691  if ( !$masterInfo ) {
692  $this->queryLogger->error(
693  "Unable to query master of {db_server} for server ID",
694  $this->getLogContext( [
695  'method' => __METHOD__
696  ] )
697  );
698 
699  return false; // could not get master server ID
700  }
701 
702  $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
703  $data = $this->getHeartbeatData( $conds );
704  }
705 
706  list( $time, $nowUnix ) = $data;
707  if ( $time !== null ) {
708  // @time is in ISO format like "2015-09-25T16:48:10.000510"
709  $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
710  $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
711 
712  return max( $nowUnix - $timeUnix, 0.0 );
713  }
714 
715  $this->queryLogger->error(
716  "Unable to find pt-heartbeat row for {db_server}",
717  $this->getLogContext( [
718  'method' => __METHOD__
719  ] )
720  );
721 
722  return false;
723  }
724 
725  protected function getMasterServerInfo() {
727  $key = $cache->makeGlobalKey(
728  'mysql',
729  'master-info',
730  // Using one key for all cluster replica DBs is preferable
731  $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
732  );
733 
734  return $cache->getWithSetCallback(
735  $key,
736  $cache::TTL_INDEFINITE,
737  function () use ( $cache, $key ) {
738  // Get and leave a lock key in place for a short period
739  if ( !$cache->lock( $key, 0, 10 ) ) {
740  return false; // avoid master connection spike slams
741  }
742 
743  $conn = $this->getLazyMasterHandle();
744  if ( !$conn ) {
745  return false; // something is misconfigured
746  }
747 
748  // Connect to and query the master; catch errors to avoid outages
749  try {
750  $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
751  $row = $res ? $res->fetchObject() : false;
752  $id = $row ? (int)$row->id : 0;
753  } catch ( DBError $e ) {
754  $id = 0;
755  }
756 
757  // Cache the ID if it was retrieved
758  return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
759  }
760  );
761  }
762 
768  protected function getHeartbeatData( array $conds ) {
769  // Do not bother starting implicit transactions here
770  $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
771  try {
772  $whereSQL = $this->makeList( $conds, self::LIST_AND );
773  // Use ORDER BY for channel based queries since that field might not be UNIQUE.
774  // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
775  // percision field is not supported in MySQL <= 5.5.
776  $res = $this->query(
777  "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
778  );
779  $row = $res ? $res->fetchObject() : false;
780  } finally {
781  $this->restoreFlags();
782  }
783 
784  return [ $row ? $row->ts : null, microtime( true ) ];
785  }
786 
787  protected function getApproximateLagStatus() {
788  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
789  // Disable caching since this is fast enough and we don't wan't
790  // to be *too* pessimistic by having both the cache TTL and the
791  // pt-heartbeat interval count as lag in getSessionLagStatus()
792  return parent::getApproximateLagStatus();
793  }
794 
795  $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
796  $approxLag = $this->srvCache->get( $key );
797  if ( !$approxLag ) {
798  $approxLag = parent::getApproximateLagStatus();
799  $this->srvCache->set( $key, $approxLag, 1 );
800  }
801 
802  return $approxLag;
803  }
804 
805  public function masterPosWait( DBMasterPos $pos, $timeout ) {
806  if ( !( $pos instanceof MySQLMasterPos ) ) {
807  throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
808  }
809 
810  if ( $this->getLBInfo( 'is static' ) === true ) {
811  return 0; // this is a copy of a read-only dataset with no master DB
812  } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
813  return 0; // already reached this point for sure
814  }
815 
816  // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
817  if ( $this->useGTIDs && $pos->gtids ) {
818  // Wait on the GTID set (MariaDB only)
819  $gtidArg = $this->addQuotes( implode( ',', $pos->gtids ) );
820  $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
821  } else {
822  // Wait on the binlog coordinates
823  $encFile = $this->addQuotes( $pos->file );
824  $encPos = intval( $pos->pos );
825  $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
826  }
827 
828  $row = $res ? $this->fetchRow( $res ) : false;
829  if ( !$row ) {
830  throw new DBExpectedError( $this,
831  "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
832  }
833 
834  // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
835  $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
836  if ( $status === null ) {
837  // T126436: jobs programmed to wait on master positions might be referencing binlogs
838  // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
839  // to detect this and treat the replica DB as having reached the position; a proper master
840  // switchover already requires that the new master be caught up before the switch.
841  $replicationPos = $this->getReplicaPos();
842  if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
843  $this->lastKnownReplicaPos = $replicationPos;
844  $status = 0;
845  }
846  } elseif ( $status >= 0 ) {
847  // Remember that this position was reached to save queries next time
848  $this->lastKnownReplicaPos = $pos;
849  }
850 
851  return $status;
852  }
853 
859  public function getReplicaPos() {
860  $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
861  $row = $this->fetchObject( $res );
862 
863  if ( $row ) {
864  $pos = isset( $row->Exec_master_log_pos )
865  ? $row->Exec_master_log_pos
866  : $row->Exec_Master_Log_Pos;
867  // Also fetch the last-applied GTID set (MariaDB)
868  if ( $this->useGTIDs ) {
869  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__ );
870  $gtidRow = $this->fetchObject( $res );
871  $gtidSet = $gtidRow ? $gtidRow->Value : '';
872  } else {
873  $gtidSet = '';
874  }
875 
876  return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos, $gtidSet );
877  } else {
878  return false;
879  }
880  }
881 
887  public function getMasterPos() {
888  $res = $this->query( 'SHOW MASTER STATUS', __METHOD__ );
889  $row = $this->fetchObject( $res );
890 
891  if ( $row ) {
892  // Also fetch the last-written GTID set (MariaDB)
893  if ( $this->useGTIDs ) {
894  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__ );
895  $gtidRow = $this->fetchObject( $res );
896  $gtidSet = $gtidRow ? $gtidRow->Value : '';
897  } else {
898  $gtidSet = '';
899  }
900 
901  return new MySQLMasterPos( $row->File, $row->Position, $gtidSet );
902  } else {
903  return false;
904  }
905  }
906 
907  public function serverIsReadOnly() {
908  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__ );
909  $row = $this->fetchObject( $res );
910 
911  return $row ? ( strtolower( $row->Value ) === 'on' ) : false;
912  }
913 
918  function useIndexClause( $index ) {
919  return "FORCE INDEX (" . $this->indexName( $index ) . ")";
920  }
921 
926  function ignoreIndexClause( $index ) {
927  return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
928  }
929 
933  function lowPriorityOption() {
934  return 'LOW_PRIORITY';
935  }
936 
940  public function getSoftwareLink() {
941  // MariaDB includes its name in its version string; this is how MariaDB's version of
942  // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
943  // in libmysql/libmysql.c).
944  $version = $this->getServerVersion();
945  if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
946  return '[{{int:version-db-mariadb-url}} MariaDB]';
947  }
948 
949  // Percona Server's version suffix is not very distinctive, and @@version_comment
950  // doesn't give the necessary info for source builds, so assume the server is MySQL.
951  // (Even Percona's version of mysql doesn't try to make the distinction.)
952  return '[{{int:version-db-mysql-url}} MySQL]';
953  }
954 
958  public function getServerVersion() {
959  // Not using mysql_get_server_info() or similar for consistency: in the handshake,
960  // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
961  // it off (see RPL_VERSION_HACK in include/mysql_com.h).
962  if ( $this->serverVersion === null ) {
963  $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
964  }
965  return $this->serverVersion;
966  }
967 
971  public function setSessionOptions( array $options ) {
972  if ( isset( $options['connTimeout'] ) ) {
973  $timeout = (int)$options['connTimeout'];
974  $this->query( "SET net_read_timeout=$timeout" );
975  $this->query( "SET net_write_timeout=$timeout" );
976  }
977  }
978 
984  public function streamStatementEnd( &$sql, &$newLine ) {
985  if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
986  preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
987  $this->delimiter = $m[1];
988  $newLine = '';
989  }
990 
991  return parent::streamStatementEnd( $sql, $newLine );
992  }
993 
1002  public function lockIsFree( $lockName, $method ) {
1003  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1004  $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1005  $row = $this->fetchObject( $result );
1006 
1007  return ( $row->lockstatus == 1 );
1008  }
1009 
1016  public function lock( $lockName, $method, $timeout = 5 ) {
1017  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1018  $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1019  $row = $this->fetchObject( $result );
1020 
1021  if ( $row->lockstatus == 1 ) {
1022  parent::lock( $lockName, $method, $timeout ); // record
1023  return true;
1024  }
1025 
1026  $this->queryLogger->warning( __METHOD__ . " failed to acquire lock '$lockName'\n" );
1027 
1028  return false;
1029  }
1030 
1038  public function unlock( $lockName, $method ) {
1039  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1040  $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1041  $row = $this->fetchObject( $result );
1042 
1043  if ( $row->lockstatus == 1 ) {
1044  parent::unlock( $lockName, $method ); // record
1045  return true;
1046  }
1047 
1048  $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1049 
1050  return false;
1051  }
1052 
1053  private function makeLockName( $lockName ) {
1054  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1055  // Newer version enforce a 64 char length limit.
1056  return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1057  }
1058 
1059  public function namedLocksEnqueue() {
1060  return true;
1061  }
1062 
1064  return false; // tied to TCP connection
1065  }
1066 
1067  protected function doLockTables( array $read, array $write, $method ) {
1068  $items = [];
1069  foreach ( $write as $table ) {
1070  $items[] = $this->tableName( $table ) . ' WRITE';
1071  }
1072  foreach ( $read as $table ) {
1073  $items[] = $this->tableName( $table ) . ' READ';
1074  }
1075 
1076  $sql = "LOCK TABLES " . implode( ',', $items );
1077  $this->query( $sql, $method );
1078 
1079  return true;
1080  }
1081 
1082  protected function doUnlockTables( $method ) {
1083  $this->query( "UNLOCK TABLES", $method );
1084 
1085  return true;
1086  }
1087 
1091  public function setBigSelects( $value = true ) {
1092  if ( $value === 'default' ) {
1093  if ( $this->mDefaultBigSelects === null ) {
1094  # Function hasn't been called before so it must already be set to the default
1095  return;
1096  } else {
1098  }
1099  } elseif ( $this->mDefaultBigSelects === null ) {
1100  $this->mDefaultBigSelects =
1101  (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1102  }
1103  $encValue = $value ? '1' : '0';
1104  $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1105  }
1106 
1118  public function deleteJoin(
1119  $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1120  ) {
1121  if ( !$conds ) {
1122  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1123  }
1124 
1125  $delTable = $this->tableName( $delTable );
1126  $joinTable = $this->tableName( $joinTable );
1127  $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1128 
1129  if ( $conds != '*' ) {
1130  $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1131  }
1132 
1133  return $this->query( $sql, $fname );
1134  }
1135 
1144  public function upsert( $table, array $rows, array $uniqueIndexes,
1145  array $set, $fname = __METHOD__
1146  ) {
1147  if ( !count( $rows ) ) {
1148  return true; // nothing to do
1149  }
1150 
1151  if ( !is_array( reset( $rows ) ) ) {
1152  $rows = [ $rows ];
1153  }
1154 
1155  $table = $this->tableName( $table );
1156  $columns = array_keys( $rows[0] );
1157 
1158  $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1159  $rowTuples = [];
1160  foreach ( $rows as $row ) {
1161  $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1162  }
1163  $sql .= implode( ',', $rowTuples );
1164  $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
1165 
1166  return (bool)$this->query( $sql, $fname );
1167  }
1168 
1174  public function getServerUptime() {
1175  $vars = $this->getMysqlStatus( 'Uptime' );
1176 
1177  return (int)$vars['Uptime'];
1178  }
1179 
1185  public function wasDeadlock() {
1186  return $this->lastErrno() == 1213;
1187  }
1188 
1194  public function wasLockTimeout() {
1195  return $this->lastErrno() == 1205;
1196  }
1197 
1198  public function wasErrorReissuable() {
1199  return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1200  }
1201 
1207  public function wasReadOnlyError() {
1208  return $this->lastErrno() == 1223 ||
1209  ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1210  }
1211 
1212  public function wasConnectionError( $errno ) {
1213  return $errno == 2013 || $errno == 2006;
1214  }
1215 
1223  public function duplicateTableStructure(
1224  $oldName, $newName, $temporary = false, $fname = __METHOD__
1225  ) {
1226  $tmp = $temporary ? 'TEMPORARY ' : '';
1227  $newName = $this->addIdentifierQuotes( $newName );
1228  $oldName = $this->addIdentifierQuotes( $oldName );
1229  $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1230 
1231  return $this->query( $query, $fname );
1232  }
1233 
1241  public function listTables( $prefix = null, $fname = __METHOD__ ) {
1242  $result = $this->query( "SHOW TABLES", $fname );
1243 
1244  $endArray = [];
1245 
1246  foreach ( $result as $table ) {
1247  $vars = get_object_vars( $table );
1248  $table = array_pop( $vars );
1249 
1250  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1251  $endArray[] = $table;
1252  }
1253  }
1254 
1255  return $endArray;
1256  }
1257 
1263  public function dropTable( $tableName, $fName = __METHOD__ ) {
1264  if ( !$this->tableExists( $tableName, $fName ) ) {
1265  return false;
1266  }
1267 
1268  return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1269  }
1270 
1277  private function getMysqlStatus( $which = "%" ) {
1278  $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1279  $status = [];
1280 
1281  foreach ( $res as $row ) {
1282  $status[$row->Variable_name] = $row->Value;
1283  }
1284 
1285  return $status;
1286  }
1287 
1297  public function listViews( $prefix = null, $fname = __METHOD__ ) {
1298  // The name of the column containing the name of the VIEW
1299  $propertyName = 'Tables_in_' . $this->mDBname;
1300 
1301  // Query for the VIEWS
1302  $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1303  $allViews = [];
1304  foreach ( $res as $row ) {
1305  array_push( $allViews, $row->$propertyName );
1306  }
1307 
1308  if ( is_null( $prefix ) || $prefix === '' ) {
1309  return $allViews;
1310  }
1311 
1312  $filteredViews = [];
1313  foreach ( $allViews as $viewName ) {
1314  // Does the name of this VIEW start with the table-prefix?
1315  if ( strpos( $viewName, $prefix ) === 0 ) {
1316  array_push( $filteredViews, $viewName );
1317  }
1318  }
1319 
1320  return $filteredViews;
1321  }
1322 
1331  public function isView( $name, $prefix = null ) {
1332  return in_array( $name, $this->listViews( $prefix ) );
1333  }
1334 
1341  protected function indexName( $index ) {
1356  $renamed = [
1357  'ar_usertext_timestamp' => 'usertext_timestamp',
1358  'un_user_id' => 'user_id',
1359  'un_user_ip' => 'user_ip',
1360  ];
1361 
1362  if ( isset( $renamed[$index] ) ) {
1363  return $renamed[$index];
1364  } else {
1365  return $index;
1366  }
1367  }
1368 }
1369 
1370 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );
Wikimedia\Rdbms\DatabaseMysqlBase\doLockTables
doLockTables(array $read, array $write, $method)
Definition: DatabaseMysqlBase.php:1067
Wikimedia\Rdbms\DatabaseMysqlBase\addIdentifierQuotes
addIdentifierQuotes( $s)
MySQL uses backticks for identifier quoting instead of the sql standard "double quotes".
Definition: DatabaseMysqlBase.php:637
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:45
Wikimedia\Rdbms\DatabaseMysqlBase\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
Definition: DatabaseMysqlBase.php:805
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
Wikimedia\Rdbms\DatabaseMysqlBase\$sslKeyPath
string null $sslKeyPath
Definition: DatabaseMysqlBase.php:50
Wikimedia\Rdbms\DatabaseMysqlBase\getLagDetectionMethod
getLagDetectionMethod()
Definition: DatabaseMysqlBase.php:662
Wikimedia\Rdbms\DatabaseMysqlBase\indexInfo
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object Returns false if the index does not exist.
Definition: DatabaseMysqlBase.php:582
Wikimedia\Rdbms\DatabaseMysqlBase\setSessionOptions
setSessionOptions(array $options)
Definition: DatabaseMysqlBase.php:971
Wikimedia\Rdbms\DatabaseMysqlBase\getServerUptime
getServerUptime()
Determines how long the server has been up.
Definition: DatabaseMysqlBase.php:1174
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlRealEscapeString
mysqlRealEscapeString( $s)
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCAPath
string null $sslCAPath
Definition: DatabaseMysqlBase.php:54
captcha-old.count
count
Definition: captcha-old.py:225
Wikimedia\Rdbms\DatabaseMysqlBase\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server.
Definition: DatabaseMysqlBase.php:787
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFieldName
mysqlFieldName( $res, $n)
Get the name of the specified field in a result.
Wikimedia\Rdbms\DatabaseMysqlBase\numRows
numRows( $res)
Definition: DatabaseMysqlBase.php:345
Wikimedia\Rdbms\DatabaseMysqlBase\lowPriorityOption
lowPriorityOption()
Definition: DatabaseMysqlBase.php:933
Wikimedia\Rdbms\Database\nativeReplace
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
Definition: Database.php:2152
$result
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:Array with elements of the form "language:title" in the order that they will be output. & $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:1954
Wikimedia\Rdbms\DatabaseMysqlBase\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
Definition: DatabaseMysqlBase.php:1194
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
Wikimedia\Rdbms\DatabaseMysqlBase\upsert
upsert( $table, array $rows, array $uniqueIndexes, array $set, $fname=__METHOD__)
Definition: DatabaseMysqlBase.php:1144
Wikimedia\Rdbms\Database\selectField
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1082
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCertPath
string null $sslCertPath
Definition: DatabaseMysqlBase.php:52
$user
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 account $user
Definition: hooks.txt:246
Wikimedia\Rdbms\DatabaseMysqlBase\$useGTIDs
bool $useGTIDs
bool Whether to use GTID methods
Definition: DatabaseMysqlBase.php:48
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlNumRows
mysqlNumRows( $res)
Get number of rows in result.
Wikimedia\Rdbms\DatabaseMysqlBase\getHeartbeatData
getHeartbeatData(array $conds)
Definition: DatabaseMysqlBase.php:768
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
$fname
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition: Setup.php:36
Wikimedia\Rdbms\DBMasterPos
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:10
$params
$params
Definition: styleTest.css.php:40
$s
$s
Definition: mergeMessageFileList.php:188
Wikimedia\Rdbms\DatabaseMysqlBase\ignoreIndexClause
ignoreIndexClause( $index)
Definition: DatabaseMysqlBase.php:926
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:24
$success
$success
Definition: NoLocalSettings.php:44
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFreeResult
mysqlFreeResult( $res)
Free result memory.
Wikimedia\Rdbms\DatabaseMysqlBase\fieldInfo
fieldInfo( $table, $field)
Definition: DatabaseMysqlBase.php:547
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
Wikimedia\Rdbms\DatabaseMysqlBase\setBigSelects
setBigSelects( $value=true)
Definition: DatabaseMysqlBase.php:1091
DBO_TRX
const DBO_TRX
Definition: defines.php:12
Wikimedia\Rdbms\DatabaseMysqlBase\__construct
__construct(array $params)
Additional $params include:
Definition: DatabaseMysqlBase.php:82
Wikimedia\Rdbms\DatabaseMysqlBase\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.
Definition: DatabaseMysqlBase.php:1185
php
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
LIST_AND
const LIST_AND
Definition: Defines.php:41
Wikimedia\Rdbms\DatabaseMysqlBase\connectInitCharset
connectInitCharset()
Set the character set information right after connection.
Definition: DatabaseMysqlBase.php:217
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlNumFields
mysqlNumFields( $res)
Get number of fields in result.
Wikimedia\Rdbms\Database\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Definition: Database.php:609
Wikimedia\Rdbms\Database\doQuery
doQuery( $sql)
The DBMS-dependent part of query()
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFetchObject
mysqlFetchObject( $res)
Fetch a result row as an object.
$query
null for the 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:1572
Wikimedia\Rdbms\DatabaseMysqlBase\doUnlockTables
doUnlockTables( $method)
Definition: DatabaseMysqlBase.php:1082
Wikimedia\Rdbms\DatabaseMysqlBase\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Definition: DatabaseMysqlBase.php:1223
Wikimedia\Rdbms\DatabaseMysqlBase\fieldName
fieldName( $res, $n)
Definition: DatabaseMysqlBase.php:394
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Definition: Database.php:2022
Wikimedia\Rdbms\DatabaseMysqlBase\getLagFromPtHeartbeat
getLagFromPtHeartbeat()
Definition: DatabaseMysqlBase.php:682
LIST_SET
const LIST_SET
Definition: Defines.php:42
Wikimedia\Rdbms\DatabaseMysqlBase\getSoftwareLink
getSoftwareLink()
Definition: DatabaseMysqlBase.php:940
Wikimedia\Rdbms\MySQLMasterPos
DBMasterPos class for MySQL/MariaDB.
Definition: MySQLMasterPos.php:15
Wikimedia\Rdbms\DatabaseMysqlBase\numFields
numFields( $res)
Definition: DatabaseMysqlBase.php:373
Wikimedia\Rdbms\DatabaseMysqlBase\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Definition: DatabaseMysqlBase.php:1241
Wikimedia\Rdbms\DatabaseMysqlBase\lastError
lastError()
Definition: DatabaseMysqlBase.php:459
Wikimedia\Rdbms\DatabaseMysqlBase\getType
getType()
Definition: DatabaseMysqlBase.php:105
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlSetCharset
mysqlSetCharset( $charset)
Set the character set of the MySQL link.
MediaWiki
This document describes the state of Postgres support in MediaWiki
Definition: postgres.txt:4
Wikimedia\Rdbms\Database\selectDB
selectDB( $db)
Change the current database.
Definition: Database.php:1693
Wikimedia\Rdbms\DatabaseMysqlBase\getLag
getLag()
Get replica DB lag.
Definition: DatabaseMysqlBase.php:651
Wikimedia\Rdbms\Database\reportConnectionError
reportConnectionError( $error='Unknown error')
Definition: Database.php:762
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1769
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2179
Wikimedia\Rdbms\DatabaseMysqlBase\fieldType
fieldType( $res, $n)
mysql_field_type() wrapper
Definition: DatabaseMysqlBase.php:417
Wikimedia\Rdbms\DatabaseMysqlBase\fetchObject
fetchObject( $res)
Definition: DatabaseMysqlBase.php:273
Wikimedia\Rdbms\Database\restoreFlags
restoreFlags( $state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
Definition: Database.php:616
Wikimedia\Rdbms\MySQLField
Definition: MySQLField.php:5
Wikimedia\Rdbms\DatabaseMysqlBase\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Definition: DatabaseMysqlBase.php:984
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:177
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:490
list
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
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFieldType
mysqlFieldType( $res, $n)
Get the type of the specified field in a result.
Wikimedia\Rdbms\DatabaseMysqlBase\dataSeek
dataSeek( $res, $row)
Definition: DatabaseMysqlBase.php:439
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Definition: Database.php:667
Wikimedia\Rdbms\DatabaseMysqlBase\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: DatabaseMysqlBase.php:1341
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Definition: Database.php:676
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFetchField
mysqlFetchField( $res, $n)
Get column information from a result.
Wikimedia\Rdbms\DatabaseMysqlBase\unlock
unlock( $lockName, $method)
FROM MYSQL DOCS: https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_releas...
Definition: DatabaseMysqlBase.php:1038
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
$value
$value
Definition: styleTest.css.php:45
Wikimedia\Rdbms\DatabaseMysqlBase\wasReadOnlyError
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
Definition: DatabaseMysqlBase.php:1207
Wikimedia\Rdbms\Database\$mDBname
string $mDBname
Definition: Database.php:74
Wikimedia\Rdbms\Database\getLogContext
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:715
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFetchArray
mysqlFetchArray( $res)
Fetch a result row as an associative and numeric array.
Wikimedia\Rdbms\DatabaseMysqlBase\freeResult
freeResult( $res)
Definition: DatabaseMysqlBase.php:248
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlDataSeek
mysqlDataSeek( $res, $row)
Move internal result pointer.
Wikimedia\Rdbms\DatabaseMysqlBase\open
open( $server, $user, $password, $dbName)
Definition: DatabaseMysqlBase.php:117
Wikimedia\Rdbms\DatabaseMysqlBase\getMasterPos
getMasterPos()
Get the position of the master from SHOW MASTER STATUS.
Definition: DatabaseMysqlBase.php:887
Wikimedia\Rdbms\Database\tableName
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Definition: Database.php:1710
Wikimedia\Rdbms\DatabaseMysqlBase\getReplicaPos
getReplicaPos()
Get the position of the master from SHOW SLAVE STATUS.
Definition: DatabaseMysqlBase.php:859
Wikimedia\Rdbms\DatabaseMysqlBase\$serverVersion
string null $serverVersion
Definition: DatabaseMysqlBase.php:63
Wikimedia\Rdbms\DatabaseMysqlBase\getLagFromSlaveStatus
getLagFromSlaveStatus()
Definition: DatabaseMysqlBase.php:669
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCiphers
string[] null $sslCiphers
Definition: DatabaseMysqlBase.php:56
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:850
Wikimedia\Rdbms\DatabaseMysqlBase\$utf8Mode
bool $utf8Mode
Use experimental UTF-8 transmission encoding.
Definition: DatabaseMysqlBase.php:60
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:1706
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
Wikimedia\Rdbms\Database\makeList
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:1562
Wikimedia\Rdbms\DatabaseMysqlBase\serverIsReadOnly
serverIsReadOnly()
Definition: DatabaseMysqlBase.php:907
Wikimedia\Rdbms\Database\getLazyMasterHandle
getLazyMasterHandle()
Definition: Database.php:519
Wikimedia\Rdbms\DatabaseMysqlBase\$sqlMode
string $sqlMode
sql_mode value to send on connection
Definition: DatabaseMysqlBase.php:58
Wikimedia\Rdbms\Database\close
close()
Closes a database connection.
Definition: Database.php:726
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\DatabaseMysqlBase\makeLockName
makeLockName( $lockName)
Definition: DatabaseMysqlBase.php:1053
$cache
$cache
Definition: mcc.php:33
Wikimedia\Rdbms\Database\$srvCache
BagOStuff $srvCache
APC cache.
Definition: Database.php:83
Wikimedia\Rdbms\DatabaseMysqlBase\strencode
strencode( $s)
Definition: DatabaseMysqlBase.php:611
Wikimedia\Rdbms\DBExpectedError
Base class for the more common types of database errors.
Definition: DBExpectedError.php:35
Wikimedia\Rdbms\DatabaseMysqlBase\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
Definition: DatabaseMysqlBase.php:1118
Wikimedia\Rdbms\DatabaseMysqlBase\estimateRowCount
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output Takes same arguments as Dat...
Definition: DatabaseMysqlBase.php:509
Wikimedia\Rdbms\DatabaseMysqlBase\useIndexClause
useIndexClause( $index)
Definition: DatabaseMysqlBase.php:918
Wikimedia\Rdbms\Database\$mDefaultBigSelects
bool null $mDefaultBigSelects
Definition: Database.php:116
as
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
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlConnect
mysqlConnect( $realServer)
Open a connection to a MySQL server.
Wikimedia\Rdbms\DatabaseMysqlBase\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: DatabaseMysqlBase.php:1063
Wikimedia\Rdbms\DatabaseMysqlBase\listViews
listViews( $prefix=null, $fname=__METHOD__)
Lists VIEWs in the database.
Definition: DatabaseMysqlBase.php:1297
Wikimedia\Rdbms\DatabaseMysqlBase\wasErrorReissuable
wasErrorReissuable()
Determines if the last query error was due to a dropped connection and should be dealt with by pingin...
Definition: DatabaseMysqlBase.php:1198
Wikimedia\Rdbms\DatabaseMysqlBase\replace
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
Definition: DatabaseMysqlBase.php:493
Wikimedia\Rdbms\DatabaseMysqlBase\$lastKnownReplicaPos
MysqlMasterPos $lastKnownReplicaPos
Definition: DatabaseMysqlBase.php:42
Wikimedia\Rdbms\DatabaseMysqlBase\isView
isView( $name, $prefix=null)
Differentiates between a TABLE and a VIEW.
Definition: DatabaseMysqlBase.php:1331
Wikimedia\Rdbms\Database\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1265
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
Wikimedia\Rdbms\DatabaseMysqlBase\$lagDetectionOptions
array $lagDetectionOptions
Method to detect replica DB lag.
Definition: DatabaseMysqlBase.php:46
Wikimedia\Rdbms\DatabaseMysqlBase\lock
lock( $lockName, $method, $timeout=5)
Definition: DatabaseMysqlBase.php:1016
Wikimedia\Rdbms\DatabaseMysqlBase\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: DatabaseMysqlBase.php:1212
Wikimedia\Rdbms\DatabaseMysqlBase\fetchRow
fetchRow( $res)
Definition: DatabaseMysqlBase.php:309
Wikimedia\Rdbms\DatabaseMysqlBase\getMysqlStatus
getMysqlStatus( $which="%")
Get status information from SHOW STATUS in an associative array.
Definition: DatabaseMysqlBase.php:1277
Wikimedia\Rdbms\DatabaseMysqlBase\getServerVersion
getServerVersion()
Definition: DatabaseMysqlBase.php:958
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup 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:1049
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlError
mysqlError( $conn=null)
Returns the text of the error message from previous MySQL operation.
Wikimedia\Rdbms\DatabaseMysqlBase\getMasterServerInfo
getMasterServerInfo()
Definition: DatabaseMysqlBase.php:725
array
the array() calling protocol came about after MediaWiki 1.4rc1.
Wikimedia\Rdbms\DatabaseMysqlBase\addQuotes
addQuotes( $s)
Adds quotes and backslashes.
Definition: DatabaseMysqlBase.php:621
Wikimedia\Rdbms\DatabaseMysqlBase
Database abstraction object for MySQL.
Definition: DatabaseMysqlBase.php:40
Wikimedia\Rdbms\DatabaseMysqlBase\isQuotedIdentifier
isQuotedIdentifier( $name)
Definition: DatabaseMysqlBase.php:647
Wikimedia\Rdbms\DatabaseMysqlBase\namedLocksEnqueue
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
Definition: DatabaseMysqlBase.php:1059
Wikimedia\Rdbms\DatabaseMysqlBase\tableExists
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
Definition: DatabaseMysqlBase.php:529
Wikimedia\Rdbms\DatabaseMysqlBase\$lagDetectionMethod
string $lagDetectionMethod
Method to detect replica DB lag.
Definition: DatabaseMysqlBase.php:44
Wikimedia\Rdbms\DatabaseMysqlBase\lockIsFree
lockIsFree( $lockName, $method)
Check to see if a named lock is available.
Definition: DatabaseMysqlBase.php:1002
Wikimedia\Rdbms\DatabaseMysqlBase\dropTable
dropTable( $tableName, $fName=__METHOD__)
Definition: DatabaseMysqlBase.php:1263