MediaWiki  master
DatabaseMysqlBase.php
Go to the documentation of this file.
1 <?php
23 namespace Wikimedia\Rdbms;
24 
25 use DateTime;
26 use DateTimeZone;
27 use InvalidArgumentException;
28 use RuntimeException;
29 use stdClass;
30 use Wikimedia\AtEase\AtEase;
31 
40 abstract class DatabaseMysqlBase extends Database {
46  protected $lagDetectionOptions = [];
48  protected $useGTIDs = false;
50  protected $sslKeyPath;
52  protected $sslCertPath;
54  protected $sslCAFile;
56  protected $sslCAPath;
58  protected $sslCiphers;
60  protected $sqlMode;
62  protected $utf8Mode;
64  protected $defaultBigSelects = null;
65 
67  private $insertSelectIsSafe = null;
69  private $replicationInfoRow = null;
70 
71  // Cache getServerId() for 24 hours
72  private const SERVER_ID_CACHE_TTL = 86400;
73 
75  private const LAG_STALE_WARN_THRESHOLD = 0.100;
76 
96  public function __construct( array $params ) {
97  $this->lagDetectionMethod = $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master';
98  $this->lagDetectionOptions = $params['lagDetectionOptions'] ?? [];
99  $this->useGTIDs = !empty( $params['useGTIDs' ] );
100  foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
101  $var = "ssl{$name}";
102  if ( isset( $params[$var] ) ) {
103  $this->$var = $params[$var];
104  }
105  }
106  $this->sqlMode = $params['sqlMode'] ?? null;
107  $this->utf8Mode = !empty( $params['utf8Mode'] );
108  $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] )
109  ? (bool)$params['insertSelectIsSafe'] : null;
110 
111  parent::__construct( $params );
112  }
113 
117  public function getType() {
118  return 'mysql';
119  }
120 
121  protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
122  $this->close();
123 
124  if ( $schema !== null ) {
125  throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
126  }
127 
128  $this->server = $server;
129  $this->user = $user;
130  $this->password = $password;
131 
132  $this->installErrorHandler();
133  try {
134  $this->conn = $this->mysqlConnect( $this->server, $dbName );
135  } catch ( RuntimeException $e ) {
136  $this->restoreErrorHandler();
137  throw $this->newExceptionAfterConnectError( $e->getMessage() );
138  }
139  $error = $this->restoreErrorHandler();
140 
141  if ( !$this->conn ) {
142  throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
143  }
144 
145  try {
146  $this->currentDomain = new DatabaseDomain(
147  strlen( $dbName ) ? $dbName : null,
148  null,
149  $tablePrefix
150  );
151  // Abstract over any insane MySQL defaults
152  $set = [ 'group_concat_max_len = 262144' ];
153  // Set SQL mode, default is turning them all off, can be overridden or skipped with null
154  if ( is_string( $this->sqlMode ) ) {
155  $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
156  }
157  // Set any custom settings defined by site config
158  // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
159  foreach ( $this->connectionVariables as $var => $val ) {
160  // Escape strings but not numbers to avoid MySQL complaining
161  if ( !is_int( $val ) && !is_float( $val ) ) {
162  $val = $this->addQuotes( $val );
163  }
164  $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
165  }
166 
167  if ( $set ) {
168  $this->query(
169  'SET ' . implode( ', ', $set ),
170  __METHOD__,
171  self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX
172  );
173  }
174  } catch ( RuntimeException $e ) {
175  throw $this->newExceptionAfterConnectError( $e->getMessage() );
176  }
177  }
178 
179  protected function doSelectDomain( DatabaseDomain $domain ) {
180  if ( $domain->getSchema() !== null ) {
181  throw new DBExpectedError(
182  $this,
183  __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
184  );
185  }
186 
187  $database = $domain->getDatabase();
188  // A null database means "don't care" so leave it as is and update the table prefix
189  if ( $database === null ) {
190  $this->currentDomain = new DatabaseDomain(
191  $this->currentDomain->getDatabase(),
192  null,
193  $domain->getTablePrefix()
194  );
195 
196  return true;
197  }
198 
199  if ( $database !== $this->getDBname() ) {
200  $sql = 'USE ' . $this->addIdentifierQuotes( $database );
201  list( $res, $err, $errno ) =
202  $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
203 
204  if ( $res === false ) {
205  $this->reportQueryError( $err, $errno, $sql, __METHOD__ );
206  return false; // unreachable
207  }
208  }
209 
210  // Update that domain fields on success (no exception thrown)
211  $this->currentDomain = $domain;
212 
213  return true;
214  }
215 
224  abstract protected function mysqlConnect( $realServer, $dbName );
225 
230  public function freeResult( $res ) {
231  AtEase::suppressWarnings();
232  $ok = $this->mysqlFreeResult( ResultWrapper::unwrap( $res ) );
233  AtEase::restoreWarnings();
234  if ( !$ok ) {
235  throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
236  }
237  }
238 
245  abstract protected function mysqlFreeResult( $res );
246 
252  public function fetchObject( $res ) {
253  AtEase::suppressWarnings();
254  $row = $this->mysqlFetchObject( ResultWrapper::unwrap( $res ) );
255  AtEase::restoreWarnings();
256 
257  $errno = $this->lastErrno();
258  // Unfortunately, mysql_fetch_object does not reset the last errno.
259  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
260  // these are the only errors mysql_fetch_object can cause.
261  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
262  if ( $errno == 2000 || $errno == 2013 ) {
263  throw new DBUnexpectedError(
264  $this,
265  'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
266  );
267  }
268 
269  return $row;
270  }
271 
278  abstract protected function mysqlFetchObject( $res );
279 
285  public function fetchRow( $res ) {
286  AtEase::suppressWarnings();
287  $row = $this->mysqlFetchArray( ResultWrapper::unwrap( $res ) );
288  AtEase::restoreWarnings();
289 
290  $errno = $this->lastErrno();
291  // Unfortunately, mysql_fetch_array does not reset the last errno.
292  // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
293  // these are the only errors mysql_fetch_array can cause.
294  // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
295  if ( $errno == 2000 || $errno == 2013 ) {
296  throw new DBUnexpectedError(
297  $this,
298  'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
299  );
300  }
301 
302  return $row;
303  }
304 
311  abstract protected function mysqlFetchArray( $res );
312 
318  public function numRows( $res ) {
319  if ( is_bool( $res ) ) {
320  $n = 0;
321  } else {
322  AtEase::suppressWarnings();
323  $n = $this->mysqlNumRows( ResultWrapper::unwrap( $res ) );
324  AtEase::restoreWarnings();
325  }
326 
327  // Unfortunately, mysql_num_rows does not reset the last errno.
328  // We are not checking for any errors here, since
329  // there are no errors mysql_num_rows can cause.
330  // See https://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  public function numFields( $res ) {
348  return $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
349  }
350 
357  abstract protected function mysqlNumFields( $res );
358 
364  public function fieldName( $res, $n ) {
365  return $this->mysqlFieldName( ResultWrapper::unwrap( $res ), $n );
366  }
367 
375  abstract protected function mysqlFieldName( $res, $n );
376 
383  public function fieldType( $res, $n ) {
384  return $this->mysqlFieldType( ResultWrapper::unwrap( $res ), $n );
385  }
386 
394  abstract protected function mysqlFieldType( $res, $n );
395 
401  public function dataSeek( $res, $row ) {
402  return $this->mysqlDataSeek( ResultWrapper::unwrap( $res ), $row );
403  }
404 
412  abstract protected function mysqlDataSeek( $res, $row );
413 
417  public function lastError() {
418  if ( $this->conn ) {
419  # Even if it's non-zero, it can still be invalid
420  AtEase::suppressWarnings();
421  $error = $this->mysqlError( $this->conn );
422  if ( !$error ) {
423  $error = $this->mysqlError();
424  }
425  AtEase::restoreWarnings();
426  } else {
427  $error = $this->mysqlError();
428  }
429  if ( $error ) {
430  $error .= ' (' . $this->server . ')';
431  }
432 
433  return $error;
434  }
435 
442  abstract protected function mysqlError( $conn = null );
443 
444  protected function wasQueryTimeout( $error, $errno ) {
445  // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
446  // https://phabricator.wikimedia.org/T170638
447  return in_array( $errno, [ 2062, 3024 ] );
448  }
449 
450  protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
451  $row = $this->getReplicationSafetyInfo();
452  // For row-based-replication, the resulting changes will be relayed, not the query
453  if ( $row->binlog_format === 'ROW' ) {
454  return true;
455  }
456  // LIMIT requires ORDER BY on a unique key or it is non-deterministic
457  if ( isset( $selectOptions['LIMIT'] ) ) {
458  return false;
459  }
460  // In MySQL, an INSERT SELECT is only replication safe with row-based
461  // replication or if innodb_autoinc_lock_mode is 0. When those
462  // conditions aren't met, use non-native mode.
463  // While we could try to determine if the insert is safe anyway by
464  // checking if the target table has an auto-increment column that
465  // isn't set in $varMap, that seems unlikely to be worth the extra
466  // complexity.
467  return (
468  in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
469  (int)$row->innodb_autoinc_lock_mode === 0
470  );
471  }
472 
476  protected function getReplicationSafetyInfo() {
477  if ( $this->replicationInfoRow === null ) {
478  $this->replicationInfoRow = $this->selectRow(
479  false,
480  [
481  'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
482  'binlog_format' => '@@binlog_format',
483  ],
484  [],
485  __METHOD__
486  );
487  }
488 
490  }
491 
505  public function estimateRowCount( $table, $var = '*', $conds = '',
506  $fname = __METHOD__, $options = [], $join_conds = []
507  ) {
508  $conds = $this->normalizeConditions( $conds, $fname );
509  $column = $this->extractSingleFieldFromList( $var );
510  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
511  $conds[] = "$column IS NOT NULL";
512  }
513 
514  $options['EXPLAIN'] = true;
515  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
516  if ( $res === false ) {
517  return false;
518  }
519  if ( !$this->numRows( $res ) ) {
520  return 0;
521  }
522 
523  $rows = 1;
524  foreach ( $res as $plan ) {
525  $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
526  }
527 
528  return (int)$rows;
529  }
530 
531  public function tableExists( $table, $fname = __METHOD__ ) {
532  // Split database and table into proper variables as Database::tableName() returns
533  // shared tables prefixed with their database, which do not work in SHOW TABLES statements
534  list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
535  $tableName = "{$prefix}{$table}";
536 
537  if ( isset( $this->sessionTempTables[$tableName] ) ) {
538  return true; // already known to exist and won't show in SHOW TABLES anyway
539  }
540 
541  // We can't use buildLike() here, because it specifies an escape character
542  // other than the backslash, which is the only one supported by SHOW TABLES
543  $encLike = $this->escapeLikeInternal( $tableName, '\\' );
544 
545  // If the database has been specified (such as for shared tables), use "FROM"
546  if ( $database !== '' ) {
547  $encDatabase = $this->addIdentifierQuotes( $database );
548  $sql = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
549  } else {
550  $sql = "SHOW TABLES LIKE '$encLike'";
551  }
552 
553  $res = $this->query(
554  $sql,
555  $fname,
556  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
557  );
558 
559  return $res->numRows() > 0;
560  }
561 
567  public function fieldInfo( $table, $field ) {
568  $res = $this->query(
569  "SELECT * FROM " . $this->tableName( $table ) . " LIMIT 1",
570  __METHOD__,
571  self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
572  );
573  if ( !$res ) {
574  return false;
575  }
576  $n = $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
577  for ( $i = 0; $i < $n; $i++ ) {
578  $meta = $this->mysqlFetchField( ResultWrapper::unwrap( $res ), $i );
579  if ( $field == $meta->name ) {
580  return new MySQLField( $meta );
581  }
582  }
583 
584  return false;
585  }
586 
594  abstract protected function mysqlFetchField( $res, $n );
595 
605  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
606  # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
607  $index = $this->indexName( $index );
608 
609  $res = $this->query(
610  'SHOW INDEX FROM ' . $this->tableName( $table ),
611  $fname,
612  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
613  );
614 
615  if ( !$res ) {
616  return null;
617  }
618 
619  $result = [];
620 
621  foreach ( $res as $row ) {
622  if ( $row->Key_name == $index ) {
623  $result[] = $row;
624  }
625  }
626 
627  return $result ?: false;
628  }
629 
634  public function strencode( $s ) {
635  return $this->mysqlRealEscapeString( $s );
636  }
637 
642  abstract protected function mysqlRealEscapeString( $s );
643 
650  public function addIdentifierQuotes( $s ) {
651  // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
652  // Remove NUL bytes and escape backticks by doubling
653  return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
654  }
655 
660  public function isQuotedIdentifier( $name ) {
661  return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
662  }
663 
664  protected function doGetLag() {
665  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
666  return $this->getLagFromPtHeartbeat();
667  } else {
668  return $this->getLagFromSlaveStatus();
669  }
670  }
671 
675  protected function getLagDetectionMethod() {
677  }
678 
682  protected function getLagFromSlaveStatus() {
683  $res = $this->query(
684  'SHOW SLAVE STATUS',
685  __METHOD__,
686  self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
687  );
688  $row = $res ? $res->fetchObject() : false;
689  // If the server is not replicating, there will be no row
690  if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
691  return intval( $row->Seconds_Behind_Master );
692  }
693 
694  return false;
695  }
696 
700  protected function getLagFromPtHeartbeat() {
701  $options = $this->lagDetectionOptions;
702 
703  $currentTrxInfo = $this->getRecordedTransactionLagStatus();
704  if ( $currentTrxInfo ) {
705  // There is an active transaction and the initial lag was already queried
706  $staleness = microtime( true ) - $currentTrxInfo['since'];
707  if ( $staleness > self::LAG_STALE_WARN_THRESHOLD ) {
708  // Avoid returning higher and higher lag value due to snapshot age
709  // given that the isolation level will typically be REPEATABLE-READ
710  $this->queryLogger->warning(
711  "Using cached lag value for {db_server} due to active transaction",
712  $this->getLogContext( [
713  'method' => __METHOD__,
714  'age' => $staleness,
715  'exception' => new RuntimeException()
716  ] )
717  );
718  }
719 
720  return $currentTrxInfo['lag'];
721  }
722 
723  if ( isset( $options['conds'] ) ) {
724  // Best method for multi-DC setups: use logical channel names
725  $data = $this->getHeartbeatData( $options['conds'] );
726  } else {
727  // Standard method: use master server ID (works with stock pt-heartbeat)
728  $masterInfo = $this->getMasterServerInfo();
729  if ( !$masterInfo ) {
730  $this->queryLogger->error(
731  "Unable to query master of {db_server} for server ID",
732  $this->getLogContext( [
733  'method' => __METHOD__
734  ] )
735  );
736 
737  return false; // could not get master server ID
738  }
739 
740  $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
741  $data = $this->getHeartbeatData( $conds );
742  }
743 
744  list( $time, $nowUnix ) = $data;
745  if ( $time !== null ) {
746  // @time is in ISO format like "2015-09-25T16:48:10.000510"
747  $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
748  $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
749 
750  return max( $nowUnix - $timeUnix, 0.0 );
751  }
752 
753  $this->queryLogger->error(
754  "Unable to find pt-heartbeat row for {db_server}",
755  $this->getLogContext( [
756  'method' => __METHOD__
757  ] )
758  );
759 
760  return false;
761  }
762 
763  protected function getMasterServerInfo() {
765  $key = $cache->makeGlobalKey(
766  'mysql',
767  'master-info',
768  // Using one key for all cluster replica DBs is preferable
769  $this->topologyRootMaster ?? $this->getServer()
770  );
771  $fname = __METHOD__;
772 
773  return $cache->getWithSetCallback(
774  $key,
775  $cache::TTL_INDEFINITE,
776  function () use ( $cache, $key, $fname ) {
777  // Get and leave a lock key in place for a short period
778  if ( !$cache->lock( $key, 0, 10 ) ) {
779  return false; // avoid master connection spike slams
780  }
781 
782  $conn = $this->getLazyMasterHandle();
783  if ( !$conn ) {
784  return false; // something is misconfigured
785  }
786 
787  $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
788  // Connect to and query the master; catch errors to avoid outages
789  try {
790  $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
791  $row = $res ? $res->fetchObject() : false;
792  $id = $row ? (int)$row->id : 0;
793  } catch ( DBError $e ) {
794  $id = 0;
795  }
796 
797  // Cache the ID if it was retrieved
798  return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
799  }
800  );
801  }
802 
808  protected function getHeartbeatData( array $conds ) {
809  // Query time and trip time are not counted
810  $nowUnix = microtime( true );
811  $whereSQL = $this->makeList( $conds, self::LIST_AND );
812  // Use ORDER BY for channel based queries since that field might not be UNIQUE.
813  // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
814  // percision field is not supported in MySQL <= 5.5.
815  $res = $this->query(
816  "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
817  __METHOD__,
818  self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
819  );
820  $row = $res ? $res->fetchObject() : false;
821 
822  return [ $row ? $row->ts : null, $nowUnix ];
823  }
824 
825  protected function getApproximateLagStatus() {
826  if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
827  // Disable caching since this is fast enough and we don't wan't
828  // to be *too* pessimistic by having both the cache TTL and the
829  // pt-heartbeat interval count as lag in getSessionLagStatus()
830  return parent::getApproximateLagStatus();
831  }
832 
833  $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
834  $approxLag = $this->srvCache->get( $key );
835  if ( !$approxLag ) {
836  $approxLag = parent::getApproximateLagStatus();
837  $this->srvCache->set( $key, $approxLag, 1 );
838  }
839 
840  return $approxLag;
841  }
842 
843  public function masterPosWait( DBMasterPos $pos, $timeout ) {
844  if ( !( $pos instanceof MySQLMasterPos ) ) {
845  throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
846  }
847 
848  if ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
849  $this->queryLogger->debug(
850  "Bypassed replication wait; database has a static dataset",
851  $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
852  );
853 
854  return 0; // this is a copy of a read-only dataset with no master DB
855  } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
856  $this->queryLogger->debug(
857  "Bypassed replication wait; replication known to have reached {raw_pos}",
858  $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
859  );
860 
861  return 0; // already reached this point for sure
862  }
863 
864  // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
865  if ( $pos->getGTIDs() ) {
866  // Get the GTIDs from this replica server too see the domains (channels)
867  $refPos = $this->getReplicaPos();
868  if ( !$refPos ) {
869  $this->queryLogger->error(
870  "Could not get replication position on replica DB to compare to {raw_pos}",
871  $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
872  );
873 
874  return -1; // this is the master itself?
875  }
876  // GTIDs with domains (channels) that are active and are present on the replica
877  $gtidsWait = $pos::getRelevantActiveGTIDs( $pos, $refPos );
878  if ( !$gtidsWait ) {
879  $this->queryLogger->error(
880  "No active GTIDs in {raw_pos} share a domain with those in {current_pos}",
881  $this->getLogContext( [
882  'method' => __METHOD__,
883  'raw_pos' => $pos,
884  'current_pos' => $refPos
885  ] )
886  );
887 
888  return -1; // $pos is from the wrong cluster?
889  }
890  // Wait on the GTID set
891  $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
892  if ( strpos( $gtidArg, ':' ) !== false ) {
893  // MySQL GTIDs, e.g "source_id:transaction_id"
894  $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
895  } else {
896  // MariaDB GTIDs, e.g."domain:server:sequence"
897  $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
898  }
899  $waitPos = implode( ',', $gtidsWait );
900  } else {
901  // Wait on the binlog coordinates
902  $encFile = $this->addQuotes( $pos->getLogFile() );
903  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
904  $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
905  $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
906  $waitPos = $pos->__toString();
907  }
908 
909  $start = microtime( true );
910  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
911  $res = $this->query( $sql, __METHOD__, $flags );
912  $row = $this->fetchRow( $res );
913  $seconds = max( microtime( true ) - $start, 0 );
914 
915  // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
916  $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
917  if ( $status === null ) {
918  $this->replLogger->error(
919  "An error occurred while waiting for replication to reach {raw_pos}",
920  $this->getLogContext( [
921  'raw_pos' => $pos,
922  'wait_pos' => $waitPos,
923  'sql' => $sql,
924  'seconds_waited' => $seconds,
925  'exception' => new RuntimeException()
926  ] )
927  );
928  } elseif ( $status < 0 ) {
929  $this->replLogger->error(
930  "Timed out waiting for replication to reach {raw_pos}",
931  $this->getLogContext( [
932  'raw_pos' => $pos,
933  'wait_pos' => $waitPos,
934  'timeout' => $timeout,
935  'sql' => $sql,
936  'seconds_waited' => $seconds,
937  'exception' => new RuntimeException()
938  ] )
939  );
940  } elseif ( $status >= 0 ) {
941  $this->replLogger->debug(
942  "Replication has reached {raw_pos}",
943  $this->getLogContext( [
944  'raw_pos' => $pos,
945  'wait_pos' => $waitPos,
946  'seconds_waited' => $seconds,
947  ] )
948  );
949  // Remember that this position was reached to save queries next time
950  $this->lastKnownReplicaPos = $pos;
951  }
952 
953  return $status;
954  }
955 
961  public function getReplicaPos() {
962  $now = microtime( true ); // as-of-time *before* fetching GTID variables
963 
964  if ( $this->useGTIDs() ) {
965  // Try to use GTIDs, fallbacking to binlog positions if not possible
966  $data = $this->getServerGTIDs( __METHOD__ );
967  // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
968  foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
969  if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
970  return new MySQLMasterPos( $data[$name], $now );
971  }
972  }
973  }
974 
975  $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
976  if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
977  return new MySQLMasterPos(
978  "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
979  $now
980  );
981  }
982 
983  return false;
984  }
985 
991  public function getMasterPos() {
992  $now = microtime( true ); // as-of-time *before* fetching GTID variables
993 
994  $pos = false;
995  if ( $this->useGTIDs() ) {
996  // Try to use GTIDs, fallbacking to binlog positions if not possible
997  $data = $this->getServerGTIDs( __METHOD__ );
998  // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
999  foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
1000  if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1001  $pos = new MySQLMasterPos( $data[$name], $now );
1002  break;
1003  }
1004  }
1005  // Filter domains that are inactive or not relevant to the session
1006  if ( $pos ) {
1007  $pos->setActiveOriginServerId( $this->getServerId() );
1008  $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1009  if ( isset( $data['gtid_domain_id'] ) ) {
1010  $pos->setActiveDomain( $data['gtid_domain_id'] );
1011  }
1012  }
1013  }
1014 
1015  if ( !$pos ) {
1016  $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
1017  if ( $data && strlen( $data['File'] ) ) {
1018  $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1019  }
1020  }
1021 
1022  return $pos;
1023  }
1024 
1029  protected function getServerId() {
1030  $fname = __METHOD__;
1031  return $this->srvCache->getWithSetCallback(
1032  $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1033  self::SERVER_ID_CACHE_TTL,
1034  function () use ( $fname ) {
1035  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1036  $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
1037 
1038  return intval( $this->fetchObject( $res )->id );
1039  }
1040  );
1041  }
1042 
1046  protected function getServerUUID() {
1047  $fname = __METHOD__;
1048  return $this->srvCache->getWithSetCallback(
1049  $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1050  self::SERVER_ID_CACHE_TTL,
1051  function () use ( $fname ) {
1052  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1053  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
1054  $row = $this->fetchObject( $res );
1055 
1056  return $row ? $row->Value : null;
1057  }
1058  );
1059  }
1060 
1065  protected function getServerGTIDs( $fname = __METHOD__ ) {
1066  $map = [];
1067 
1068  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1069 
1070  // Get global-only variables like gtid_executed
1071  $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
1072  foreach ( $res as $row ) {
1073  $map[$row->Variable_name] = $row->Value;
1074  }
1075  // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1076  $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
1077  foreach ( $res as $row ) {
1078  $map[$row->Variable_name] = $row->Value;
1079  }
1080 
1081  return $map;
1082  }
1083 
1089  protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
1090  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1091  $res = $this->query( "SHOW $role STATUS", $fname, $flags );
1092 
1093  return $res->fetchRow() ?: [];
1094  }
1095 
1096  public function serverIsReadOnly() {
1097  // Avoid SHOW to avoid internal temporary tables
1098  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1099  $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
1100  $row = $this->fetchObject( $res );
1101 
1102  return $row ? (bool)$row->Value : false;
1103  }
1104 
1109  public function useIndexClause( $index ) {
1110  return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1111  }
1112 
1117  public function ignoreIndexClause( $index ) {
1118  return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1119  }
1120 
1124  public function getSoftwareLink() {
1125  // MariaDB includes its name in its version string; this is how MariaDB's version of
1126  // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1127  // in libmysql/libmysql.c).
1128  $version = $this->getServerVersion();
1129  if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
1130  return '[{{int:version-db-mariadb-url}} MariaDB]';
1131  }
1132 
1133  // Percona Server's version suffix is not very distinctive, and @@version_comment
1134  // doesn't give the necessary info for source builds, so assume the server is MySQL.
1135  // (Even Percona's version of mysql doesn't try to make the distinction.)
1136  return '[{{int:version-db-mysql-url}} MySQL]';
1137  }
1138 
1142  public function getServerVersion() {
1144  $fname = __METHOD__;
1145 
1146  return $cache->getWithSetCallback(
1147  $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
1148  $cache::TTL_HOUR,
1149  function () use ( $fname ) {
1150  // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1151  // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1152  // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1153  return $this->selectField( '', 'VERSION()', '', $fname );
1154  }
1155  );
1156  }
1157 
1161  public function setSessionOptions( array $options ) {
1162  if ( isset( $options['connTimeout'] ) ) {
1163  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_TRX;
1164  $timeout = (int)$options['connTimeout'];
1165  $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
1166  $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
1167  }
1168  }
1169 
1175  public function streamStatementEnd( &$sql, &$newLine ) {
1176  if ( preg_match( '/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
1177  $this->delimiter = $m[1];
1178  $newLine = '';
1179  }
1180 
1181  return parent::streamStatementEnd( $sql, $newLine );
1182  }
1183 
1192  public function lockIsFree( $lockName, $method ) {
1193  if ( !parent::lockIsFree( $lockName, $method ) ) {
1194  return false; // already held
1195  }
1196 
1197  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1198 
1199  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1200  $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
1201  $row = $this->fetchObject( $res );
1202 
1203  return ( $row->lockstatus == 1 );
1204  }
1205 
1212  public function lock( $lockName, $method, $timeout = 5 ) {
1213  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1214 
1215  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1216  $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
1217  $row = $this->fetchObject( $res );
1218 
1219  if ( $row->lockstatus == 1 ) {
1220  parent::lock( $lockName, $method, $timeout ); // record
1221  return true;
1222  }
1223 
1224  $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
1225  [ 'lockname' => $lockName ] );
1226 
1227  return false;
1228  }
1229 
1237  public function unlock( $lockName, $method ) {
1238  $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1239 
1240  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1241  $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
1242  $row = $this->fetchObject( $res );
1243 
1244  if ( $row->lockstatus == 1 ) {
1245  parent::unlock( $lockName, $method ); // record
1246  return true;
1247  }
1248 
1249  $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
1250 
1251  return false;
1252  }
1253 
1254  private function makeLockName( $lockName ) {
1255  // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1256  // Newer version enforce a 64 char length limit.
1257  return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1258  }
1259 
1260  public function namedLocksEnqueue() {
1261  return true;
1262  }
1263 
1265  return false; // tied to TCP connection
1266  }
1267 
1268  protected function doLockTables( array $read, array $write, $method ) {
1269  $items = [];
1270  foreach ( $write as $table ) {
1271  $items[] = $this->tableName( $table ) . ' WRITE';
1272  }
1273  foreach ( $read as $table ) {
1274  $items[] = $this->tableName( $table ) . ' READ';
1275  }
1276 
1277  $this->query(
1278  "LOCK TABLES " . implode( ',', $items ),
1279  $method,
1280  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_ROWS
1281  );
1282 
1283  return true;
1284  }
1285 
1286  protected function doUnlockTables( $method ) {
1287  $this->query(
1288  "UNLOCK TABLES",
1289  $method,
1290  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_ROWS
1291  );
1292 
1293  return true;
1294  }
1295 
1299  public function setBigSelects( $value = true ) {
1300  if ( $value === 'default' ) {
1301  if ( $this->defaultBigSelects === null ) {
1302  # Function hasn't been called before so it must already be set to the default
1303  return;
1304  } else {
1305  $value = $this->defaultBigSelects;
1306  }
1307  } elseif ( $this->defaultBigSelects === null ) {
1308  $this->defaultBigSelects =
1309  (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1310  }
1311 
1312  $this->query(
1313  "SET sql_big_selects=" . ( $value ? '1' : '0' ),
1314  __METHOD__,
1315  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_TRX
1316  );
1317  }
1318 
1329  public function deleteJoin(
1330  $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1331  ) {
1332  if ( !$conds ) {
1333  throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1334  }
1335 
1336  $delTable = $this->tableName( $delTable );
1337  $joinTable = $this->tableName( $joinTable );
1338  $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1339 
1340  if ( $conds != '*' ) {
1341  $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1342  }
1343 
1344  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
1345  }
1346 
1347  protected function doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname ) {
1348  $encTable = $this->tableName( $table );
1349  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
1350  $sqlColumnAssignments = $this->makeList( $set, self::LIST_SET );
1351 
1352  $sql =
1353  "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples " .
1354  "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
1355 
1356  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
1357  }
1358 
1359  protected function doReplace( $table, array $uniqueKeys, array $rows, $fname ) {
1360  $encTable = $this->tableName( $table );
1361  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
1362 
1363  $sql = "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
1364 
1365  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
1366  }
1367 
1373  public function getServerUptime() {
1374  $vars = $this->getMysqlStatus( 'Uptime' );
1375 
1376  return (int)$vars['Uptime'];
1377  }
1378 
1384  public function wasDeadlock() {
1385  return $this->lastErrno() == 1213;
1386  }
1387 
1393  public function wasLockTimeout() {
1394  return $this->lastErrno() == 1205;
1395  }
1396 
1402  public function wasReadOnlyError() {
1403  return $this->lastErrno() == 1223 ||
1404  ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1405  }
1406 
1407  public function wasConnectionError( $errno ) {
1408  return $errno == 2013 || $errno == 2006;
1409  }
1410 
1411  protected function wasKnownStatementRollbackError() {
1412  $errno = $this->lastErrno();
1413 
1414  if ( $errno === 1205 ) { // lock wait timeout
1415  // Note that this is uncached to avoid stale values of SET is used
1416  $row = $this->selectRow(
1417  false,
1418  [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1419  [],
1420  __METHOD__
1421  );
1422  // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1423  // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1424  return $row->innodb_rollback_on_timeout ? false : true;
1425  }
1426 
1427  // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1428  return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1429  }
1430 
1438  public function duplicateTableStructure(
1439  $oldName, $newName, $temporary = false, $fname = __METHOD__
1440  ) {
1441  $tmp = $temporary ? 'TEMPORARY ' : '';
1442  $newName = $this->addIdentifierQuotes( $newName );
1443  $oldName = $this->addIdentifierQuotes( $oldName );
1444 
1445  return $this->query(
1446  "CREATE $tmp TABLE $newName (LIKE $oldName)",
1447  $fname,
1448  self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA
1449  );
1450  }
1451 
1459  public function listTables( $prefix = null, $fname = __METHOD__ ) {
1460  $result = $this->query(
1461  "SHOW TABLES",
1462  $fname,
1463  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1464  );
1465 
1466  $endArray = [];
1467 
1468  foreach ( $result as $table ) {
1469  $vars = get_object_vars( $table );
1470  $table = array_pop( $vars );
1471 
1472  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1473  $endArray[] = $table;
1474  }
1475  }
1476 
1477  return $endArray;
1478  }
1479 
1486  private function getMysqlStatus( $which = "%" ) {
1487  $res = $this->query(
1488  "SHOW STATUS LIKE '{$which}'",
1489  __METHOD__,
1490  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1491  );
1492 
1493  $status = [];
1494  foreach ( $res as $row ) {
1495  $status[$row->Variable_name] = $row->Value;
1496  }
1497 
1498  return $status;
1499  }
1500 
1510  public function listViews( $prefix = null, $fname = __METHOD__ ) {
1511  // The name of the column containing the name of the VIEW
1512  $propertyName = 'Tables_in_' . $this->getDBname();
1513 
1514  // Query for the VIEWS
1515  $res = $this->query(
1516  'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"',
1517  $fname,
1518  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1519  );
1520 
1521  $allViews = [];
1522  foreach ( $res as $row ) {
1523  array_push( $allViews, $row->$propertyName );
1524  }
1525 
1526  if ( $prefix === null || $prefix === '' ) {
1527  return $allViews;
1528  }
1529 
1530  $filteredViews = [];
1531  foreach ( $allViews as $viewName ) {
1532  // Does the name of this VIEW start with the table-prefix?
1533  if ( strpos( $viewName, $prefix ) === 0 ) {
1534  array_push( $filteredViews, $viewName );
1535  }
1536  }
1537 
1538  return $filteredViews;
1539  }
1540 
1549  public function isView( $name, $prefix = null ) {
1550  return in_array( $name, $this->listViews( $prefix ) );
1551  }
1552 
1553  protected function isTransactableQuery( $sql ) {
1554  return parent::isTransactableQuery( $sql ) &&
1555  !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\‍(/', $sql );
1556  }
1557 
1558  public function buildStringCast( $field ) {
1559  return "CAST( $field AS BINARY )";
1560  }
1561 
1566  public function buildIntegerCast( $field ) {
1567  return 'CAST( ' . $field . ' AS SIGNED )';
1568  }
1569 
1570  /*
1571  * @return bool Whether GTID support is used (mockable for testing)
1572  */
1573  protected function useGTIDs() {
1574  return $this->useGTIDs;
1575  }
1576 }
1577 
1581 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );
Wikimedia\Rdbms\DatabaseMysqlBase\doLockTables
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
Definition: DatabaseMysqlBase.php:1268
Wikimedia\Rdbms\DatabaseMysqlBase\estimateRowCount
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output Takes same arguments as Dat...
Definition: DatabaseMysqlBase.php:505
Wikimedia\Rdbms\DatabaseMysqlBase\addIdentifierQuotes
addIdentifierQuotes( $s)
MySQL uses backticks for identifier quoting instead of the sql standard "double quotes".
Definition: DatabaseMysqlBase.php:650
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:49
Wikimedia\Rdbms\DatabaseMysqlBase\masterPosWait
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the replica DB to catch up to a given master position.
Definition: DatabaseMysqlBase.php:843
Wikimedia\Rdbms\DatabaseMysqlBase\wasQueryTimeout
wasQueryTimeout( $error, $errno)
Checks whether the cause of the error is detected to be a timeout.
Definition: DatabaseMysqlBase.php:444
Wikimedia\Rdbms\DatabaseMysqlBase\$sslKeyPath
string null $sslKeyPath
Definition: DatabaseMysqlBase.php:50
Wikimedia\Rdbms\DatabaseMysqlBase\getLagDetectionMethod
getLagDetectionMethod()
Definition: DatabaseMysqlBase.php:675
Wikimedia\Rdbms\DatabaseMysqlBase\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: DatabaseMysqlBase.php:1411
Wikimedia\Rdbms\DatabaseMysqlBase\getServerId
getServerId()
Definition: DatabaseMysqlBase.php:1029
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:605
Wikimedia\Rdbms\DatabaseMysqlBase\setSessionOptions
setSessionOptions(array $options)
Definition: DatabaseMysqlBase.php:1161
Wikimedia\Rdbms\DatabaseMysqlBase\getServerUptime
getServerUptime()
Determines how long the server has been up.
Definition: DatabaseMysqlBase.php:1373
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlRealEscapeString
mysqlRealEscapeString( $s)
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCAPath
string null $sslCAPath
Definition: DatabaseMysqlBase.php:56
if
if(ini_get( 'mbstring.func_overload')) if(!defined('MW_ENTRY_POINT'))
Pre-config setup: Before loading LocalSettings.php.
Definition: Setup.php:85
Wikimedia\Rdbms\DatabaseMysqlBase\getApproximateLagStatus
getApproximateLagStatus()
Get a replica DB lag estimate for this server at the start of a transaction.
Definition: DatabaseMysqlBase.php:825
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:318
Wikimedia\Rdbms\Database\$password
string $password
Password used to establish the current connection.
Definition: Database.php:81
Wikimedia\Rdbms\DatabaseMysqlBase\getServerUUID
getServerUUID()
Definition: DatabaseMysqlBase.php:1046
Wikimedia\Rdbms\DatabaseMysqlBase\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
Definition: DatabaseMysqlBase.php:1393
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:3002
Wikimedia\Rdbms\Database\executeQuery
executeQuery( $sql, $fname, $flags)
Execute a query, retrying it if there is a recoverable connection loss.
Definition: Database.php:1241
Wikimedia\Rdbms\DatabaseDomain\getTablePrefix
getTablePrefix()
Definition: DatabaseDomain.php:189
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCertPath
string null $sslCertPath
Definition: DatabaseMysqlBase.php:52
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:808
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:2107
Wikimedia\Rdbms\DBMasterPos
An object representing a master or replica DB position in a replicated setup.
Definition: DBMasterPos.php:12
Wikimedia\Rdbms\DatabaseMysqlBase\doGetLag
doGetLag()
Definition: DatabaseMysqlBase.php:664
$s
$s
Definition: mergeMessageFileList.php:185
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:2210
Wikimedia\Rdbms\DatabaseMysqlBase\ignoreIndexClause
ignoreIndexClause( $index)
Definition: DatabaseMysqlBase.php:1117
Wikimedia\Rdbms\DatabaseDomain\getDatabase
getDatabase()
Definition: DatabaseDomain.php:175
$res
$res
Definition: testCompression.php:57
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFreeResult
mysqlFreeResult( $res)
Free result memory.
Wikimedia\Rdbms\DatabaseMysqlBase\fieldInfo
fieldInfo( $table, $field)
Definition: DatabaseMysqlBase.php:567
Wikimedia\Rdbms\DatabaseMysqlBase\doReplace
doReplace( $table, array $uniqueKeys, array $rows, $fname)
Definition: DatabaseMysqlBase.php:1359
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
Wikimedia\Rdbms\DatabaseMysqlBase\setBigSelects
setBigSelects( $value=true)
Definition: DatabaseMysqlBase.php:1299
Wikimedia\Rdbms\DatabaseMysqlBase\__construct
__construct(array $params)
Additional $params include:
Definition: DatabaseMysqlBase.php:96
Wikimedia\Rdbms\DatabaseMysqlBase\buildIntegerCast
buildIntegerCast( $field)
Definition: DatabaseMysqlBase.php:1566
Wikimedia\Rdbms\DatabaseMysqlBase\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.
Definition: DatabaseMysqlBase.php:1384
LIST_AND
const LIST_AND
Definition: Defines.php:48
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlNumFields
mysqlNumFields( $res)
Get number of fields in result.
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlFetchObject
mysqlFetchObject( $res)
Fetch a result row as an object.
Wikimedia\Rdbms\Database\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:887
Wikimedia\Rdbms\DatabaseMysqlBase\doUnlockTables
doUnlockTables( $method)
Helper function for unlockTables() that handles the actual table unlocking.
Definition: DatabaseMysqlBase.php:1286
Wikimedia\Rdbms\DatabaseMysqlBase\SERVER_ID_CACHE_TTL
const SERVER_ID_CACHE_TTL
Definition: DatabaseMysqlBase.php:72
Wikimedia\Rdbms\DatabaseMysqlBase\buildStringCast
buildStringCast( $field)
Definition: DatabaseMysqlBase.php:1558
Wikimedia\Rdbms\DatabaseMysqlBase\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Definition: DatabaseMysqlBase.php:1438
Wikimedia\Rdbms\DatabaseMysqlBase\fieldName
fieldName( $res, $n)
Definition: DatabaseMysqlBase.php:364
Wikimedia\Rdbms\Database\escapeLikeInternal
escapeLikeInternal( $s, $escapeChar='`')
Definition: Database.php:3043
Wikimedia\Rdbms\DatabaseMysqlBase\getLagFromPtHeartbeat
getLagFromPtHeartbeat()
Definition: DatabaseMysqlBase.php:700
Wikimedia\Rdbms\Database\reportQueryError
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
Definition: Database.php:1636
LIST_SET
const LIST_SET
Definition: Defines.php:49
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlConnect
mysqlConnect( $realServer, $dbName)
Open a connection to a MySQL server.
Wikimedia\Rdbms\DatabaseMysqlBase\getSoftwareLink
getSoftwareLink()
Definition: DatabaseMysqlBase.php:1124
Wikimedia\Rdbms\Database\makeInsertLists
makeInsertLists(array $rows)
Make SQL lists of columns, row tuples for INSERT/VALUES expressions.
Definition: Database.php:2340
Wikimedia\Rdbms\MySQLMasterPos
DBMasterPos class for MySQL/MariaDB.
Definition: MySQLMasterPos.php:19
Wikimedia\Rdbms\DatabaseMysqlBase\numFields
numFields( $res)
Definition: DatabaseMysqlBase.php:347
Wikimedia\Rdbms\DatabaseMysqlBase\listTables
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Definition: DatabaseMysqlBase.php:1459
Wikimedia\Rdbms\DatabaseMysqlBase\lastError
lastError()
Definition: DatabaseMysqlBase.php:417
Wikimedia\Rdbms\Database\$user
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:79
Wikimedia\Rdbms\DatabaseMysqlBase\getType
getType()
Definition: DatabaseMysqlBase.php:117
Wikimedia\Rdbms\DatabaseMysqlBase\fieldType
fieldType( $res, $n)
mysql_field_type() wrapper
Definition: DatabaseMysqlBase.php:383
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCAFile
string null $sslCAFile
Definition: DatabaseMysqlBase.php:54
Wikimedia\Rdbms\DatabaseMysqlBase\fetchObject
fetchObject( $res)
Definition: DatabaseMysqlBase.php:252
Wikimedia\Rdbms\MySQLField
Definition: MySQLField.php:5
Wikimedia\Rdbms\DatabaseMysqlBase\getReplicationSafetyInfo
getReplicationSafetyInfo()
Definition: DatabaseMysqlBase.php:476
Wikimedia\Rdbms\DatabaseMysqlBase\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Definition: DatabaseMysqlBase.php:1175
Wikimedia\Rdbms\DatabaseMysqlBase\open
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
Definition: DatabaseMysqlBase.php:121
Wikimedia\Rdbms\Database\selectRow
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
Definition: Database.php:1969
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:401
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:825
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:836
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:1237
Wikimedia\Rdbms\DatabaseMysqlBase\wasReadOnlyError
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
Definition: DatabaseMysqlBase.php:1402
Wikimedia\Rdbms\DatabaseMysqlBase\$defaultBigSelects
bool null $defaultBigSelects
Definition: DatabaseMysqlBase.php:64
Wikimedia\Rdbms\Database\getLogContext
getLogContext(array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: Database.php:876
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:230
Wikimedia\Rdbms\DatabaseMysqlBase\mysqlDataSeek
mysqlDataSeek( $res, $row)
Move internal result pointer.
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $flags=self::QUERY_NORMAL)
Run an SQL query and return the result.
Definition: Database.php:1204
Wikimedia\Rdbms\DatabaseMysqlBase\getMasterPos
getMasterPos()
Get the position of the master from SHOW MASTER STATUS.
Definition: DatabaseMysqlBase.php:991
Wikimedia\Rdbms\Database\tableName
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Definition: Database.php:2703
Wikimedia\Rdbms\DatabaseMysqlBase\getReplicaPos
getReplicaPos()
Get the position of the master from SHOW SLAVE STATUS.
Definition: DatabaseMysqlBase.php:961
Wikimedia\Rdbms\DatabaseMysqlBase\getLagFromSlaveStatus
getLagFromSlaveStatus()
Definition: DatabaseMysqlBase.php:682
Wikimedia\Rdbms\DatabaseMysqlBase\$sslCiphers
string[] null $sslCiphers
Definition: DatabaseMysqlBase.php:58
Wikimedia\Rdbms\DatabaseMysqlBase\getServerGTIDs
getServerGTIDs( $fname=__METHOD__)
Definition: DatabaseMysqlBase.php:1065
Wikimedia\Rdbms\Database\getRecordedTransactionLagStatus
getRecordedTransactionLagStatus()
Get the replica DB lag when the current transaction started.
Definition: Database.php:4663
Wikimedia\Rdbms\DatabaseMysqlBase\$utf8Mode
bool $utf8Mode
Use experimental UTF-8 transmission encoding.
Definition: DatabaseMysqlBase.php:62
Wikimedia\Rdbms\Database\getServer
getServer()
Get the server hostname or IP address.
Definition: Database.php:2699
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:27
Wikimedia\Rdbms\Database\selectField
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1709
Wikimedia\Rdbms\DatabaseMysqlBase\$replicationInfoRow
stdClass null $replicationInfoRow
Definition: DatabaseMysqlBase.php:69
Wikimedia\Rdbms\DatabaseMysqlBase\serverIsReadOnly
serverIsReadOnly()
Definition: DatabaseMysqlBase.php:1096
Wikimedia\Rdbms\DatabaseMysqlBase\$sqlMode
string $sqlMode
sql_mode value to send on connection
Definition: DatabaseMysqlBase.php:60
Wikimedia\Rdbms\DatabaseMysqlBase\isTransactableQuery
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
Definition: DatabaseMysqlBase.php:1553
Wikimedia\Rdbms\IDatabase\lastErrno
lastErrno()
Get the last error number.
Wikimedia\Rdbms\DatabaseMysqlBase\makeLockName
makeLockName( $lockName)
Definition: DatabaseMysqlBase.php:1254
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1687
$cache
$cache
Definition: mcc.php:33
Wikimedia\Rdbms\Database\$srvCache
BagOStuff $srvCache
APC cache.
Definition: Database.php:51
Wikimedia\Rdbms\DatabaseMysqlBase\strencode
strencode( $s)
Definition: DatabaseMysqlBase.php:634
Wikimedia\Rdbms\DBExpectedError
Base class for the more common types of database errors.
Definition: DBExpectedError.php:32
Wikimedia\Rdbms\DatabaseMysqlBase\deleteJoin
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
Definition: DatabaseMysqlBase.php:1329
Wikimedia\Rdbms\DatabaseMysqlBase\useIndexClause
useIndexClause( $index)
Definition: DatabaseMysqlBase.php:1109
Wikimedia\Rdbms\DBMasterPos\__toString
__toString()
Wikimedia\Rdbms\DatabaseMysqlBase\getServerRoleStatus
getServerRoleStatus( $role, $fname=__METHOD__)
Definition: DatabaseMysqlBase.php:1089
Wikimedia\Rdbms\DatabaseDomain\getSchema
getSchema()
Definition: DatabaseDomain.php:182
Wikimedia\Rdbms\DatabaseMysqlBase\tableLocksHaveTransactionScope
tableLocksHaveTransactionScope()
Checks if table locks acquired by lockTables() are transaction-bound in their scope.
Definition: DatabaseMysqlBase.php:1264
Wikimedia\Rdbms\Database\$server
string $server
Server that this instance is currently connected to.
Definition: Database.php:77
Wikimedia\Rdbms\DatabaseMysqlBase\listViews
listViews( $prefix=null, $fname=__METHOD__)
Lists VIEWs in the database.
Definition: DatabaseMysqlBase.php:1510
Wikimedia\Rdbms\Database\$flags
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:98
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:1549
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:1874
Wikimedia\Rdbms\DatabaseMysqlBase\$lagDetectionOptions
array $lagDetectionOptions
Method to detect replica DB lag.
Definition: DatabaseMysqlBase.php:46
Wikimedia\Rdbms\Database\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
Definition: Database.php:3006
Wikimedia\Rdbms\DatabaseMysqlBase\$insertSelectIsSafe
bool null $insertSelectIsSafe
Definition: DatabaseMysqlBase.php:67
Wikimedia\Rdbms\Database\qualifiedTableComponents
qualifiedTableComponents( $name)
Get the table components needed for a query given the currently selected database.
Definition: Database.php:2761
Wikimedia\Rdbms\DatabaseMysqlBase\lock
lock( $lockName, $method, $timeout=5)
Definition: DatabaseMysqlBase.php:1212
Wikimedia\Rdbms\DatabaseMysqlBase\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: DatabaseMysqlBase.php:1407
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/schema/prefix specifications for IDatabase.
Definition: DatabaseDomain.php:40
Wikimedia\Rdbms\DatabaseMysqlBase\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Definition: DatabaseMysqlBase.php:179
Wikimedia\Rdbms\DatabaseMysqlBase\fetchRow
fetchRow( $res)
Definition: DatabaseMysqlBase.php:285
Wikimedia\Rdbms\DatabaseMysqlBase\getMysqlStatus
getMysqlStatus( $which="%")
Get status information from SHOW STATUS in an associative array.
Definition: DatabaseMysqlBase.php:1486
Wikimedia\Rdbms\DatabaseMysqlBase\getServerVersion
getServerVersion()
Definition: DatabaseMysqlBase.php:1142
Wikimedia\Rdbms\Database\makeList
makeList(array $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2417
Wikimedia\Rdbms\DatabaseMysqlBase\useGTIDs
useGTIDs()
Definition: DatabaseMysqlBase.php:1573
Wikimedia\Rdbms\ResultWrapper\unwrap
static & unwrap(&$res)
Get the underlying RDBMS driver-specific result resource.
Definition: ResultWrapper.php:59
Wikimedia\Rdbms\DatabaseMysqlBase\doUpsert
doUpsert( $table, array $rows, array $uniqueKeys, array $set, $fname)
Definition: DatabaseMysqlBase.php:1347
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:763
Wikimedia\Rdbms\Database\$conn
object resource null $conn
Database connection.
Definition: Database.php:71
Wikimedia\Rdbms\DatabaseMysqlBase
Database abstraction object for MySQL.
Definition: DatabaseMysqlBase.php:40
Wikimedia\Rdbms\DatabaseMysqlBase\isQuotedIdentifier
isQuotedIdentifier( $name)
Definition: DatabaseMysqlBase.php:660
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current DB name.
Definition: Database.php:2695
Wikimedia\Rdbms\DatabaseMysqlBase\namedLocksEnqueue
namedLocksEnqueue()
Check to see if a named lock used by lock() use blocking queues.
Definition: DatabaseMysqlBase.php:1260
Wikimedia\Rdbms\DatabaseMysqlBase\tableExists
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
Definition: DatabaseMysqlBase.php:531
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:1192
Wikimedia\Rdbms\DatabaseMysqlBase\isInsertSelectSafe
isInsertSelectSafe(array $insertOptions, array $selectOptions)
Definition: DatabaseMysqlBase.php:450